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