LLVM  12.0.0git
LTOCodeGenerator.cpp
Go to the documentation of this file.
1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassTimingInfo.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/LTO/LTO.h"
42 #include "llvm/Linker/Linker.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
48 #include "llvm/Support/Host.h"
50 #include "llvm/Support/Signals.h"
57 #include "llvm/Transforms/IPO.h"
63 #include <system_error>
64 using namespace llvm;
65 
67 #ifdef LLVM_VERSION_INFO
68  return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
69 #else
70  return PACKAGE_NAME " version " PACKAGE_VERSION;
71 #endif
72 }
73 
74 namespace llvm {
76  "lto-discard-value-names",
77  cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
78 #ifdef NDEBUG
79  cl::init(true),
80 #else
81  cl::init(false),
82 #endif
83  cl::Hidden);
84 
86  "lto-pass-remarks-with-hotness",
87  cl::desc("With PGO, include profile count in optimization remarks"),
88  cl::Hidden);
89 
91  RemarksFilename("lto-pass-remarks-output",
92  cl::desc("Output filename for pass remarks"),
93  cl::value_desc("filename"));
94 
96  RemarksPasses("lto-pass-remarks-filter",
97  cl::desc("Only record optimization remarks from passes whose "
98  "names match the given regular expression"),
99  cl::value_desc("regex"));
100 
102  "lto-pass-remarks-format",
103  cl::desc("The format used for serializing remarks (default: YAML)"),
104  cl::value_desc("format"), cl::init("yaml"));
105 
107  "lto-stats-file",
108  cl::desc("Save statistics to the specified file"),
109  cl::Hidden);
110 }
111 
113  : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
114  TheLinker(new Linker(*MergedModule)) {
116  Context.enableDebugTypeODRUniquing();
117  initializeLTOPasses();
118 }
119 
121 
122 // Initialize LTO passes. Please keep this function in sync with
123 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
124 // passes are initialized.
125 void LTOCodeGenerator::initializeLTOPasses() {
127 
152 }
153 
155  const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
156  for (int i = 0, e = undefs.size(); i != e; ++i)
157  AsmUndefinedRefs.insert(undefs[i]);
158 }
159 
161  assert(&Mod->getModule().getContext() == &Context &&
162  "Expected module in same context");
163 
164  bool ret = TheLinker->linkInModule(Mod->takeModule());
165  setAsmUndefinedRefs(Mod);
166 
167  // We've just changed the input, so let's make sure we verify it.
168  HasVerifiedInput = false;
169 
170  return !ret;
171 }
172 
173 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
174  assert(&Mod->getModule().getContext() == &Context &&
175  "Expected module in same context");
176 
177  AsmUndefinedRefs.clear();
178 
179  MergedModule = Mod->takeModule();
180  TheLinker = std::make_unique<Linker>(*MergedModule);
181  setAsmUndefinedRefs(&*Mod);
182 
183  // We've just changed the input, so let's make sure we verify it.
184  HasVerifiedInput = false;
185 }
186 
188  this->Options = Options;
189 }
190 
192  switch (Debug) {
194  EmitDwarfDebugInfo = false;
195  return;
196 
198  EmitDwarfDebugInfo = true;
199  return;
200  }
201  llvm_unreachable("Unknown debug format!");
202 }
203 
205  OptLevel = Level;
206  switch (OptLevel) {
207  case 0:
208  CGOptLevel = CodeGenOpt::None;
209  return;
210  case 1:
211  CGOptLevel = CodeGenOpt::Less;
212  return;
213  case 2:
214  CGOptLevel = CodeGenOpt::Default;
215  return;
216  case 3:
217  CGOptLevel = CodeGenOpt::Aggressive;
218  return;
219  }
220  llvm_unreachable("Unknown optimization level!");
221 }
222 
224  if (!determineTarget())
225  return false;
226 
227  // We always run the verifier once on the merged module.
228  verifyMergedModuleOnce();
229 
230  // mark which symbols can not be internalized
231  applyScopeRestrictions();
232 
233  // create output file
234  std::error_code EC;
235  ToolOutputFile Out(Path, EC, sys::fs::OF_None);
236  if (EC) {
237  std::string ErrMsg = "could not open bitcode file for writing: ";
238  ErrMsg += Path.str() + ": " + EC.message();
239  emitError(ErrMsg);
240  return false;
241  }
242 
243  // write bitcode to it
244  WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
245  Out.os().close();
246 
247  if (Out.os().has_error()) {
248  std::string ErrMsg = "could not write bitcode file: ";
249  ErrMsg += Path.str() + ": " + Out.os().error().message();
250  emitError(ErrMsg);
251  Out.os().clear_error();
252  return false;
253  }
254 
255  Out.keep();
256  return true;
257 }
258 
259 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
260  // make unique temp output file to put generated code
261  SmallString<128> Filename;
262  int FD;
263 
265  (FileType == CGFT_AssemblyFile ? "s" : "o");
266 
267  std::error_code EC =
268  sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
269  if (EC) {
270  emitError(EC.message());
271  return false;
272  }
273 
274  // generate object file
275  ToolOutputFile objFile(Filename, FD);
276 
277  bool genResult = compileOptimized(&objFile.os());
278  objFile.os().close();
279  if (objFile.os().has_error()) {
280  emitError((Twine("could not write object file: ") + Filename + ": " +
281  objFile.os().error().message())
282  .str());
283  objFile.os().clear_error();
284  sys::fs::remove(Twine(Filename));
285  return false;
286  }
287 
288  objFile.keep();
289  if (!genResult) {
290  sys::fs::remove(Twine(Filename));
291  return false;
292  }
293 
294  NativeObjectPath = Filename.c_str();
295  *Name = NativeObjectPath.c_str();
296  return true;
297 }
298 
299 std::unique_ptr<MemoryBuffer>
301  const char *name;
302  if (!compileOptimizedToFile(&name))
303  return nullptr;
304 
305  // read .o file into memory buffer
307  MemoryBuffer::getFile(name, -1, false);
308  if (std::error_code EC = BufferOrErr.getError()) {
309  emitError(EC.message());
310  sys::fs::remove(NativeObjectPath);
311  return nullptr;
312  }
313 
314  // remove temp files
315  sys::fs::remove(NativeObjectPath);
316 
317  return std::move(*BufferOrErr);
318 }
319 
320 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
321  bool DisableInline,
322  bool DisableGVNLoadPRE,
323  bool DisableVectorization) {
324  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
325  DisableVectorization))
326  return false;
327 
328  return compileOptimizedToFile(Name);
329 }
330 
331 std::unique_ptr<MemoryBuffer>
332 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
333  bool DisableGVNLoadPRE, bool DisableVectorization) {
334  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
335  DisableVectorization))
336  return nullptr;
337 
338  return compileOptimized();
339 }
340 
341 bool LTOCodeGenerator::determineTarget() {
342  if (TargetMach)
343  return true;
344 
345  TripleStr = MergedModule->getTargetTriple();
346  if (TripleStr.empty()) {
347  TripleStr = sys::getDefaultTargetTriple();
348  MergedModule->setTargetTriple(TripleStr);
349  }
350  llvm::Triple Triple(TripleStr);
351 
352  // create target machine from info for merged modules
353  std::string ErrMsg;
354  MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
355  if (!MArch) {
356  emitError(ErrMsg);
357  return false;
358  }
359 
360  // Construct LTOModule, hand over ownership of module and target. Use MAttr as
361  // the default set of features.
362  SubtargetFeatures Features(MAttr);
363  Features.getDefaultSubtargetFeatures(Triple);
364  FeatureStr = Features.getString();
365  // Set a default CPU for Darwin triples.
366  if (MCpu.empty() && Triple.isOSDarwin()) {
367  if (Triple.getArch() == llvm::Triple::x86_64)
368  MCpu = "core2";
369  else if (Triple.getArch() == llvm::Triple::x86)
370  MCpu = "yonah";
371  else if (Triple.getArch() == llvm::Triple::aarch64 ||
372  Triple.getArch() == llvm::Triple::aarch64_32)
373  MCpu = "cyclone";
374  }
375 
376  TargetMach = createTargetMachine();
377  assert(TargetMach && "Unable to create target machine");
378 
379  return true;
380 }
381 
382 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
383  assert(MArch && "MArch is not set!");
384  return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
385  TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
386 }
387 
388 // If a linkonce global is present in the MustPreserveSymbols, we need to make
389 // sure we honor this. To force the compiler to not drop it, we add it to the
390 // "llvm.compiler.used" global.
391 void LTOCodeGenerator::preserveDiscardableGVs(
392  Module &TheModule,
394  std::vector<GlobalValue *> Used;
395  auto mayPreserveGlobal = [&](GlobalValue &GV) {
396  if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
397  !mustPreserveGV(GV))
398  return;
399  if (GV.hasAvailableExternallyLinkage())
400  return emitWarning(
401  (Twine("Linker asked to preserve available_externally global: '") +
402  GV.getName() + "'").str());
403  if (GV.hasInternalLinkage())
404  return emitWarning((Twine("Linker asked to preserve internal global: '") +
405  GV.getName() + "'").str());
406  Used.push_back(&GV);
407  };
408  for (auto &GV : TheModule)
409  mayPreserveGlobal(GV);
410  for (auto &GV : TheModule.globals())
411  mayPreserveGlobal(GV);
412  for (auto &GV : TheModule.aliases())
413  mayPreserveGlobal(GV);
414 
415  if (Used.empty())
416  return;
417 
418  appendToCompilerUsed(TheModule, Used);
419 }
420 
421 void LTOCodeGenerator::applyScopeRestrictions() {
422  if (ScopeRestrictionsDone)
423  return;
424 
425  // Declare a callback for the internalize pass that will ask for every
426  // candidate GlobalValue if it can be internalized or not.
427  Mangler Mang;
428  SmallString<64> MangledName;
429  auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
430  // Unnamed globals can't be mangled, but they can't be preserved either.
431  if (!GV.hasName())
432  return false;
433 
434  // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
435  // with the linker supplied name, which on Darwin includes a leading
436  // underscore.
437  MangledName.clear();
438  MangledName.reserve(GV.getName().size() + 1);
439  Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
440  return MustPreserveSymbols.count(MangledName);
441  };
442 
443  // Preserve linkonce value on linker request
444  preserveDiscardableGVs(*MergedModule, mustPreserveGV);
445 
446  if (!ShouldInternalize)
447  return;
448 
449  if (ShouldRestoreGlobalsLinkage) {
450  // Record the linkage type of non-local symbols so they can be restored
451  // prior
452  // to module splitting.
453  auto RecordLinkage = [&](const GlobalValue &GV) {
454  if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
455  GV.hasName())
456  ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
457  };
458  for (auto &GV : *MergedModule)
459  RecordLinkage(GV);
460  for (auto &GV : MergedModule->globals())
461  RecordLinkage(GV);
462  for (auto &GV : MergedModule->aliases())
463  RecordLinkage(GV);
464  }
465 
466  // Update the llvm.compiler_used globals to force preserving libcalls and
467  // symbols referenced from asm
468  updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
469 
470  internalizeModule(*MergedModule, mustPreserveGV);
471 
472  ScopeRestrictionsDone = true;
473 }
474 
475 /// Restore original linkage for symbols that may have been internalized
476 void LTOCodeGenerator::restoreLinkageForExternals() {
477  if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
478  return;
479 
480  assert(ScopeRestrictionsDone &&
481  "Cannot externalize without internalization!");
482 
483  if (ExternalSymbols.empty())
484  return;
485 
486  auto externalize = [this](GlobalValue &GV) {
487  if (!GV.hasLocalLinkage() || !GV.hasName())
488  return;
489 
490  auto I = ExternalSymbols.find(GV.getName());
491  if (I == ExternalSymbols.end())
492  return;
493 
494  GV.setLinkage(I->second);
495  };
496 
497  llvm::for_each(MergedModule->functions(), externalize);
498  llvm::for_each(MergedModule->globals(), externalize);
499  llvm::for_each(MergedModule->aliases(), externalize);
500 }
501 
502 void LTOCodeGenerator::verifyMergedModuleOnce() {
503  // Only run on the first call.
504  if (HasVerifiedInput)
505  return;
506  HasVerifiedInput = true;
507 
508  bool BrokenDebugInfo = false;
509  if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
510  report_fatal_error("Broken module found, compilation aborted!");
511  if (BrokenDebugInfo) {
512  emitWarning("Invalid debug info found, debug info will be stripped");
513  StripDebugInfo(*MergedModule);
514  }
515 }
516 
517 void LTOCodeGenerator::finishOptimizationRemarks() {
518  if (DiagnosticOutputFile) {
519  DiagnosticOutputFile->keep();
520  // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
521  DiagnosticOutputFile->os().flush();
522  }
523 }
524 
525 /// Optimize merged modules using various IPO passes
526 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
527  bool DisableGVNLoadPRE,
528  bool DisableVectorization) {
529  if (!this->determineTarget())
530  return false;
531 
532  auto DiagFileOrErr =
535  if (!DiagFileOrErr) {
536  errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
537  report_fatal_error("Can't get an output file for the remarks");
538  }
539  DiagnosticOutputFile = std::move(*DiagFileOrErr);
540 
541  // Setup output file to emit statistics.
542  auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
543  if (!StatsFileOrErr) {
544  errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
545  report_fatal_error("Can't get an output file for the statistics");
546  }
547  StatsFile = std::move(StatsFileOrErr.get());
548 
549  // Currently there is no support for enabling whole program visibility via a
550  // linker option in the old LTO API, but this call allows it to be specified
551  // via the internal option. Must be done before WPD invoked via the optimizer
552  // pipeline run below.
553  updateVCallVisibilityInModule(*MergedModule,
554  /* WholeProgramVisibilityEnabledInLTO */ false);
555 
556  // We always run the verifier once on the merged module, the `DisableVerify`
557  // parameter only applies to subsequent verify.
558  verifyMergedModuleOnce();
559 
560  // Mark which symbols can not be internalized
561  this->applyScopeRestrictions();
562 
563  // Write LTOPostLink flag for passes that require all the modules.
564  MergedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
565 
566  // Instantiate the pass manager to organize the passes.
567  legacy::PassManager passes;
568 
569  // Add an appropriate DataLayout instance for this module...
570  MergedModule->setDataLayout(TargetMach->createDataLayout());
571 
572  passes.add(
573  createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
574 
575  Triple TargetTriple(TargetMach->getTargetTriple());
576  PassManagerBuilder PMB;
577  PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
578  PMB.LoopVectorize = !DisableVectorization;
579  PMB.SLPVectorize = !DisableVectorization;
580  if (!DisableInline)
581  PMB.Inliner = createFunctionInliningPass();
582  PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
583  if (Freestanding)
584  PMB.LibraryInfo->disableAllFunctions();
585  PMB.OptLevel = OptLevel;
586  PMB.VerifyInput = !DisableVerify;
587  PMB.VerifyOutput = !DisableVerify;
588 
589  PMB.populateLTOPassManager(passes);
590 
591  // Run our queue of passes all at once now, efficiently.
592  passes.run(*MergedModule);
593 
594  return true;
595 }
596 
598  if (!this->determineTarget())
599  return false;
600 
601  // We always run the verifier once on the merged module. If it has already
602  // been called in optimize(), this call will return early.
603  verifyMergedModuleOnce();
604 
605  legacy::PassManager preCodeGenPasses;
606 
607  // If the bitcode files contain ARC code and were compiled with optimization,
608  // the ObjCARCContractPass must be run, so do it unconditionally here.
609  preCodeGenPasses.add(createObjCARCContractPass());
610  preCodeGenPasses.run(*MergedModule);
611 
612  // Re-externalize globals that may have been internalized to increase scope
613  // for splitting
614  restoreLinkageForExternals();
615 
616  // Do code generation. We need to preserve the module in case the client calls
617  // writeMergedModules() after compilation, but we only need to allow this at
618  // parallelism level 1. This is achieved by having splitCodeGen return the
619  // original module at parallelism level 1 which we then assign back to
620  // MergedModule.
621  MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
622  [&]() { return createTargetMachine(); }, FileType,
623  ShouldRestoreGlobalsLinkage);
624 
625  // If statistics were requested, save them to the specified file or
626  // print them out after codegen.
627  if (StatsFile)
628  PrintStatisticsJSON(StatsFile->os());
629  else if (AreStatisticsEnabled())
630  PrintStatistics();
631 
633 
634  finishOptimizationRemarks();
635 
636  return true;
637 }
638 
640  for (StringRef Option : Options)
641  CodegenOptions.push_back(Option.str());
642 }
643 
645  // if options were requested, set them
646  if (!CodegenOptions.empty()) {
647  // ParseCommandLineOptions() expects argv[0] to be program name.
648  std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
649  for (std::string &Arg : CodegenOptions)
650  CodegenArgv.push_back(Arg.c_str());
651  cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
652  }
653 }
654 
655 
657  // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
659  switch (DI.getSeverity()) {
660  case DS_Error:
661  Severity = LTO_DS_ERROR;
662  break;
663  case DS_Warning:
664  Severity = LTO_DS_WARNING;
665  break;
666  case DS_Remark:
667  Severity = LTO_DS_REMARK;
668  break;
669  case DS_Note:
670  Severity = LTO_DS_NOTE;
671  break;
672  }
673  // Create the string that will be reported to the external diagnostic handler.
674  std::string MsgStorage;
675  raw_string_ostream Stream(MsgStorage);
676  DiagnosticPrinterRawOStream DP(Stream);
677  DI.print(DP);
678  Stream.flush();
679 
680  // If this method has been called it means someone has set up an external
681  // diagnostic handler. Assert on that.
682  assert(DiagHandler && "Invalid diagnostic handler");
683  (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
684 }
685 
686 namespace {
687 struct LTODiagnosticHandler : public DiagnosticHandler {
688  LTOCodeGenerator *CodeGenerator;
689  LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
690  : CodeGenerator(CodeGenPtr) {}
691  bool handleDiagnostics(const DiagnosticInfo &DI) override {
692  CodeGenerator->DiagnosticHandler(DI);
693  return true;
694  }
695 };
696 }
697 
698 void
700  void *Ctxt) {
701  this->DiagHandler = DiagHandler;
702  this->DiagContext = Ctxt;
703  if (!DiagHandler)
704  return Context.setDiagnosticHandler(nullptr);
705  // Register the LTOCodeGenerator stub in the LLVMContext to forward the
706  // diagnostic to the external DiagHandler.
707  Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this),
708  true);
709 }
710 
711 namespace {
712 class LTODiagnosticInfo : public DiagnosticInfo {
713  const Twine &Msg;
714 public:
715  LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
716  : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
717  void print(DiagnosticPrinter &DP) const override { DP << Msg; }
718 };
719 }
720 
721 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
722  if (DiagHandler)
723  (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
724  else
725  Context.diagnose(LTODiagnosticInfo(ErrMsg));
726 }
727 
728 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
729  if (DiagHandler)
730  (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
731  else
732  Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
733 }
void setDiagnosticHandler(std::unique_ptr< DiagnosticHandler > &&DH, bool RespectFilters=false)
setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler to provide custom d...
void initializeDCELegacyPassPass(PassRegistry &)
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (macOS, iOS, tvOS or watchOS).
Definition: Triple.h:477
This is the base class for diagnostic handling in LLVM.
std::unique_ptr< Module > splitCodeGen(std::unique_ptr< Module > M, ArrayRef< raw_pwrite_stream *> OSs, ArrayRef< llvm::raw_pwrite_stream *> BCOSs, const std::function< std::unique_ptr< TargetMachine >()> &TMFactory, CodeGenFileType FileType=CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
Definition: ParallelCG.cpp:39
void initializeOpenMPOptLegacyPassPass(PassRegistry &)
void initializeGlobalOptLegacyPassPass(PassRegistry &)
Represents either an error or a value T.
Definition: ErrorOr.h:56
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:248
LLVMContext & Context
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
void initializeInternalizeLegacyPassPass(PassRegistry &)
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:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
std::unique_ptr< MemoryBuffer > compileOptimized()
Compiles the merged optimized module into a single output file.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:67
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 initializeSimpleInlinerPass(PassRegistry &)
void initializeJumpThreadingPass(PassRegistry &)
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
lto_codegen_diagnostic_severity_t
Diagnostic severity.
Definition: lto.h:320
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
void enableDebugTypeODRUniquing()
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
std::string getString() const
Returns features as a string.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:176
void initializeGlobalDCELegacyPassPass(PassRegistry &)
iterator find(StringRef Key)
Definition: StringMap.h:218
void initializeAttributorCGSCCLegacyPassPass(PassRegistry &)
Expected< std::unique_ptr< ToolOutputFile > > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1489
bool addModule(struct LTOModule *)
Merge given module.
Implementation of the target library information.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
static const char * name
bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Optimizes the merged module.
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
void reserve(size_type N)
Definition: SmallVector.h:493
std::unique_ptr< Module > takeModule()
Definition: LTOModule.h:118
std::error_code error() const
Definition: raw_ostream.h:507
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
void initializeReversePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
static void externalize(GlobalValue *GV)
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
void initializePruneEHPass(PassRegistry &)
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, const char *EnvVar=nullptr, bool LongOptionsUseDoubleDash=false)
void setCodeGenDebugOptions(ArrayRef< StringRef > Opts)
Pass options to the driver and optimization passes.
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:991
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:253
void initializeArgPromotionPass(PassRegistry &)
std::unique_ptr< MemoryBuffer > compile(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
As with compile_to_file(), this function compiles the merged module into single output file...
Interface for custom diagnostic printing.
This header defines classes/functions to handle pass execution timing information with interfaces for...
bool writeMergedModules(StringRef Path)
Write the merged module to the file specified by the given path.
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:300
Pass * createObjCARCContractPass()
static const char * getVersionString()
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:358
void initializeAttributorLegacyPassPass(PassRegistry &)
This class provides the core functionality of linking in LLVM.
Definition: Linker.h:24
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
void reportAndResetTimings(raw_ostream *OutStream=nullptr)
If -time-passes has been specified, report the timings immediately and then reset the timers to zero...
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1491
Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition: LTO.cpp:1512
lto_debug_model
Definition: lto.h:79
void initializeGVNLegacyPassPass(PassRegistry &)
PassManager manages ModulePassManagers.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:427
This is the base abstract class for diagnostic reporting in the backend.
Emits an error if two values disagree, otherwise the resulting value is that of the operands...
Definition: Module.h:120
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:246
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::error_code getError() const
Definition: ErrorOr.h:153
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.
constexpr double e
Definition: MathExtras.h:58
void initializeSROALegacyPassPass(PassRegistry &)
void setOptLevel(unsigned OptLevel)
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void setTargetOptions(const TargetOptions &Options)
const Module & getModule() const
Definition: LTOModule.h:115
C++ class which implements the opaque lto_module_t type.
Definition: LTOModule.h:38
void initializeMemCpyOptLegacyPassPass(PassRegistry &)
void initializeConstantMergeLegacyPassPass(PassRegistry &)
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition: StringSet.h:33
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:45
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
Definition: raw_ostream.h:513
C++ class which implements the opaque lto_code_gen_t type.
void initializeGlobalsAAWrapperPassPass(PassRegistry &)
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
Definition: lto.h:336
const std::vector< StringRef > & getAsmUndefinedRefs()
Definition: LTOModule.h:157
void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
Definition: Statistic.cpp:200
cl::opt< std::string > LTOStatsFile("lto-stats-file", cl::desc("Save statistics to the specified file"), cl::Hidden)
Module.h This file contains the declarations for the Module class.
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:276
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
The access may modify the value stored in memory.
Manages the enabling and disabling of subtarget specific features.
void add(Pass *P) override
Add a pass to the queue of passes to run.
void initializeDAHPass(PassRegistry &)
#define NDEBUG
Definition: regutils.h:48
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Definition: Verifier.cpp:5511
Basic diagnostic printer that uses an underlying raw_ostream.
void DiagnosticHandler(const DiagnosticInfo &DI)
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
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:862
void initializePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
void initializeIPSCCPLegacyPassPass(PassRegistry &)
const char * c_str()
Definition: SmallString.h:295
#define I(x, y, z)
Definition: MD5.cpp:59
bool compile_to_file(const char **Name, bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Compile the merged module into a single output file; the path to output file is returned to the calle...
DiagnosticSeverity getSeverity() const
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void initializeInstructionCombiningPassPass(PassRegistry &)
void keep()
Indicate that the tool&#39;s job wrt this output file has been successful and the file should not be dele...
void close()
Manually flush the stream and close the file.
void updateCompilerUsed(Module &TheModule, const TargetMachine &TM, const StringSet<> &AsmUndefinedRefs)
Find all globals in TheModule that are referenced in AsmUndefinedRefs, as well as the user-supplied f...
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 setAsmUndefinedRefs(struct LTOModule *)
void initializeCFGSimplifyPassPass(PassRegistry &)
void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
Definition: Statistic.cpp:226
bool empty() const
Definition: StringMap.h:92
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:607
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
LTOCodeGenerator(LLVMContext &Context)
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
static cl::opt< bool, true > Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag))
void initializeLegacyLICMPassPass(PassRegistry &)
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:114
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1556
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:38
This pass exposes codegen information to IR-level passes.
void parseCodeGenDebugOptions()
Parse the options set in setCodeGenDebugOptions.
void updateVCallVisibilityInModule(Module &M, bool WholeProgramVisibilityEnabledInLTO)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
void setModule(std::unique_ptr< LTOModule > M)
Set the destination module.
void initializeMergedLoadStoreMotionLegacyPassPass(PassRegistry &)
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV, CallGraph *CG=nullptr)
Helper function to internalize functions and variables in a Module.
Definition: Internalize.h:70
bool AreStatisticsEnabled()
Check if statistics are enabled.
Definition: Statistic.cpp:131
iterator end()
Definition: StringMap.h:205
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
void clear_error()
Set the flag read by has_error() to false.
Definition: raw_ostream.h:524
Level
Definition: Debugify.cpp:34
void setDebugInfo(lto_debug_model)