LLVM  9.0.0svn
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"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/PassTimingInfo.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LTO/LTO.h"
41 #include "llvm/Linker/Linker.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
47 #include "llvm/Support/Host.h"
49 #include "llvm/Support/Signals.h"
56 #include "llvm/Transforms/IPO.h"
61 #include <system_error>
62 using namespace llvm;
63 
65 #ifdef LLVM_VERSION_INFO
66  return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 #else
68  return PACKAGE_NAME " version " PACKAGE_VERSION;
69 #endif
70 }
71 
72 namespace llvm {
74  "lto-discard-value-names",
75  cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
76 #ifdef NDEBUG
77  cl::init(true),
78 #else
79  cl::init(false),
80 #endif
81  cl::Hidden);
82 
84  LTORemarksFilename("lto-pass-remarks-output",
85  cl::desc("Output filename for pass remarks"),
86  cl::value_desc("filename"));
87 
89  LTORemarksPasses("lto-pass-remarks-filter",
90  cl::desc("Only record optimization remarks from passes "
91  "whose names match the given regular expression"),
92  cl::value_desc("regex"));
93 
95  "lto-pass-remarks-with-hotness",
96  cl::desc("With PGO, include profile count in optimization remarks"),
97  cl::Hidden);
98 
100  "lto-stats-file",
101  cl::desc("Save statistics to the specified file"),
102  cl::Hidden);
103 }
104 
106  : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
107  TheLinker(new Linker(*MergedModule)) {
109  Context.enableDebugTypeODRUniquing();
110  initializeLTOPasses();
111 }
112 
114 
115 // Initialize LTO passes. Please keep this function in sync with
116 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
117 // passes are initialized.
118 void LTOCodeGenerator::initializeLTOPasses() {
120 
142 }
143 
145  const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
146  for (int i = 0, e = undefs.size(); i != e; ++i)
147  AsmUndefinedRefs[undefs[i]] = 1;
148 }
149 
151  assert(&Mod->getModule().getContext() == &Context &&
152  "Expected module in same context");
153 
154  bool ret = TheLinker->linkInModule(Mod->takeModule());
155  setAsmUndefinedRefs(Mod);
156 
157  // We've just changed the input, so let's make sure we verify it.
158  HasVerifiedInput = false;
159 
160  return !ret;
161 }
162 
163 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
164  assert(&Mod->getModule().getContext() == &Context &&
165  "Expected module in same context");
166 
167  AsmUndefinedRefs.clear();
168 
169  MergedModule = Mod->takeModule();
170  TheLinker = make_unique<Linker>(*MergedModule);
171  setAsmUndefinedRefs(&*Mod);
172 
173  // We've just changed the input, so let's make sure we verify it.
174  HasVerifiedInput = false;
175 }
176 
178  this->Options = Options;
179 }
180 
182  switch (Debug) {
184  EmitDwarfDebugInfo = false;
185  return;
186 
188  EmitDwarfDebugInfo = true;
189  return;
190  }
191  llvm_unreachable("Unknown debug format!");
192 }
193 
195  OptLevel = Level;
196  switch (OptLevel) {
197  case 0:
198  CGOptLevel = CodeGenOpt::None;
199  return;
200  case 1:
201  CGOptLevel = CodeGenOpt::Less;
202  return;
203  case 2:
204  CGOptLevel = CodeGenOpt::Default;
205  return;
206  case 3:
207  CGOptLevel = CodeGenOpt::Aggressive;
208  return;
209  }
210  llvm_unreachable("Unknown optimization level!");
211 }
212 
214  if (!determineTarget())
215  return false;
216 
217  // We always run the verifier once on the merged module.
218  verifyMergedModuleOnce();
219 
220  // mark which symbols can not be internalized
221  applyScopeRestrictions();
222 
223  // create output file
224  std::error_code EC;
225  ToolOutputFile Out(Path, EC, sys::fs::F_None);
226  if (EC) {
227  std::string ErrMsg = "could not open bitcode file for writing: ";
228  ErrMsg += Path.str() + ": " + EC.message();
229  emitError(ErrMsg);
230  return false;
231  }
232 
233  // write bitcode to it
234  WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
235  Out.os().close();
236 
237  if (Out.os().has_error()) {
238  std::string ErrMsg = "could not write bitcode file: ";
239  ErrMsg += Path.str() + ": " + Out.os().error().message();
240  emitError(ErrMsg);
241  Out.os().clear_error();
242  return false;
243  }
244 
245  Out.keep();
246  return true;
247 }
248 
249 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
250  // make unique temp output file to put generated code
251  SmallString<128> Filename;
252  int FD;
253 
255  (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
256 
257  std::error_code EC =
258  sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
259  if (EC) {
260  emitError(EC.message());
261  return false;
262  }
263 
264  // generate object file
265  ToolOutputFile objFile(Filename, FD);
266 
267  bool genResult = compileOptimized(&objFile.os());
268  objFile.os().close();
269  if (objFile.os().has_error()) {
270  emitError((Twine("could not write object file: ") + Filename + ": " +
271  objFile.os().error().message())
272  .str());
273  objFile.os().clear_error();
274  sys::fs::remove(Twine(Filename));
275  return false;
276  }
277 
278  objFile.keep();
279  if (!genResult) {
280  sys::fs::remove(Twine(Filename));
281  return false;
282  }
283 
284  NativeObjectPath = Filename.c_str();
285  *Name = NativeObjectPath.c_str();
286  return true;
287 }
288 
289 std::unique_ptr<MemoryBuffer>
291  const char *name;
292  if (!compileOptimizedToFile(&name))
293  return nullptr;
294 
295  // read .o file into memory buffer
297  MemoryBuffer::getFile(name, -1, false);
298  if (std::error_code EC = BufferOrErr.getError()) {
299  emitError(EC.message());
300  sys::fs::remove(NativeObjectPath);
301  return nullptr;
302  }
303 
304  // remove temp files
305  sys::fs::remove(NativeObjectPath);
306 
307  return std::move(*BufferOrErr);
308 }
309 
310 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
311  bool DisableInline,
312  bool DisableGVNLoadPRE,
313  bool DisableVectorization) {
314  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
315  DisableVectorization))
316  return false;
317 
318  return compileOptimizedToFile(Name);
319 }
320 
321 std::unique_ptr<MemoryBuffer>
322 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
323  bool DisableGVNLoadPRE, bool DisableVectorization) {
324  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
325  DisableVectorization))
326  return nullptr;
327 
328  return compileOptimized();
329 }
330 
331 bool LTOCodeGenerator::determineTarget() {
332  if (TargetMach)
333  return true;
334 
335  TripleStr = MergedModule->getTargetTriple();
336  if (TripleStr.empty()) {
337  TripleStr = sys::getDefaultTargetTriple();
338  MergedModule->setTargetTriple(TripleStr);
339  }
340  llvm::Triple Triple(TripleStr);
341 
342  // create target machine from info for merged modules
343  std::string ErrMsg;
344  MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
345  if (!MArch) {
346  emitError(ErrMsg);
347  return false;
348  }
349 
350  // Construct LTOModule, hand over ownership of module and target. Use MAttr as
351  // the default set of features.
352  SubtargetFeatures Features(MAttr);
353  Features.getDefaultSubtargetFeatures(Triple);
354  FeatureStr = Features.getString();
355  // Set a default CPU for Darwin triples.
356  if (MCpu.empty() && Triple.isOSDarwin()) {
357  if (Triple.getArch() == llvm::Triple::x86_64)
358  MCpu = "core2";
359  else if (Triple.getArch() == llvm::Triple::x86)
360  MCpu = "yonah";
361  else if (Triple.getArch() == llvm::Triple::aarch64)
362  MCpu = "cyclone";
363  }
364 
365  TargetMach = createTargetMachine();
366  return true;
367 }
368 
369 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
370  return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
371  TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
372 }
373 
374 // If a linkonce global is present in the MustPreserveSymbols, we need to make
375 // sure we honor this. To force the compiler to not drop it, we add it to the
376 // "llvm.compiler.used" global.
377 void LTOCodeGenerator::preserveDiscardableGVs(
378  Module &TheModule,
380  std::vector<GlobalValue *> Used;
381  auto mayPreserveGlobal = [&](GlobalValue &GV) {
382  if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
383  !mustPreserveGV(GV))
384  return;
385  if (GV.hasAvailableExternallyLinkage())
386  return emitWarning(
387  (Twine("Linker asked to preserve available_externally global: '") +
388  GV.getName() + "'").str());
389  if (GV.hasInternalLinkage())
390  return emitWarning((Twine("Linker asked to preserve internal global: '") +
391  GV.getName() + "'").str());
392  Used.push_back(&GV);
393  };
394  for (auto &GV : TheModule)
395  mayPreserveGlobal(GV);
396  for (auto &GV : TheModule.globals())
397  mayPreserveGlobal(GV);
398  for (auto &GV : TheModule.aliases())
399  mayPreserveGlobal(GV);
400 
401  if (Used.empty())
402  return;
403 
404  appendToCompilerUsed(TheModule, Used);
405 }
406 
407 void LTOCodeGenerator::applyScopeRestrictions() {
408  if (ScopeRestrictionsDone)
409  return;
410 
411  // Declare a callback for the internalize pass that will ask for every
412  // candidate GlobalValue if it can be internalized or not.
413  Mangler Mang;
414  SmallString<64> MangledName;
415  auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
416  // Unnamed globals can't be mangled, but they can't be preserved either.
417  if (!GV.hasName())
418  return false;
419 
420  // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
421  // with the linker supplied name, which on Darwin includes a leading
422  // underscore.
423  MangledName.clear();
424  MangledName.reserve(GV.getName().size() + 1);
425  Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
426  return MustPreserveSymbols.count(MangledName);
427  };
428 
429  // Preserve linkonce value on linker request
430  preserveDiscardableGVs(*MergedModule, mustPreserveGV);
431 
432  if (!ShouldInternalize)
433  return;
434 
435  if (ShouldRestoreGlobalsLinkage) {
436  // Record the linkage type of non-local symbols so they can be restored
437  // prior
438  // to module splitting.
439  auto RecordLinkage = [&](const GlobalValue &GV) {
440  if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
441  GV.hasName())
442  ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
443  };
444  for (auto &GV : *MergedModule)
445  RecordLinkage(GV);
446  for (auto &GV : MergedModule->globals())
447  RecordLinkage(GV);
448  for (auto &GV : MergedModule->aliases())
449  RecordLinkage(GV);
450  }
451 
452  // Update the llvm.compiler_used globals to force preserving libcalls and
453  // symbols referenced from asm
454  updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
455 
456  internalizeModule(*MergedModule, mustPreserveGV);
457 
458  ScopeRestrictionsDone = true;
459 }
460 
461 /// Restore original linkage for symbols that may have been internalized
462 void LTOCodeGenerator::restoreLinkageForExternals() {
463  if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
464  return;
465 
466  assert(ScopeRestrictionsDone &&
467  "Cannot externalize without internalization!");
468 
469  if (ExternalSymbols.empty())
470  return;
471 
472  auto externalize = [this](GlobalValue &GV) {
473  if (!GV.hasLocalLinkage() || !GV.hasName())
474  return;
475 
476  auto I = ExternalSymbols.find(GV.getName());
477  if (I == ExternalSymbols.end())
478  return;
479 
480  GV.setLinkage(I->second);
481  };
482 
483  llvm::for_each(MergedModule->functions(), externalize);
484  llvm::for_each(MergedModule->globals(), externalize);
485  llvm::for_each(MergedModule->aliases(), externalize);
486 }
487 
488 void LTOCodeGenerator::verifyMergedModuleOnce() {
489  // Only run on the first call.
490  if (HasVerifiedInput)
491  return;
492  HasVerifiedInput = true;
493 
494  bool BrokenDebugInfo = false;
495  if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
496  report_fatal_error("Broken module found, compilation aborted!");
497  if (BrokenDebugInfo) {
498  emitWarning("Invalid debug info found, debug info will be stripped");
499  StripDebugInfo(*MergedModule);
500  }
501 }
502 
503 void LTOCodeGenerator::finishOptimizationRemarks() {
504  if (DiagnosticOutputFile) {
505  DiagnosticOutputFile->keep();
506  // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
507  DiagnosticOutputFile->os().flush();
508  }
509 }
510 
511 /// Optimize merged modules using various IPO passes
512 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
513  bool DisableGVNLoadPRE,
514  bool DisableVectorization) {
515  if (!this->determineTarget())
516  return false;
517 
518  auto DiagFileOrErr = lto::setupOptimizationRemarks(
520  if (!DiagFileOrErr) {
521  errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
522  report_fatal_error("Can't get an output file for the remarks");
523  }
524  DiagnosticOutputFile = std::move(*DiagFileOrErr);
525 
526  // Setup output file to emit statistics.
527  auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
528  if (!StatsFileOrErr) {
529  errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
530  report_fatal_error("Can't get an output file for the statistics");
531  }
532  StatsFile = std::move(StatsFileOrErr.get());
533 
534  // We always run the verifier once on the merged module, the `DisableVerify`
535  // parameter only applies to subsequent verify.
536  verifyMergedModuleOnce();
537 
538  // Mark which symbols can not be internalized
539  this->applyScopeRestrictions();
540 
541  // Instantiate the pass manager to organize the passes.
542  legacy::PassManager passes;
543 
544  // Add an appropriate DataLayout instance for this module...
545  MergedModule->setDataLayout(TargetMach->createDataLayout());
546 
547  passes.add(
548  createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
549 
550  Triple TargetTriple(TargetMach->getTargetTriple());
551  PassManagerBuilder PMB;
552  PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
553  PMB.LoopVectorize = !DisableVectorization;
554  PMB.SLPVectorize = !DisableVectorization;
555  if (!DisableInline)
556  PMB.Inliner = createFunctionInliningPass();
557  PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
558  if (Freestanding)
559  PMB.LibraryInfo->disableAllFunctions();
560  PMB.OptLevel = OptLevel;
561  PMB.VerifyInput = !DisableVerify;
562  PMB.VerifyOutput = !DisableVerify;
563 
564  PMB.populateLTOPassManager(passes);
565 
566  // Run our queue of passes all at once now, efficiently.
567  passes.run(*MergedModule);
568 
569  return true;
570 }
571 
573  if (!this->determineTarget())
574  return false;
575 
576  // We always run the verifier once on the merged module. If it has already
577  // been called in optimize(), this call will return early.
578  verifyMergedModuleOnce();
579 
580  legacy::PassManager preCodeGenPasses;
581 
582  // If the bitcode files contain ARC code and were compiled with optimization,
583  // the ObjCARCContractPass must be run, so do it unconditionally here.
584  preCodeGenPasses.add(createObjCARCContractPass());
585  preCodeGenPasses.run(*MergedModule);
586 
587  // Re-externalize globals that may have been internalized to increase scope
588  // for splitting
589  restoreLinkageForExternals();
590 
591  // Do code generation. We need to preserve the module in case the client calls
592  // writeMergedModules() after compilation, but we only need to allow this at
593  // parallelism level 1. This is achieved by having splitCodeGen return the
594  // original module at parallelism level 1 which we then assign back to
595  // MergedModule.
596  MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
597  [&]() { return createTargetMachine(); }, FileType,
598  ShouldRestoreGlobalsLinkage);
599 
600  // If statistics were requested, save them to the specified file or
601  // print them out after codegen.
602  if (StatsFile)
603  PrintStatisticsJSON(StatsFile->os());
604  else if (AreStatisticsEnabled())
605  PrintStatistics();
606 
608 
609  finishOptimizationRemarks();
610 
611  return true;
612 }
613 
614 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
615 /// LTO problems.
617  for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
618  o = getToken(o.second))
619  CodegenOptions.push_back(o.first);
620 }
621 
623  // if options were requested, set them
624  if (!CodegenOptions.empty()) {
625  // ParseCommandLineOptions() expects argv[0] to be program name.
626  std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
627  for (std::string &Arg : CodegenOptions)
628  CodegenArgv.push_back(Arg.c_str());
629  cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
630  }
631 }
632 
633 
635  // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
637  switch (DI.getSeverity()) {
638  case DS_Error:
639  Severity = LTO_DS_ERROR;
640  break;
641  case DS_Warning:
642  Severity = LTO_DS_WARNING;
643  break;
644  case DS_Remark:
645  Severity = LTO_DS_REMARK;
646  break;
647  case DS_Note:
648  Severity = LTO_DS_NOTE;
649  break;
650  }
651  // Create the string that will be reported to the external diagnostic handler.
652  std::string MsgStorage;
653  raw_string_ostream Stream(MsgStorage);
654  DiagnosticPrinterRawOStream DP(Stream);
655  DI.print(DP);
656  Stream.flush();
657 
658  // If this method has been called it means someone has set up an external
659  // diagnostic handler. Assert on that.
660  assert(DiagHandler && "Invalid diagnostic handler");
661  (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
662 }
663 
664 namespace {
665 struct LTODiagnosticHandler : public DiagnosticHandler {
666  LTOCodeGenerator *CodeGenerator;
667  LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
668  : CodeGenerator(CodeGenPtr) {}
669  bool handleDiagnostics(const DiagnosticInfo &DI) override {
670  CodeGenerator->DiagnosticHandler(DI);
671  return true;
672  }
673 };
674 }
675 
676 void
678  void *Ctxt) {
679  this->DiagHandler = DiagHandler;
680  this->DiagContext = Ctxt;
681  if (!DiagHandler)
682  return Context.setDiagnosticHandler(nullptr);
683  // Register the LTOCodeGenerator stub in the LLVMContext to forward the
684  // diagnostic to the external DiagHandler.
685  Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
686  true);
687 }
688 
689 namespace {
690 class LTODiagnosticInfo : public DiagnosticInfo {
691  const Twine &Msg;
692 public:
693  LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
694  : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
695  void print(DiagnosticPrinter &DP) const override { DP << Msg; }
696 };
697 }
698 
699 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
700  if (DiagHandler)
701  (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
702  else
703  Context.diagnose(LTODiagnosticInfo(ErrMsg));
704 }
705 
706 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
707  if (DiagHandler)
708  (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
709  else
710  Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
711 }
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 (OS X, iOS, or watchOS).
Definition: Triple.h:479
This is the base class for diagnostic handling in LLVM.
void initializeGlobalOptLegacyPassPass(PassRegistry &)
Represents either an error or a value T.
Definition: ErrorOr.h:56
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
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:218
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:139
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< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
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:65
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...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
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:313
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:116
void initializeGlobalDCELegacyPassPass(PassRegistry &)
iterator find(StringRef Key)
Definition: StringMap.h:332
bool addModule(struct LTOModule *)
Merge given module.
Implementation of the target library information.
bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Optimizes the merged module.
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, TargetMachine::CodeGenFileType FileType=TargetMachine::CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
Definition: ParallelCG.cpp:37
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:369
std::unique_ptr< Module > takeModule()
Definition: LTOModule.h:119
std::error_code error() const
Definition: raw_ostream.h:445
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
void initializeReversePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
static void externalize(GlobalValue *GV)
void initializePruneEHPass(PassRegistry &)
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, const char *EnvVar=nullptr, bool LongOptionsUseDoubleDash=false)
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:966
void add(Pass *P) override
Add a pass to the queue of passes to run.
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:244
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 ...
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \\\)
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
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:294
Pass * createObjCARCContractPass()
static const char * getVersionString()
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:350
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...
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, StringRef LTORemarksPasses, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1341
Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition: LTO.cpp:1371
lto_debug_model
Definition: lto.h:77
void initializeGVNLegacyPassPass(PassRegistry &)
PassManager manages ModulePassManagers.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
This is the base abstract class for diagnostic reporting in the backend.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:358
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::error_code getError() const
Definition: ErrorOr.h:159
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.
cl::opt< std::string > LTORemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes " "whose names match the given regular expression"), cl::value_desc("regex"))
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)
void setTargetOptions(const TargetOptions &Options)
const Module & getModule() const
Definition: LTOModule.h:116
C++ class which implements the opaque lto_module_t type.
Definition: LTOModule.h:37
void setCodeGenDebugOptions(StringRef Opts)
Pass options to the driver and optimization passes.
void initializeMemCpyOptLegacyPassPass(PassRegistry &)
void initializeConstantMergeLegacyPassPass(PassRegistry &)
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
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.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
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:451
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:329
const std::vector< StringRef > & getAsmUndefinedRefs()
Definition: LTOModule.h:160
void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
Definition: Statistic.cpp:201
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:365
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 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:4960
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:812
void initializePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
void initializeIPSCCPLegacyPassPass(PassRegistry &)
const char * c_str()
Definition: SmallString.h:269
#define I(x, y, z)
Definition: MD5.cpp:58
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:227
bool empty() const
Definition: StringMap.h:110
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:482
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
static const char * name
LTOCodeGenerator(LLVMContext &Context)
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:111
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
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.
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1178
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:133
iterator end()
Definition: StringMap.h:317
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:462
void setDebugInfo(lto_debug_model)