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