LLVM  12.0.0git
LTOBackend.cpp
Go to the documentation of this file.
1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
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 "backend" phase of LTO, i.e. it performs
10 // optimization and code generation on a loaded module. It is generally used
11 // internally by the LTO class but can also be used independently, for example
12 // to implement a standalone ThinLTO backend.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/LTO/LTOBackend.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/LTO/LTO.h"
32 #include "llvm/Passes/PassPlugin.h"
34 #include "llvm/Support/Error.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Program.h"
44 #include "llvm/Transforms/IPO.h"
49 
50 using namespace llvm;
51 using namespace lto;
52 
54  errs() << "failed to open " << Path << ": " << Msg << '\n';
55  errs().flush();
56  exit(1);
57 }
58 
59 Error Config::addSaveTemps(std::string OutputFileName,
60  bool UseInputModulePath) {
62 
63  std::error_code EC;
64  ResolutionFile = std::make_unique<raw_fd_ostream>(
65  OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text);
66  if (EC) {
67  ResolutionFile.reset();
68  return errorCodeToError(EC);
69  }
70 
71  auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
72  // Keep track of the hook provided by the linker, which also needs to run.
73  ModuleHookFn LinkerHook = Hook;
74  Hook = [=](unsigned Task, const Module &M) {
75  // If the linker's hook returned false, we need to pass that result
76  // through.
77  if (LinkerHook && !LinkerHook(Task, M))
78  return false;
79 
80  std::string PathPrefix;
81  // If this is the combined module (not a ThinLTO backend compile) or the
82  // user hasn't requested using the input module's path, emit to a file
83  // named from the provided OutputFileName with the Task ID appended.
84  if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
85  PathPrefix = OutputFileName;
86  if (Task != (unsigned)-1)
87  PathPrefix += utostr(Task) + ".";
88  } else
89  PathPrefix = M.getModuleIdentifier() + ".";
90  std::string Path = PathPrefix + PathSuffix + ".bc";
91  std::error_code EC;
93  // Because -save-temps is a debugging feature, we report the error
94  // directly and exit.
95  if (EC)
96  reportOpenError(Path, EC.message());
97  WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
98  return true;
99  };
100  };
101 
102  setHook("0.preopt", PreOptModuleHook);
103  setHook("1.promote", PostPromoteModuleHook);
104  setHook("2.internalize", PostInternalizeModuleHook);
105  setHook("3.import", PostImportModuleHook);
106  setHook("4.opt", PostOptModuleHook);
107  setHook("5.precodegen", PreCodeGenModuleHook);
108 
110  [=](const ModuleSummaryIndex &Index,
111  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
112  std::string Path = OutputFileName + "index.bc";
113  std::error_code EC;
115  // Because -save-temps is a debugging feature, we report the error
116  // directly and exit.
117  if (EC)
118  reportOpenError(Path, EC.message());
119  WriteIndexToFile(Index, OS);
120 
121  Path = OutputFileName + "index.dot";
123  if (EC)
124  reportOpenError(Path, EC.message());
125  Index.exportToDot(OSDot, GUIDPreservedSymbols);
126  return true;
127  };
128 
129  return Error::success();
130 }
131 
132 #define HANDLE_EXTENSION(Ext) \
133  llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
134 #include "llvm/Support/Extension.def"
135 
137  PassBuilder &PB) {
138 #define HANDLE_EXTENSION(Ext) \
139  get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
140 #include "llvm/Support/Extension.def"
141 
142  // Load requested pass plugins and let them register pass builder callbacks
143  for (auto &PluginFN : PassPlugins) {
144  auto PassPlugin = PassPlugin::Load(PluginFN);
145  if (!PassPlugin) {
146  errs() << "Failed to load passes from '" << PluginFN
147  << "'. Request ignored.\n";
148  continue;
149  }
150 
152  }
153 }
154 
155 namespace {
156 
157 std::unique_ptr<TargetMachine>
158 createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
159  StringRef TheTriple = M.getTargetTriple();
160  SubtargetFeatures Features;
161  Features.getDefaultSubtargetFeatures(Triple(TheTriple));
162  for (const std::string &A : Conf.MAttrs)
163  Features.AddFeature(A);
164 
166  if (Conf.RelocModel)
167  RelocModel = *Conf.RelocModel;
168  else
169  RelocModel =
171 
173  if (Conf.CodeModel)
174  CodeModel = *Conf.CodeModel;
175  else
176  CodeModel = M.getCodeModel();
177 
178  return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
179  TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
180  CodeModel, Conf.CGOptLevel));
181 }
182 
183 static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
184  unsigned OptLevel, bool IsThinLTO,
185  ModuleSummaryIndex *ExportSummary,
186  const ModuleSummaryIndex *ImportSummary) {
187  Optional<PGOOptions> PGOOpt;
188  if (!Conf.SampleProfile.empty())
189  PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
191  else if (Conf.RunCSIRInstr) {
192  PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
194  } else if (!Conf.CSIRProfile.empty()) {
195  PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
197  }
198 
201  SI.registerCallbacks(PIC);
202  PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
203  AAManager AA;
204 
205  // Parse a custom AA pipeline if asked to.
206  if (auto Err = PB.parseAAPipeline(AA, "default"))
207  report_fatal_error("Error parsing default AA pipeline");
208 
210 
215 
216  // Register the AA manager first so that our version is the one used.
217  FAM.registerPass([&] { return std::move(AA); });
218 
219  // Register all the basic analyses with the managers.
220  PB.registerModuleAnalyses(MAM);
221  PB.registerCGSCCAnalyses(CGAM);
222  PB.registerFunctionAnalyses(FAM);
223  PB.registerLoopAnalyses(LAM);
224  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
225 
227  // FIXME (davide): verify the input.
228 
230 
231  switch (OptLevel) {
232  default:
233  llvm_unreachable("Invalid optimization level");
234  case 0:
236  break;
237  case 1:
239  break;
240  case 2:
242  break;
243  case 3:
245  break;
246  }
247 
248  if (IsThinLTO)
250  ImportSummary);
251  else
252  MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
253  MPM.run(Mod, MAM);
254 
255  // FIXME (davide): verify the output.
256 }
257 
258 static void runNewPMCustomPasses(const Config &Conf, Module &Mod,
259  TargetMachine *TM, std::string PipelineDesc,
260  std::string AAPipelineDesc,
261  bool DisableVerify) {
262  PassBuilder PB(TM);
263  AAManager AA;
264 
265  // Parse a custom AA pipeline if asked to.
266  if (!AAPipelineDesc.empty())
267  if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
268  report_fatal_error("unable to parse AA pipeline description '" +
269  AAPipelineDesc + "': " + toString(std::move(Err)));
270 
272 
277 
278  // Register the AA manager first so that our version is the one used.
279  FAM.registerPass([&] { return std::move(AA); });
280 
281  // Register all the basic analyses with the managers.
282  PB.registerModuleAnalyses(MAM);
283  PB.registerCGSCCAnalyses(CGAM);
284  PB.registerFunctionAnalyses(FAM);
285  PB.registerLoopAnalyses(LAM);
286  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
287 
288  ModulePassManager MPM;
289 
290  // Always verify the input.
291  MPM.addPass(VerifierPass());
292 
293  // Now, add all the passes we've been requested to.
294  if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
295  report_fatal_error("unable to parse pass pipeline description '" +
296  PipelineDesc + "': " + toString(std::move(Err)));
297 
298  if (!DisableVerify)
299  MPM.addPass(VerifierPass());
300  MPM.run(Mod, MAM);
301 }
302 
303 static void runOldPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
304  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
305  const ModuleSummaryIndex *ImportSummary) {
306  legacy::PassManager passes;
308 
309  PassManagerBuilder PMB;
312  PMB.ExportSummary = ExportSummary;
313  PMB.ImportSummary = ImportSummary;
314  // Unconditionally verify input since it is not verified before this
315  // point and has unknown origin.
316  PMB.VerifyInput = true;
317  PMB.VerifyOutput = !Conf.DisableVerify;
318  PMB.LoopVectorize = true;
319  PMB.SLPVectorize = true;
320  PMB.OptLevel = Conf.OptLevel;
321  PMB.PGOSampleUse = Conf.SampleProfile;
323  if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
324  PMB.EnablePGOCSInstrUse = true;
325  PMB.PGOInstrUse = Conf.CSIRProfile;
326  }
327  if (IsThinLTO)
328  PMB.populateThinLTOPassManager(passes);
329  else
330  PMB.populateLTOPassManager(passes);
331  passes.run(Mod);
332 }
333 
334 bool opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
335  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
336  const ModuleSummaryIndex *ImportSummary) {
337  // FIXME: Plumb the combined index into the new pass manager.
338  if (!Conf.OptPipeline.empty())
339  runNewPMCustomPasses(Conf, Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
340  Conf.DisableVerify);
341  else if (Conf.UseNewPM)
342  runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
343  ImportSummary);
344  else
345  runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
346  return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
347 }
348 
349 static cl::opt<bool> EmbedBitcode(
350  "lto-embed-bitcode", cl::init(false),
351  cl::desc("Embed LLVM bitcode in object files produced by LTO"));
352 
353 static void EmitBitcodeSection(Module &M, const Config &Conf) {
354  if (!EmbedBitcode)
355  return;
356  SmallVector<char, 0> Buffer;
357  raw_svector_ostream OS(Buffer);
358  WriteBitcodeToFile(M, OS);
359 
360  std::unique_ptr<MemoryBuffer> Buf(
361  new SmallVectorMemoryBuffer(std::move(Buffer)));
362  llvm::EmbedBitcodeInModule(M, Buf->getMemBufferRef(), /*EmbedBitcode*/ true,
363  /*EmbedMarker*/ false, /*CmdArgs*/ nullptr);
364 }
365 
366 void codegen(const Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
367  unsigned Task, Module &Mod,
368  const ModuleSummaryIndex &CombinedIndex) {
369  if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
370  return;
371 
372  EmitBitcodeSection(Mod, Conf);
373 
374  std::unique_ptr<ToolOutputFile> DwoOut;
375  SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
376  if (!Conf.DwoDir.empty()) {
377  std::error_code EC;
378  if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
379  report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
380  EC.message());
381 
382  DwoFile = Conf.DwoDir;
383  sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
384  TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
385  } else
387 
388  if (!DwoFile.empty()) {
389  std::error_code EC;
390  DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
391  if (EC)
392  report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
393  }
394 
395  auto Stream = AddStream(Task);
396  legacy::PassManager CodeGenPasses;
397  CodeGenPasses.add(
399  if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
400  DwoOut ? &DwoOut->os() : nullptr,
401  Conf.CGFileType))
402  report_fatal_error("Failed to setup codegen");
403  CodeGenPasses.run(Mod);
404 
405  if (DwoOut)
406  DwoOut->keep();
407 }
408 
409 void splitCodeGen(const Config &C, TargetMachine *TM, AddStreamFn AddStream,
410  unsigned ParallelCodeGenParallelismLevel,
411  std::unique_ptr<Module> Mod,
412  const ModuleSummaryIndex &CombinedIndex) {
413  ThreadPool CodegenThreadPool(
414  heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
415  unsigned ThreadCount = 0;
416  const Target *T = &TM->getTarget();
417 
418  SplitModule(
419  std::move(Mod), ParallelCodeGenParallelismLevel,
420  [&](std::unique_ptr<Module> MPart) {
421  // We want to clone the module in a new context to multi-thread the
422  // codegen. We do it by serializing partition modules to bitcode
423  // (while still on the main thread, in order to avoid data races) and
424  // spinning up new threads which deserialize the partitions into
425  // separate contexts.
426  // FIXME: Provide a more direct way to do this in LLVM.
427  SmallString<0> BC;
428  raw_svector_ostream BCOS(BC);
429  WriteBitcodeToFile(*MPart, BCOS);
430 
431  // Enqueue the task
432  CodegenThreadPool.async(
433  [&](const SmallString<0> &BC, unsigned ThreadId) {
434  LTOLLVMContext Ctx(C);
436  MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
437  Ctx);
438  if (!MOrErr)
439  report_fatal_error("Failed to read bitcode");
440  std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
441 
442  std::unique_ptr<TargetMachine> TM =
443  createTargetMachine(C, T, *MPartInCtx);
444 
445  codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
446  CombinedIndex);
447  },
448  // Pass BC using std::move to ensure that it get moved rather than
449  // copied into the thread's context.
450  std::move(BC), ThreadCount++);
451  },
452  false);
453 
454  // Because the inner lambda (which runs in a worker thread) captures our local
455  // variables, we need to wait for the worker threads to terminate before we
456  // can leave the function scope.
457  CodegenThreadPool.wait();
458 }
459 
460 Expected<const Target *> initAndLookupTarget(const Config &C, Module &Mod) {
461  if (!C.OverrideTriple.empty())
463  else if (Mod.getTargetTriple().empty())
465 
466  std::string Msg;
468  if (!T)
469  return make_error<StringError>(Msg, inconvertibleErrorCode());
470  return T;
471 }
472 }
473 
475  std::unique_ptr<ToolOutputFile> DiagOutputFile) {
476  // Make sure we flush the diagnostic remarks file in case the linker doesn't
477  // call the global destructors before exiting.
478  if (!DiagOutputFile)
479  return Error::success();
480  DiagOutputFile->keep();
481  DiagOutputFile->os().flush();
482  return Error::success();
483 }
484 
486  unsigned ParallelCodeGenParallelismLevel,
487  std::unique_ptr<Module> Mod,
488  ModuleSummaryIndex &CombinedIndex) {
489  Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
490  if (!TOrErr)
491  return TOrErr.takeError();
492 
493  std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
494 
495  if (!C.CodeGenOnly) {
496  if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
497  /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
498  return Error::success();
499  }
500 
501  if (ParallelCodeGenParallelismLevel == 1) {
502  codegen(C, TM.get(), AddStream, 0, *Mod, CombinedIndex);
503  } else {
504  splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
505  std::move(Mod), CombinedIndex);
506  }
507  return Error::success();
508 }
509 
510 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
511  const ModuleSummaryIndex &Index) {
512  std::vector<GlobalValue*> DeadGVs;
513  for (auto &GV : Mod.global_values())
514  if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
515  if (!Index.isGlobalValueLive(GVS)) {
516  DeadGVs.push_back(&GV);
518  }
519 
520  // Now that all dead bodies have been dropped, delete the actual objects
521  // themselves when possible.
522  for (GlobalValue *GV : DeadGVs) {
523  GV->removeDeadConstantUsers();
524  // Might reference something defined in native object (i.e. dropped a
525  // non-prevailing IR def, but we need to keep the declaration).
526  if (GV->use_empty())
527  GV->eraseFromParent();
528  }
529 }
530 
531 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
532  Module &Mod, const ModuleSummaryIndex &CombinedIndex,
533  const FunctionImporter::ImportMapTy &ImportList,
534  const GVSummaryMapTy &DefinedGlobals,
536  Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
537  if (!TOrErr)
538  return TOrErr.takeError();
539 
540  std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
541 
542  // Setup optimization remarks.
543  auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
544  Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
545  Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
546  if (!DiagFileOrErr)
547  return DiagFileOrErr.takeError();
548  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
549 
550  // Set the partial sample profile ratio in the profile summary module flag of
551  // the module, if applicable.
552  Mod.setPartialSampleProfileRatio(CombinedIndex);
553 
554  if (Conf.CodeGenOnly) {
555  codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
556  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
557  }
558 
559  if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
560  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
561 
562  // When linking an ELF shared object, dso_local should be dropped. We
563  // conservatively do this for -fpic.
564  bool ClearDSOLocalOnDeclarations =
565  TM->getTargetTriple().isOSBinFormatELF() &&
566  TM->getRelocationModel() != Reloc::Static &&
568  renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
569 
570  dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
571 
572  thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
573 
574  if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
575  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
576 
577  if (!DefinedGlobals.empty())
578  thinLTOInternalizeModule(Mod, DefinedGlobals);
579 
580  if (Conf.PostInternalizeModuleHook &&
581  !Conf.PostInternalizeModuleHook(Task, Mod))
582  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
583 
584  auto ModuleLoader = [&](StringRef Identifier) {
586  "ODR Type uniquing should be enabled on the context");
587  auto I = ModuleMap.find(Identifier);
588  assert(I != ModuleMap.end());
589  return I->second.getLazyModule(Mod.getContext(),
590  /*ShouldLazyLoadMetadata=*/true,
591  /*IsImporting*/ true);
592  };
593 
594  FunctionImporter Importer(CombinedIndex, ModuleLoader,
595  ClearDSOLocalOnDeclarations);
596  if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
597  return Err;
598 
599  if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
600  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
601 
602  if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
603  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
604  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
605 
606  codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
607  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
608 }
uint64_t CallInst * C
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition: Path.cpp:953
std::unique_ptr< Module > splitCodeGen(std::unique_ptr< Module > M, ArrayRef< raw_pwrite_stream *> OSs, ArrayRef< llvm::raw_pwrite_stream *> BCOSs, const std::function< std::unique_ptr< TargetMachine >()> &TMFactory, CodeGenFileType FileType=CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
Definition: ParallelCG.cpp:37
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:249
Interfaces for registering analysis passes, producing common pass manager configurations, and parsing of pass pipelines.
void thinLTOResolvePrevailingInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Resolve prevailing symbol linkages in TheModule based on the information recorded in the summaries du...
std::string CPU
Definition: Config.h:41
std::string AAPipeline
Definition: Config.h:82
Error finalizeOptimizationRemarks(std::unique_ptr< ToolOutputFile > DiagOutputFile)
Definition: LTOBackend.cpp:474
CodeGenOpt::Level CGOptLevel
Definition: Config.h:47
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfoWrapperPass *MMIWP=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
std::vector< std::string > PassPlugins
Definition: Config.h:44
MCTargetOptions MCOptions
Machine level options.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
bool EnablePGOCSInstrUse
Enable profile context sensitive profile use pass.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:67
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Optional< Reloc::Model > RM, Optional< CodeModel::Model > CM=None, CodeGenOpt::Level OL=CodeGenOpt::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple...
Error parseAAPipeline(AAManager &AA, StringRef PipelineText)
Parse a textual alias analysis pipeline into the provided AA manager.
This is the interface to build a ModuleSummaryIndex for a module.
bool ShouldDiscardValueNames
Definition: Config.h:142
Implements a dense probed hash-table based set.
Definition: DenseSet.h:255
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Definition: Config.h:86
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
std::string SplitDwarfFile
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition: Config.h:60
void registerModuleAnalyses(ModuleAnalysisManager &MAM)
Registers all available module analysis passes.
void SplitModule(std::unique_ptr< Module > M, unsigned N, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback, bool PreserveLocals=false)
Splits the module M into N linkable partitions.
static void RegisterPassPlugins(ArrayRef< std::string > PassPlugins, PassBuilder &PB)
Definition: LTOBackend.cpp:136
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
Definition: Config.h:149
bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
ModuleSummaryIndex * ExportSummary
The module summary index to use for exporting information from the regular LTO phase, for example for the CFI and devirtualization type tests.
std::string getString() const
Returns features as a string.
const ModuleSummaryIndex * ImportSummary
The module summary index to use for importing information to the thin LTO backends, for example for the CFI and devirtualization type tests.
Expected< std::unique_ptr< ToolOutputFile > > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1460
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:550
Optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
Definition: Module.cpp:560
Implementation of the target library information.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition: Config.h:128
std::string PGOSampleUse
Path of the sample Profile data file.
void registerCallbacks(PassInstrumentationCallbacks &PIC)
Error takeError()
Take ownership of the stored error.
Definition: Error.h:557
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
Definition: PassManager.h:489
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:54
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition: Config.h:200
Pass * Inliner
Inliner - Specifies the inliner to use.
CombinedIndexHookFn CombinedIndexHook
Definition: Config.h:214
void registerPassBuilderCallbacks(PassBuilder &PB) const
Invoke the PassBuilder callback registration.
Definition: PassPlugin.h:82
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue *> *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:455
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:991
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition: Config.h:122
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
std::string DwoDir
The directory to store .dwo files.
Definition: Config.h:102
std::vector< std::string > MAttrs
Definition: Config.h:43
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:253
std::string ProfileRemapping
Name remapping file for profile data.
Definition: Config.h:99
static const OptimizationLevel O3
Optimize for fast execution as much as possible.
Definition: PassBuilder.h:223
void populateLTOPassManager(legacy::PassManagerBase &PM)
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:831
This class provides access to building LLVM&#39;s passes.
Definition: PassBuilder.h:120
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
bool EnablePGOCSInstrGen
Enable profile context sensitive instrumentation pass.
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
Definition: Config.h:108
void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index)
Set the partial sample profile ratio in the profile summary module flag, if applicable.
Definition: Module.cpp:678
Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
Definition: LTOBackend.cpp:485
bool DisableVerify
Definition: Config.h:50
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
void crossRegisterProxies(LoopAnalysisManager &LAM, FunctionAnalysisManager &FAM, CGSCCAnalysisManager &CGAM, ModuleAnalysisManager &MAM)
Cross register the analysis managers through their proxies.
std::string SampleProfile
Sample PGO profile path.
Definition: Config.h:96
TargetOptions Options
Definition: Config.h:42
Optional< CodeModel::Model > CodeModel
Definition: Config.h:46
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:25
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Definition: ThreadPool.h:37
Class to hold module path string table and global value map, and encapsulate methods for operating on...
iterator find(const KeyT &Key)
Definition: MapVector.h:147
std::string PGOInstrUse
Path of the profile data file.
The file should be opened in text mode on platforms that make this distinction.
Definition: FileSystem.h:767
This class provides an interface to register all the standard pass instrumentations and manages their...
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, CodeGenFileType FileType)
Definition: ParallelCG.cpp:27
PassManager manages ModulePassManagers.
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
Definition: LTOBackend.cpp:510
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:434
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
Definition: Config.h:182
static Expected< PassPlugin > Load(const std::string &Filename)
Attempts to load a pass plugin from a given file.
Definition: PassPlugin.cpp:16
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
Definition: Config.h:178
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition: Module.cpp:546
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
A loaded pass plugin.
Definition: PassPlugin.h:60
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
A manager for alias analyses.
TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
bool UseNewPM
Use the new pass manager.
Definition: Config.h:53
Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > &ModuleMap)
Runs a ThinLTO backend.
Definition: LTOBackend.cpp:531
unsigned OptLevel
Definition: Config.h:49
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.
bool isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
void registerFunctionAnalyses(FunctionAnalysisManager &FAM)
Registers all available function analysis passes.
LTO configuration.
Definition: Config.h:38
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
Definition: Config.h:90
const Triple & getTargetTriple() const
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition: Config.h:93
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Function and variable summary information to aid decisions and implementation of importing.
const Target & getTarget() const
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition: Config.h:189
Create a verifier pass.
Definition: Verifier.h:136
ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, const ModuleSummaryIndex *ImportSummary)
Build an ThinLTO default optimization pipeline to a pass manager.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::function< std::unique_ptr< NativeObjectStream >(unsigned Task)> AddStreamFn
This type defines the callback to add a native object that is generated on the fly.
Definition: LTO.h:200
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:45
std::string RemarksFilename
Optimization remarks file path.
Definition: Config.h:116
void exportToDot(raw_ostream &OS, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols) const
Export summary to dot file for GraphViz.
static const OptimizationLevel O0
Disable as many optimizations as possible.
Definition: PassBuilder.h:175
static ErrorSuccess success()
Create a success value.
Definition: Error.h:332
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition: Config.h:63
Error parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText, bool VerifyEachPass=true, bool DebugLogging=false)
Parse a textual pass pipeline description into a ModulePassManager.
#define LLVM_ATTRIBUTE_NORETURN
Definition: Compiler.h:249
Optional< Reloc::Model > RelocModel
Definition: Config.h:45
reference get()
Returns a reference to the stored T value.
Definition: Error.h:537
arm prera ldst opt
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:231
The access may modify the value stored in memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:106
Target - Wrapper for Target specific information.
CodeGenFileType CGFileType
Definition: Config.h:48
Manages the enabling and disabling of subtarget specific features.
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
Definition: Config.h:77
void WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
void add(Pass *P) override
Add a pass to the queue of passes to run.
void EmbedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedMarker, const std::vector< uint8_t > *CmdArgs)
Save a copy of the llvm IR as data in the __LLVM,__bitcode section.
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition: Config.h:125
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
SmallVector-backed MemoryBuffer instance.
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:408
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:171
A struct capturing PGO tunables.
Definition: PassBuilder.h:34
static const OptimizationLevel O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
Definition: PassBuilder.h:208
TargetOptions Options
#define I(x, y, z)
Definition: MD5.cpp:59
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
void setTargetTriple(StringRef T)
Set the target triple.
Definition: Module.h:292
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition: Config.h:113
size_t size() const
Definition: SmallVector.h:66
std::string RemarksPasses
Optimization remarks pass filter.
Definition: Config.h:119
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:97
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:197
This header provides classes for managing passes over SCCs of the call graph.
static const OptimizationLevel O1
Optimize quickly without destroying debuggability.
Definition: PassBuilder.h:191
const std::string to_string(const T &Value)
Definition: ScopedPrinter.h:61
void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM)
Registers all available CGSCC analysis passes.
ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, DataLayoutCallbackTy DataLayoutCallback=[](StringRef) { return None;})
Read the specified bitcode file, returning the module.
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition: Config.h:192
iterator end()
Definition: MapVector.h:71
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM-provided high-level optimization levels.
Definition: PassBuilder.h:156
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
The function importer is automatically importing function from other modules based on the provided su...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition: Config.h:195
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
Definition: Module.cpp:532
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false)
This is a convenience function that configures this Config object to write temporary files named afte...
Definition: LTOBackend.cpp:59
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
Definition: Threading.h:194
A derived class of LLVMContext that initializes itself according to a given Config object...
Definition: Config.h:249
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
A container for analyses that lazily runs them and caches their results.
void addPass(PassT Pass)
Definition: PassManager.h:554
static LLVM_ATTRIBUTE_NORETURN void reportOpenError(StringRef Path, Twine Msg)
Definition: LTOBackend.cpp:53
This pass exposes codegen information to IR-level passes.
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
Definition: Config.h:152
This header defines various interfaces for pass management in LLVM.
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition: Config.h:186
ImmutablePass * createImmutableModuleSummaryIndexWrapperPass(const ModuleSummaryIndex *Index)
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
Definition: ThreadPool.cpp:69
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77
iterator_range< global_value_iterator > global_values()
Definition: Module.cpp:420