LLVM  6.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"
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
66 }
67 
68 namespace {
69 
70 static cl::opt<int>
71  ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
72 
73 // Simple helper to save temporary files for debug.
74 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
75  unsigned count, StringRef Suffix) {
76  if (TempDir.empty())
77  return;
78  // User asked to save temps, let dump the bitcode file after import.
79  std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
80  std::error_code EC;
81  raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
82  if (EC)
83  report_fatal_error(Twine("Failed to open ") + SaveTempPath +
84  " to save optimized bitcode\n");
85  WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
86 }
87 
88 static const GlobalValueSummary *
89 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
90  // If there is any strong definition anywhere, get it.
91  auto StrongDefForLinker = llvm::find_if(
92  GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
93  auto Linkage = Summary->linkage();
96  });
97  if (StrongDefForLinker != GVSummaryList.end())
98  return StrongDefForLinker->get();
99  // Get the first *linker visible* definition for this global in the summary
100  // list.
101  auto FirstDefForLinker = llvm::find_if(
102  GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
103  auto Linkage = Summary->linkage();
105  });
106  // Extern templates can be emitted as available_externally.
107  if (FirstDefForLinker == GVSummaryList.end())
108  return nullptr;
109  return FirstDefForLinker->get();
110 }
111 
112 // Populate map of GUID to the prevailing copy for any multiply defined
113 // symbols. Currently assume first copy is prevailing, or any strong
114 // definition. Can be refined with Linker information in the future.
115 static void computePrevailingCopies(
116  const ModuleSummaryIndex &Index,
118  auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
119  return GVSummaryList.size() > 1;
120  };
121 
122  for (auto &I : Index) {
123  if (HasMultipleCopies(I.second.SummaryList))
124  PrevailingCopy[I.first] =
125  getFirstDefinitionForLinker(I.second.SummaryList);
126  }
127 }
128 
130 generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
131  StringMap<MemoryBufferRef> ModuleMap;
132  for (auto &ModuleBuffer : Modules) {
133  assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
134  ModuleMap.end() &&
135  "Expect unique Buffer Identifier");
136  ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
137  }
138  return ModuleMap;
139 }
140 
141 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
142  if (renameModuleForThinLTO(TheModule, Index))
143  report_fatal_error("renameModuleForThinLTO failed");
144 }
145 
146 namespace {
147 class ThinLTODiagnosticInfo : public DiagnosticInfo {
148  const Twine &Msg;
149 public:
150  ThinLTODiagnosticInfo(const Twine &DiagMsg,
151  DiagnosticSeverity Severity = DS_Error)
152  : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
153  void print(DiagnosticPrinter &DP) const override { DP << Msg; }
154 };
155 }
156 
157 /// Verify the module and strip broken debug info.
158 static void verifyLoadedModule(Module &TheModule) {
159  bool BrokenDebugInfo = false;
160  if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
161  report_fatal_error("Broken module found, compilation aborted!");
162  if (BrokenDebugInfo) {
163  TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
164  "Invalid debug info found, debug info will be stripped", DS_Warning));
165  StripDebugInfo(TheModule);
166  }
167 }
168 
169 static std::unique_ptr<Module>
170 loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
171  bool Lazy, bool IsImporting) {
172  SMDiagnostic Err;
173  Expected<std::unique_ptr<Module>> ModuleOrErr =
174  Lazy
175  ? getLazyBitcodeModule(Buffer, Context,
176  /* ShouldLazyLoadMetadata */ true, IsImporting)
177  : parseBitcodeFile(Buffer, Context);
178  if (!ModuleOrErr) {
179  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
181  SourceMgr::DK_Error, EIB.message());
182  Err.print("ThinLTO", errs());
183  });
184  report_fatal_error("Can't load module, abort.");
185  }
186  if (!Lazy)
187  verifyLoadedModule(*ModuleOrErr.get());
188  return std::move(ModuleOrErr.get());
189 }
190 
191 static void
192 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
193  StringMap<MemoryBufferRef> &ModuleMap,
194  const FunctionImporter::ImportMapTy &ImportList) {
195  auto Loader = [&](StringRef Identifier) {
196  return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
197  /*Lazy=*/true, /*IsImporting*/ true);
198  };
199 
200  FunctionImporter Importer(Index, Loader);
201  Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
202  if (!Result) {
203  handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
205  SourceMgr::DK_Error, EIB.message());
206  Err.print("ThinLTO", errs());
207  });
208  report_fatal_error("importFunctions failed");
209  }
210  // Verify again after cross-importing.
211  verifyLoadedModule(TheModule);
212 }
213 
214 static void optimizeModule(Module &TheModule, TargetMachine &TM,
215  unsigned OptLevel, bool Freestanding) {
216  // Populate the PassManager
217  PassManagerBuilder PMB;
219  if (Freestanding)
222  // FIXME: should get it from the bitcode?
223  PMB.OptLevel = OptLevel;
224  PMB.LoopVectorize = true;
225  PMB.SLPVectorize = true;
226  // Already did this in verifyLoadedModule().
227  PMB.VerifyInput = false;
228  PMB.VerifyOutput = false;
229 
231 
232  // Add the TTI (required to inform the vectorizer about register size for
233  // instance)
235 
236  // Add optimizations
238 
239  PM.run(TheModule);
240 }
241 
242 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
244 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
245  const Triple &TheTriple) {
246  DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
247  for (auto &Entry : PreservedSymbols) {
248  StringRef Name = Entry.first();
249  if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
250  Name = Name.drop_front();
251  GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
252  }
253  return GUIDPreservedSymbols;
254 }
255 
256 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
257  TargetMachine &TM) {
258  SmallVector<char, 128> OutputBuffer;
259 
260  // CodeGen
261  {
262  raw_svector_ostream OS(OutputBuffer);
264 
265  // If the bitcode files contain ARC code and were compiled with optimization,
266  // the ObjCARCContractPass must be run, so do it unconditionally here.
268 
269  // Setup the codegen now.
271  /* DisableVerify */ true))
272  report_fatal_error("Failed to setup codegen");
273 
274  // Run codegen now. resulting binary is in OutputBuffer.
275  PM.run(TheModule);
276  }
277  return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
278 }
279 
280 /// Manage caching for a single Module.
281 class ModuleCacheEntry {
282  SmallString<128> EntryPath;
283 
284 public:
285  // Create a cache entry. This compute a unique hash for the Module considering
286  // the current list of export/import, and offer an interface to query to
287  // access the content in the cache.
288  ModuleCacheEntry(
289  StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
290  const FunctionImporter::ImportMapTy &ImportList,
291  const FunctionImporter::ExportSetTy &ExportList,
292  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
293  const GVSummaryMapTy &DefinedFunctions,
294  const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
295  bool Freestanding, const TargetMachineBuilder &TMBuilder) {
296  if (CachePath.empty())
297  return;
298 
299  if (!Index.modulePaths().count(ModuleID))
300  // The module does not have an entry, it can't have a hash at all
301  return;
302 
303  // Compute the unique hash for this entry
304  // This is based on the current compiler version, the module itself, the
305  // export list, the hash for every single module in the import list, the
306  // list of ResolvedODR for the module, and the list of preserved symbols.
307 
308  // Include the hash for the current module
309  auto ModHash = Index.getModuleHash(ModuleID);
310 
311  if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
312  // No hash entry, no caching!
313  return;
314 
315  SHA1 Hasher;
316 
317  // Include the parts of the LTO configuration that affect code generation.
318  auto AddString = [&](StringRef Str) {
319  Hasher.update(Str);
320  Hasher.update(ArrayRef<uint8_t>{0});
321  };
322  auto AddUnsigned = [&](unsigned I) {
323  uint8_t Data[4];
324  Data[0] = I;
325  Data[1] = I >> 8;
326  Data[2] = I >> 16;
327  Data[3] = I >> 24;
328  Hasher.update(ArrayRef<uint8_t>{Data, 4});
329  };
330 
331  // Start with the compiler revision
332  Hasher.update(LLVM_VERSION_STRING);
333 #ifdef LLVM_REVISION
334  Hasher.update(LLVM_REVISION);
335 #endif
336 
337  // Hash the optimization level and the target machine settings.
338  AddString(TMBuilder.MCpu);
339  // FIXME: Hash more of Options. For now all clients initialize Options from
340  // command-line flags (which is unsupported in production), but may set
341  // RelaxELFRelocations. The clang driver can also pass FunctionSections,
342  // DataSections and DebuggerTuning via command line flags.
343  AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
344  AddUnsigned(TMBuilder.Options.FunctionSections);
345  AddUnsigned(TMBuilder.Options.DataSections);
346  AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
347  AddString(TMBuilder.MAttr);
348  if (TMBuilder.RelocModel)
349  AddUnsigned(*TMBuilder.RelocModel);
350  AddUnsigned(TMBuilder.CGOptLevel);
351  AddUnsigned(OptLevel);
352  AddUnsigned(Freestanding);
353 
354  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
355  for (auto F : ExportList)
356  // The export list can impact the internalization, be conservative here
357  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
358 
359  // Include the hash for every module we import functions from
360  for (auto &Entry : ImportList) {
361  auto ModHash = Index.getModuleHash(Entry.first());
362  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
363  }
364 
365  // Include the hash for the resolved ODR.
366  for (auto &Entry : ResolvedODR) {
367  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
368  sizeof(GlobalValue::GUID)));
369  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
370  sizeof(GlobalValue::LinkageTypes)));
371  }
372 
373  // Include the hash for the preserved symbols.
374  for (auto &Entry : PreservedSymbols) {
375  if (DefinedFunctions.count(Entry))
376  Hasher.update(
377  ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
378  }
379 
380  // This choice of file name allows the cache to be pruned (see pruneCache()
381  // in include/llvm/Support/CachePruning.h).
382  sys::path::append(EntryPath, CachePath,
383  "llvmcache-" + toHex(Hasher.result()));
384  }
385 
386  // Access the path to this entry in the cache.
387  StringRef getEntryPath() { return EntryPath; }
388 
389  // Try loading the buffer for this cache entry.
390  ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
391  if (EntryPath.empty())
392  return std::error_code();
393  return MemoryBuffer::getFile(EntryPath);
394  }
395 
396  // Cache the Produced object file
397  void write(const MemoryBuffer &OutputBuffer) {
398  if (EntryPath.empty())
399  return;
400 
401  // Write to a temporary to avoid race condition
402  SmallString<128> TempFilename;
403  int TempFD;
404  std::error_code EC =
405  sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
406  if (EC) {
407  errs() << "Error: " << EC.message() << "\n";
408  report_fatal_error("ThinLTO: Can't get a temporary file");
409  }
410  {
411  raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
412  OS << OutputBuffer.getBuffer();
413  }
414  // Rename to final destination (hopefully race condition won't matter here)
415  EC = sys::fs::rename(TempFilename, EntryPath);
416  if (EC) {
417  sys::fs::remove(TempFilename);
418  raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
419  if (EC)
420  report_fatal_error(Twine("Failed to open ") + EntryPath +
421  " to save cached entry\n");
422  OS << OutputBuffer.getBuffer();
423  }
424  }
425 };
426 
427 static std::unique_ptr<MemoryBuffer>
428 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
430  const FunctionImporter::ImportMapTy &ImportList,
431  const FunctionImporter::ExportSetTy &ExportList,
432  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
433  const GVSummaryMapTy &DefinedGlobals,
434  const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
435  bool DisableCodeGen, StringRef SaveTempsDir,
436  bool Freestanding, unsigned OptLevel, unsigned count) {
437 
438  // "Benchmark"-like optimization: single-source case
439  bool SingleModule = (ModuleMap.size() == 1);
440 
441  if (!SingleModule) {
442  promoteModule(TheModule, Index);
443 
444  // Apply summary-based LinkOnce/Weak resolution decisions.
445  thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
446 
447  // Save temps: after promotion.
448  saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
449  }
450 
451  // Be friendly and don't nuke totally the module when the client didn't
452  // supply anything to preserve.
453  if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
454  // Apply summary-based internalization decisions.
455  thinLTOInternalizeModule(TheModule, DefinedGlobals);
456  }
457 
458  // Save internalized bitcode
459  saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
460 
461  if (!SingleModule) {
462  crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
463 
464  // Save temps: after cross-module import.
465  saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
466  }
467 
468  optimizeModule(TheModule, TM, OptLevel, Freestanding);
469 
470  saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
471 
472  if (DisableCodeGen) {
473  // Configured to stop before CodeGen, serialize the bitcode and return.
474  SmallVector<char, 128> OutputBuffer;
475  {
476  raw_svector_ostream OS(OutputBuffer);
477  ProfileSummaryInfo PSI(TheModule);
478  auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
479  WriteBitcodeToFile(&TheModule, OS, true, &Index);
480  }
481  return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
482  }
483 
484  return codegenModule(TheModule, TM);
485 }
486 
487 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
488 /// for caching, and in the \p Index for application during the ThinLTO
489 /// backends. This is needed for correctness for exported symbols (ensure
490 /// at least one copy kept) and a compile-time optimization (to drop duplicate
491 /// copies when possible).
492 static void resolveWeakForLinkerInIndex(
493  ModuleSummaryIndex &Index,
494  StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
495  &ResolvedODR) {
496 
498  computePrevailingCopies(Index, PrevailingCopy);
499 
500  auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
501  const auto &Prevailing = PrevailingCopy.find(GUID);
502  // Not in map means that there was only one copy, which must be prevailing.
503  if (Prevailing == PrevailingCopy.end())
504  return true;
505  return Prevailing->second == S;
506  };
507 
508  auto recordNewLinkage = [&](StringRef ModuleIdentifier,
509  GlobalValue::GUID GUID,
510  GlobalValue::LinkageTypes NewLinkage) {
511  ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
512  };
513 
514  thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
515 }
516 
517 // Initialize the TargetMachine builder for a given Triple
518 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
519  const Triple &TheTriple) {
520  // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
521  // FIXME this looks pretty terrible...
522  if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
523  if (TheTriple.getArch() == llvm::Triple::x86_64)
524  TMBuilder.MCpu = "core2";
525  else if (TheTriple.getArch() == llvm::Triple::x86)
526  TMBuilder.MCpu = "yonah";
527  else if (TheTriple.getArch() == llvm::Triple::aarch64)
528  TMBuilder.MCpu = "cyclone";
529  }
530  TMBuilder.TheTriple = std::move(TheTriple);
531 }
532 
533 } // end anonymous namespace
534 
536  ThinLTOBuffer Buffer(Data, Identifier);
538  StringRef TripleStr;
540  Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
541 
542  if (TripleOrErr)
543  TripleStr = *TripleOrErr;
544 
545  Triple TheTriple(TripleStr);
546 
547  if (Modules.empty())
548  initTMBuilder(TMBuilder, Triple(TheTriple));
549  else if (TMBuilder.TheTriple != TheTriple) {
550  if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
551  report_fatal_error("ThinLTO modules with incompatible triples not "
552  "supported");
553  initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
554  }
555 
556  Modules.push_back(Buffer);
557 }
558 
560  PreservedSymbols.insert(Name);
561 }
562 
564  // FIXME: At the moment, we don't take advantage of this extra information,
565  // we're conservatively considering cross-references as preserved.
566  // CrossReferencedSymbols.insert(Name);
567  PreservedSymbols.insert(Name);
568 }
569 
570 // TargetMachine factory
571 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
572  std::string ErrMsg;
573  const Target *TheTarget =
574  TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
575  if (!TheTarget) {
576  report_fatal_error("Can't load target for this Triple: " + ErrMsg);
577  }
578 
579  // Use MAttr as the default set of features.
581  Features.getDefaultSubtargetFeatures(TheTriple);
582  std::string FeatureStr = Features.getString();
583 
584  return std::unique_ptr<TargetMachine>(
585  TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
586  RelocModel, None, CGOptLevel));
587 }
588 
589 /**
590  * Produce the combined summary index from all the bitcode files:
591  * "thin-link".
592  */
593 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
594  std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
595  llvm::make_unique<ModuleSummaryIndex>();
596  uint64_t NextModuleId = 0;
597  for (auto &ModuleBuffer : Modules) {
598  if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
599  *CombinedIndex, NextModuleId++)) {
600  // FIXME diagnose
602  std::move(Err), errs(),
603  "error: can't create module summary index for buffer: ");
604  return nullptr;
605  }
606  }
607  return CombinedIndex;
608 }
609 
610 /**
611  * Perform promotion and renaming of exported internal functions.
612  * Index is updated to reflect linkage changes from weak resolution.
613  */
615  ModuleSummaryIndex &Index) {
616  auto ModuleCount = Index.modulePaths().size();
617  auto ModuleIdentifier = TheModule.getModuleIdentifier();
618 
619  // Collect for each module the list of function it defines (GUID -> Summary).
620  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
621  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
622 
623  // Convert the preserved symbols set from string to GUID
624  auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
625  PreservedSymbols, Triple(TheModule.getTargetTriple()));
626 
627  // Compute "dead" symbols, we don't want to import/export these!
628  computeDeadSymbols(Index, GUIDPreservedSymbols);
629 
630  // Generate import/export list
631  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
632  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
633  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
634  ExportLists);
635 
636  // Resolve LinkOnce/Weak symbols.
638  resolveWeakForLinkerInIndex(Index, ResolvedODR);
639 
641  TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
642 
643  // Promote the exported values in the index, so that they are promoted
644  // in the module.
645  auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
646  const auto &ExportList = ExportLists.find(ModuleIdentifier);
647  return (ExportList != ExportLists.end() &&
648  ExportList->second.count(GUID)) ||
649  GUIDPreservedSymbols.count(GUID);
650  };
651  thinLTOInternalizeAndPromoteInIndex(Index, isExported);
652 
653  promoteModule(TheModule, Index);
654 }
655 
656 /**
657  * Perform cross-module importing for the module identified by ModuleIdentifier.
658  */
660  ModuleSummaryIndex &Index) {
661  auto ModuleMap = generateModuleMap(Modules);
662  auto ModuleCount = Index.modulePaths().size();
663 
664  // Collect for each module the list of function it defines (GUID -> Summary).
665  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
666  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
667 
668  // Convert the preserved symbols set from string to GUID
669  auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
670  PreservedSymbols, Triple(TheModule.getTargetTriple()));
671 
672  // Compute "dead" symbols, we don't want to import/export these!
673  computeDeadSymbols(Index, GUIDPreservedSymbols);
674 
675  // Generate import/export list
676  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
677  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
678  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
679  ExportLists);
680  auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
681 
682  crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
683 }
684 
685 /**
686  * Compute the list of summaries needed for importing into module.
687  */
689  StringRef ModulePath, ModuleSummaryIndex &Index,
690  std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
691  auto ModuleCount = Index.modulePaths().size();
692 
693  // Collect for each module the list of function it defines (GUID -> Summary).
694  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
695  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
696 
697  // Generate import/export list
698  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
699  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
700  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
701  ExportLists);
702 
703  llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
704  ImportLists[ModulePath],
705  ModuleToSummariesForIndex);
706 }
707 
708 /**
709  * Emit the list of files needed for importing into module.
710  */
712  StringRef OutputName,
713  ModuleSummaryIndex &Index) {
714  auto ModuleCount = Index.modulePaths().size();
715 
716  // Collect for each module the list of function it defines (GUID -> Summary).
717  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
718  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
719 
720  // Generate import/export list
721  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
722  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
723  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
724  ExportLists);
725 
726  std::error_code EC;
727  if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
728  report_fatal_error(Twine("Failed to open ") + OutputName +
729  " to save imports lists\n");
730 }
731 
732 /**
733  * Perform internalization. Index is updated to reflect linkage changes.
734  */
736  ModuleSummaryIndex &Index) {
737  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
738  auto ModuleCount = Index.modulePaths().size();
739  auto ModuleIdentifier = TheModule.getModuleIdentifier();
740 
741  // Convert the preserved symbols set from string to GUID
742  auto GUIDPreservedSymbols =
743  computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
744 
745  // Collect for each module the list of function it defines (GUID -> Summary).
746  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
747  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
748 
749  // Compute "dead" symbols, we don't want to import/export these!
750  computeDeadSymbols(Index, GUIDPreservedSymbols);
751 
752  // Generate import/export list
753  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
754  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
755  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
756  ExportLists);
757  auto &ExportList = ExportLists[ModuleIdentifier];
758 
759  // Be friendly and don't nuke totally the module when the client didn't
760  // supply anything to preserve.
761  if (ExportList.empty() && GUIDPreservedSymbols.empty())
762  return;
763 
764  // Internalization
765  auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
766  const auto &ExportList = ExportLists.find(ModuleIdentifier);
767  return (ExportList != ExportLists.end() &&
768  ExportList->second.count(GUID)) ||
769  GUIDPreservedSymbols.count(GUID);
770  };
771  thinLTOInternalizeAndPromoteInIndex(Index, isExported);
772  thinLTOInternalizeModule(TheModule,
773  ModuleToDefinedGVSummaries[ModuleIdentifier]);
774 }
775 
776 /**
777  * Perform post-importing ThinLTO optimizations.
778  */
780  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
781 
782  // Optimize now
783  optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
784 }
785 
786 /**
787  * Perform ThinLTO CodeGen.
788  */
789 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
790  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
791  return codegenModule(TheModule, *TMBuilder.create());
792 }
793 
794 /// Write out the generated object file, either from CacheEntryPath or from
795 /// OutputBuffer, preferring hard-link when possible.
796 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
797 static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
798  StringRef SavedObjectsDirectoryPath,
799  const MemoryBuffer &OutputBuffer) {
800  SmallString<128> OutputPath(SavedObjectsDirectoryPath);
801  llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
802  OutputPath.c_str(); // Ensure the string is null terminated.
803  if (sys::fs::exists(OutputPath))
804  sys::fs::remove(OutputPath);
805 
806  // We don't return a memory buffer to the linker, just a list of files.
807  if (!CacheEntryPath.empty()) {
808  // Cache is enabled, hard-link the entry (or copy if hard-link fails).
809  auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
810  if (!Err)
811  return OutputPath.str();
812  // Hard linking failed, try to copy.
813  Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
814  if (!Err)
815  return OutputPath.str();
816  // Copy failed (could be because the CacheEntry was removed from the cache
817  // in the meantime by another process), fall back and try to write down the
818  // buffer to the output.
819  errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
820  << "' to '" << OutputPath << "'\n";
821  }
822  // No cache entry, just write out the buffer.
823  std::error_code Err;
824  raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
825  if (Err)
826  report_fatal_error("Can't open output '" + OutputPath + "'\n");
827  OS << OutputBuffer.getBuffer();
828  return OutputPath.str();
829 }
830 
831 // Main entry point for the ThinLTO processing
833  // Prepare the resulting object vector
834  assert(ProducedBinaries.empty() && "The generator should not be reused");
835  if (SavedObjectsDirectoryPath.empty())
836  ProducedBinaries.resize(Modules.size());
837  else {
838  sys::fs::create_directories(SavedObjectsDirectoryPath);
839  bool IsDir;
840  sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
841  if (!IsDir)
842  report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
843  ProducedBinaryFiles.resize(Modules.size());
844  }
845 
846  if (CodeGenOnly) {
847  // Perform only parallel codegen and return.
848  ThreadPool Pool;
849  int count = 0;
850  for (auto &ModuleBuffer : Modules) {
851  Pool.async([&](int count) {
854 
855  // Parse module now
856  auto TheModule =
857  loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
858  /*IsImporting*/ false);
859 
860  // CodeGen
861  auto OutputBuffer = codegen(*TheModule);
862  if (SavedObjectsDirectoryPath.empty())
863  ProducedBinaries[count] = std::move(OutputBuffer);
864  else
865  ProducedBinaryFiles[count] = writeGeneratedObject(
866  count, "", SavedObjectsDirectoryPath, *OutputBuffer);
867  }, count++);
868  }
869 
870  return;
871  }
872 
873  // Sequential linking phase
874  auto Index = linkCombinedIndex();
875 
876  // Save temps: index.
877  if (!SaveTempsDir.empty()) {
878  auto SaveTempPath = SaveTempsDir + "index.bc";
879  std::error_code EC;
880  raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
881  if (EC)
882  report_fatal_error(Twine("Failed to open ") + SaveTempPath +
883  " to save optimized bitcode\n");
884  WriteIndexToFile(*Index, OS);
885  }
886 
887 
888  // Prepare the module map.
889  auto ModuleMap = generateModuleMap(Modules);
890  auto ModuleCount = Modules.size();
891 
892  // Collect for each module the list of function it defines (GUID -> Summary).
893  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
894  Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
895 
896  // Convert the preserved symbols set from string to GUID, this is needed for
897  // computing the caching hash and the internalization.
898  auto GUIDPreservedSymbols =
899  computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
900 
901  // Compute "dead" symbols, we don't want to import/export these!
902  computeDeadSymbols(*Index, GUIDPreservedSymbols);
903 
904  // Collect the import/export lists for all modules from the call-graph in the
905  // combined index.
906  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
907  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
908  ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
909  ExportLists);
910 
911  // We use a std::map here to be able to have a defined ordering when
912  // producing a hash for the cache entry.
913  // FIXME: we should be able to compute the caching hash for the entry based
914  // on the index, and nuke this map.
916 
917  // Resolve LinkOnce/Weak symbols, this has to be computed early because it
918  // impacts the caching.
919  resolveWeakForLinkerInIndex(*Index, ResolvedODR);
920 
921  auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
922  const auto &ExportList = ExportLists.find(ModuleIdentifier);
923  return (ExportList != ExportLists.end() &&
924  ExportList->second.count(GUID)) ||
925  GUIDPreservedSymbols.count(GUID);
926  };
927 
928  // Use global summary-based analysis to identify symbols that can be
929  // internalized (because they aren't exported or preserved as per callback).
930  // Changes are made in the index, consumed in the ThinLTO backends.
931  thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
932 
933  // Make sure that every module has an entry in the ExportLists and
934  // ResolvedODR maps to enable threaded access to these maps below.
935  for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
936  ExportLists[DefinedGVSummaries.first()];
937  ResolvedODR[DefinedGVSummaries.first()];
938  }
939 
940  // Compute the ordering we will process the inputs: the rough heuristic here
941  // is to sort them per size so that the largest module get schedule as soon as
942  // possible. This is purely a compile-time optimization.
943  std::vector<int> ModulesOrdering;
944  ModulesOrdering.resize(Modules.size());
945  std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
946  std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
947  [&](int LeftIndex, int RightIndex) {
948  auto LSize = Modules[LeftIndex].getBuffer().size();
949  auto RSize = Modules[RightIndex].getBuffer().size();
950  return LSize > RSize;
951  });
952 
953  // Parallel optimizer + codegen
954  {
955  ThreadPool Pool(ThreadCount);
956  for (auto IndexCount : ModulesOrdering) {
957  auto &ModuleBuffer = Modules[IndexCount];
958  Pool.async([&](int count) {
959  auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
960  auto &ExportList = ExportLists[ModuleIdentifier];
961 
962  auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
963 
964  // The module may be cached, this helps handling it.
965  ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
966  ImportLists[ModuleIdentifier], ExportList,
967  ResolvedODR[ModuleIdentifier],
968  DefinedFunctions, GUIDPreservedSymbols,
969  OptLevel, Freestanding, TMBuilder);
970  auto CacheEntryPath = CacheEntry.getEntryPath();
971 
972  {
973  auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
974  DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
975  << CacheEntryPath << "' for buffer " << count << " "
976  << ModuleIdentifier << "\n");
977 
978  if (ErrOrBuffer) {
979  // Cache Hit!
980  if (SavedObjectsDirectoryPath.empty())
981  ProducedBinaries[count] = std::move(ErrOrBuffer.get());
982  else
983  ProducedBinaryFiles[count] = writeGeneratedObject(
984  count, CacheEntryPath, SavedObjectsDirectoryPath,
985  *ErrOrBuffer.get());
986  return;
987  }
988  }
989 
992  Context.enableDebugTypeODRUniquing();
993  auto DiagFileOrErr = lto::setupOptimizationRemarks(
995  if (!DiagFileOrErr) {
996  errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
997  report_fatal_error("ThinLTO: Can't get an output file for the "
998  "remarks");
999  }
1000 
1001  // Parse module now
1002  auto TheModule =
1003  loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1004  /*IsImporting*/ false);
1005 
1006  // Save temps: original file.
1007  saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1008 
1009  auto &ImportList = ImportLists[ModuleIdentifier];
1010  // Run the main process now, and generates a binary
1011  auto OutputBuffer = ProcessThinLTOModule(
1012  *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1013  ExportList, GUIDPreservedSymbols,
1014  ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1015  DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
1016 
1017  // Commit to the cache (if enabled)
1018  CacheEntry.write(*OutputBuffer);
1019 
1020  if (SavedObjectsDirectoryPath.empty()) {
1021  // We need to generated a memory buffer for the linker.
1022  if (!CacheEntryPath.empty()) {
1023  // Cache is enabled, reload from the cache
1024  // We do this to lower memory pressuree: the buffer is on the heap
1025  // and releasing it frees memory that can be used for the next input
1026  // file. The final binary link will read from the VFS cache
1027  // (hopefully!) or from disk if the memory pressure wasn't too high.
1028  auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1029  if (auto EC = ReloadedBufferOrErr.getError()) {
1030  // On error, keeping the preexisting buffer and printing a
1031  // diagnostic is more friendly than just crashing.
1032  errs() << "error: can't reload cached file '" << CacheEntryPath
1033  << "': " << EC.message() << "\n";
1034  } else {
1035  OutputBuffer = std::move(*ReloadedBufferOrErr);
1036  }
1037  }
1038  ProducedBinaries[count] = std::move(OutputBuffer);
1039  return;
1040  }
1041  ProducedBinaryFiles[count] = writeGeneratedObject(
1042  count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
1043  }, IndexCount);
1044  }
1045  }
1046 
1047  pruneCache(CacheOptions.Path, CacheOptions.Policy);
1048 
1049  // If statistics were requested, print them out now.
1053 }
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, TargetMachine::CodeGenFileType FileType)
Definition: ParallelCG.cpp:29
void computeDeadSymbols(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Compute all the symbols that are "dead": i.e these that can&#39;t be reached in the graph from any of the...
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:470
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:951
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:233
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.
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1184
LLVMContext & Context
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
StringRef getBuffer() const
Definition: MemoryBuffer.h:59
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:483
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
Definition: SourceMgr.cpp:345
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: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...
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: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.
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:337
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:489
bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition: Path.cpp:1054
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:813
F(f)
A class that wrap the SHA1 algorithm.
Definition: SHA1.h:29
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
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
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:54
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.
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::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:947
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.
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:237
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:285
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:332
unsigned FunctionSections
Emit functions into separate sections.
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Definition: ThreadPool.h:36
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:874
PassManager manages ModulePassManagers.
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:975
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:406
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:363
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.
virtual TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
bool isWeakForLinker() const
Definition: GlobalValue.h:447
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:841
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:598
Function and variable summary information to aid decisions and implementation of importing.
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 occured, 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:208
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.
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 it requires that all errors be handled by the given han...
Definition: Error.h:889
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:285
reference get()
Returns a reference to the stored T value.
Definition: Error.h:517
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const FunctionImporter::ImportMapTy &ModuleImports)
Emit into OutputFilename the files module ModulePath will import from.
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:174
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:224
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 ...
std::string toHex(StringRef Input)
Convert buffer Input to its hexadecimal representation.
Definition: StringExtras.h:93
StringRef getBufferIdentifier() const
Definition: MemoryBuffer.h:172
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:491
unsigned RelaxELFRelocations
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, CodeGenFileType, bool=true, MachineModuleInfo *MMI=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Definition: Verifier.cpp:4638
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:361
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:308
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:866
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< 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.
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())
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...
cl::opt< Reloc::Model > RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::values(clEnumValN(Reloc::Static, "static", "Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", "Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", "Relocatable external references, non-relocatable code"), clEnumValN(Reloc::ROPI, "ropi", "Code and read-only data relocatable, accessed PC-relative"), clEnumValN(Reloc::RWPI, "rwpi", "Read-write data relocatable, accessed relative to static base"), clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi", "Combination of ropi and rwpi")))
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:57
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:199
This pass exposes codegen information to IR-level passes.
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1039
bool AreStatisticsEnabled()
Check if statistics are enabled.
Definition: Statistic.cpp:112
iterator end()
Definition: StringMap.h:322
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:343
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:233