LLVM  10.0.0svn
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"
24 #include "llvm/IR/PassManager.h"
25 #include "llvm/IR/RemarkStreamer.h"
26 #include "llvm/IR/Verifier.h"
27 #include "llvm/LTO/LTO.h"
32 #include "llvm/Support/Error.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Program.h"
41 #include "llvm/Transforms/IPO.h"
46 
47 using namespace llvm;
48 using namespace lto;
49 
51  errs() << "failed to open " << Path << ": " << Msg << '\n';
52  errs().flush();
53  exit(1);
54 }
55 
56 Error Config::addSaveTemps(std::string OutputFileName,
57  bool UseInputModulePath) {
59 
60  std::error_code EC;
61  ResolutionFile = std::make_unique<raw_fd_ostream>(
62  OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text);
63  if (EC)
64  return errorCodeToError(EC);
65 
66  auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
67  // Keep track of the hook provided by the linker, which also needs to run.
68  ModuleHookFn LinkerHook = Hook;
69  Hook = [=](unsigned Task, const Module &M) {
70  // If the linker's hook returned false, we need to pass that result
71  // through.
72  if (LinkerHook && !LinkerHook(Task, M))
73  return false;
74 
75  std::string PathPrefix;
76  // If this is the combined module (not a ThinLTO backend compile) or the
77  // user hasn't requested using the input module's path, emit to a file
78  // named from the provided OutputFileName with the Task ID appended.
79  if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
80  PathPrefix = OutputFileName;
81  if (Task != (unsigned)-1)
82  PathPrefix += utostr(Task) + ".";
83  } else
84  PathPrefix = M.getModuleIdentifier() + ".";
85  std::string Path = PathPrefix + PathSuffix + ".bc";
86  std::error_code EC;
88  // Because -save-temps is a debugging feature, we report the error
89  // directly and exit.
90  if (EC)
91  reportOpenError(Path, EC.message());
92  WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
93  return true;
94  };
95  };
96 
97  setHook("0.preopt", PreOptModuleHook);
98  setHook("1.promote", PostPromoteModuleHook);
99  setHook("2.internalize", PostInternalizeModuleHook);
100  setHook("3.import", PostImportModuleHook);
101  setHook("4.opt", PostOptModuleHook);
102  setHook("5.precodegen", PreCodeGenModuleHook);
103 
105  std::string Path = OutputFileName + "index.bc";
106  std::error_code EC;
108  // Because -save-temps is a debugging feature, we report the error
109  // directly and exit.
110  if (EC)
111  reportOpenError(Path, EC.message());
112  WriteIndexToFile(Index, OS);
113 
114  Path = OutputFileName + "index.dot";
116  if (EC)
117  reportOpenError(Path, EC.message());
118  Index.exportToDot(OSDot);
119  return true;
120  };
121 
122  return Error::success();
123 }
124 
125 namespace {
126 
127 std::unique_ptr<TargetMachine>
128 createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
129  StringRef TheTriple = M.getTargetTriple();
130  SubtargetFeatures Features;
131  Features.getDefaultSubtargetFeatures(Triple(TheTriple));
132  for (const std::string &A : Conf.MAttrs)
133  Features.AddFeature(A);
134 
136  if (Conf.RelocModel)
137  RelocModel = *Conf.RelocModel;
138  else
139  RelocModel =
141 
143  if (Conf.CodeModel)
144  CodeModel = *Conf.CodeModel;
145  else
146  CodeModel = M.getCodeModel();
147 
148  return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
149  TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
150  CodeModel, Conf.CGOptLevel));
151 }
152 
153 static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
154  unsigned OptLevel, bool IsThinLTO,
155  ModuleSummaryIndex *ExportSummary,
156  const ModuleSummaryIndex *ImportSummary) {
157  Optional<PGOOptions> PGOOpt;
158  if (!Conf.SampleProfile.empty())
159  PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
161  else if (Conf.RunCSIRInstr) {
162  PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
164  } else if (!Conf.CSIRProfile.empty()) {
165  PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
167  }
168 
171  SI.registerCallbacks(PIC);
172  PassBuilder PB(TM, PipelineTuningOptions(),PGOOpt, &PIC);
173  AAManager AA;
174 
175  // Parse a custom AA pipeline if asked to.
176  if (auto Err = PB.parseAAPipeline(AA, "default"))
177  report_fatal_error("Error parsing default AA pipeline");
178 
183 
184  // Register the AA manager first so that our version is the one used.
185  FAM.registerPass([&] { return std::move(AA); });
186 
187  // Register all the basic analyses with the managers.
188  PB.registerModuleAnalyses(MAM);
189  PB.registerCGSCCAnalyses(CGAM);
190  PB.registerFunctionAnalyses(FAM);
191  PB.registerLoopAnalyses(LAM);
192  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
193 
195  // FIXME (davide): verify the input.
196 
198 
199  switch (OptLevel) {
200  default:
201  llvm_unreachable("Invalid optimization level");
202  case 0:
203  OL = PassBuilder::O0;
204  break;
205  case 1:
206  OL = PassBuilder::O1;
207  break;
208  case 2:
209  OL = PassBuilder::O2;
210  break;
211  case 3:
212  OL = PassBuilder::O3;
213  break;
214  }
215 
216  if (IsThinLTO)
218  ImportSummary);
219  else
220  MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
221  MPM.run(Mod, MAM);
222 
223  // FIXME (davide): verify the output.
224 }
225 
226 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
227  std::string PipelineDesc,
228  std::string AAPipelineDesc,
229  bool DisableVerify) {
230  PassBuilder PB(TM);
231  AAManager AA;
232 
233  // Parse a custom AA pipeline if asked to.
234  if (!AAPipelineDesc.empty())
235  if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
236  report_fatal_error("unable to parse AA pipeline description '" +
237  AAPipelineDesc + "': " + toString(std::move(Err)));
238 
243 
244  // Register the AA manager first so that our version is the one used.
245  FAM.registerPass([&] { return std::move(AA); });
246 
247  // Register all the basic analyses with the managers.
248  PB.registerModuleAnalyses(MAM);
249  PB.registerCGSCCAnalyses(CGAM);
250  PB.registerFunctionAnalyses(FAM);
251  PB.registerLoopAnalyses(LAM);
252  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
253 
254  ModulePassManager MPM;
255 
256  // Always verify the input.
257  MPM.addPass(VerifierPass());
258 
259  // Now, add all the passes we've been requested to.
260  if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
261  report_fatal_error("unable to parse pass pipeline description '" +
262  PipelineDesc + "': " + toString(std::move(Err)));
263 
264  if (!DisableVerify)
265  MPM.addPass(VerifierPass());
266  MPM.run(Mod, MAM);
267 }
268 
269 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
270  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
271  const ModuleSummaryIndex *ImportSummary) {
272  legacy::PassManager passes;
274 
275  PassManagerBuilder PMB;
278  PMB.ExportSummary = ExportSummary;
279  PMB.ImportSummary = ImportSummary;
280  // Unconditionally verify input since it is not verified before this
281  // point and has unknown origin.
282  PMB.VerifyInput = true;
283  PMB.VerifyOutput = !Conf.DisableVerify;
284  PMB.LoopVectorize = true;
285  PMB.SLPVectorize = true;
286  PMB.OptLevel = Conf.OptLevel;
287  PMB.PGOSampleUse = Conf.SampleProfile;
289  if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
290  PMB.EnablePGOCSInstrUse = true;
291  PMB.PGOInstrUse = Conf.CSIRProfile;
292  }
293  if (IsThinLTO)
294  PMB.populateThinLTOPassManager(passes);
295  else
296  PMB.populateLTOPassManager(passes);
297  passes.run(Mod);
298 }
299 
300 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
301  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
302  const ModuleSummaryIndex *ImportSummary) {
303  // FIXME: Plumb the combined index into the new pass manager.
304  if (!Conf.OptPipeline.empty())
305  runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
306  Conf.DisableVerify);
307  else if (Conf.UseNewPM)
308  runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
309  ImportSummary);
310  else
311  runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
312  return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
313 }
314 
315 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
316  unsigned Task, Module &Mod) {
317  if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
318  return;
319 
320  std::unique_ptr<ToolOutputFile> DwoOut;
321  SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
322  if (!Conf.DwoDir.empty()) {
323  std::error_code EC;
324  if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
325  report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
326  EC.message());
327 
328  DwoFile = Conf.DwoDir;
329  sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
330  TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
331  } else
333 
334  if (!DwoFile.empty()) {
335  std::error_code EC;
336  DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
337  if (EC)
338  report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
339  }
340 
341  auto Stream = AddStream(Task);
342  legacy::PassManager CodeGenPasses;
343  if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
344  DwoOut ? &DwoOut->os() : nullptr,
345  Conf.CGFileType))
346  report_fatal_error("Failed to setup codegen");
347  CodeGenPasses.run(Mod);
348 
349  if (DwoOut)
350  DwoOut->keep();
351 }
352 
353 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
354  unsigned ParallelCodeGenParallelismLevel,
355  std::unique_ptr<Module> Mod) {
356  ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
357  unsigned ThreadCount = 0;
358  const Target *T = &TM->getTarget();
359 
360  SplitModule(
361  std::move(Mod), ParallelCodeGenParallelismLevel,
362  [&](std::unique_ptr<Module> MPart) {
363  // We want to clone the module in a new context to multi-thread the
364  // codegen. We do it by serializing partition modules to bitcode
365  // (while still on the main thread, in order to avoid data races) and
366  // spinning up new threads which deserialize the partitions into
367  // separate contexts.
368  // FIXME: Provide a more direct way to do this in LLVM.
369  SmallString<0> BC;
370  raw_svector_ostream BCOS(BC);
371  WriteBitcodeToFile(*MPart, BCOS);
372 
373  // Enqueue the task
374  CodegenThreadPool.async(
375  [&](const SmallString<0> &BC, unsigned ThreadId) {
376  LTOLLVMContext Ctx(C);
378  MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
379  Ctx);
380  if (!MOrErr)
381  report_fatal_error("Failed to read bitcode");
382  std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
383 
384  std::unique_ptr<TargetMachine> TM =
385  createTargetMachine(C, T, *MPartInCtx);
386 
387  codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
388  },
389  // Pass BC using std::move to ensure that it get moved rather than
390  // copied into the thread's context.
391  std::move(BC), ThreadCount++);
392  },
393  false);
394 
395  // Because the inner lambda (which runs in a worker thread) captures our local
396  // variables, we need to wait for the worker threads to terminate before we
397  // can leave the function scope.
398  CodegenThreadPool.wait();
399 }
400 
401 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
402  if (!C.OverrideTriple.empty())
404  else if (Mod.getTargetTriple().empty())
406 
407  std::string Msg;
409  if (!T)
410  return make_error<StringError>(Msg, inconvertibleErrorCode());
411  return T;
412 }
413 
414 }
415 
416 static Error
417 finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
418  // Make sure we flush the diagnostic remarks file in case the linker doesn't
419  // call the global destructors before exiting.
420  if (!DiagOutputFile)
421  return Error::success();
422  DiagOutputFile->keep();
423  DiagOutputFile->os().flush();
424  return Error::success();
425 }
426 
428  unsigned ParallelCodeGenParallelismLevel,
429  std::unique_ptr<Module> Mod,
430  ModuleSummaryIndex &CombinedIndex) {
431  Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
432  if (!TOrErr)
433  return TOrErr.takeError();
434 
435  std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
436 
437  // Setup optimization remarks.
438  auto DiagFileOrErr = lto::setupOptimizationRemarks(
439  Mod->getContext(), C.RemarksFilename, C.RemarksPasses, C.RemarksFormat,
441  if (!DiagFileOrErr)
442  return DiagFileOrErr.takeError();
443  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
444 
445  if (!C.CodeGenOnly) {
446  if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
447  /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
448  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
449  }
450 
451  if (ParallelCodeGenParallelismLevel == 1) {
452  codegen(C, TM.get(), AddStream, 0, *Mod);
453  } else {
454  splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
455  std::move(Mod));
456  }
457  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
458 }
459 
460 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
461  const ModuleSummaryIndex &Index) {
462  std::vector<GlobalValue*> DeadGVs;
463  for (auto &GV : Mod.global_values())
464  if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
465  if (!Index.isGlobalValueLive(GVS)) {
466  DeadGVs.push_back(&GV);
468  }
469 
470  // Now that all dead bodies have been dropped, delete the actual objects
471  // themselves when possible.
472  for (GlobalValue *GV : DeadGVs) {
473  GV->removeDeadConstantUsers();
474  // Might reference something defined in native object (i.e. dropped a
475  // non-prevailing IR def, but we need to keep the declaration).
476  if (GV->use_empty())
477  GV->eraseFromParent();
478  }
479 }
480 
481 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
482  Module &Mod, const ModuleSummaryIndex &CombinedIndex,
483  const FunctionImporter::ImportMapTy &ImportList,
484  const GVSummaryMapTy &DefinedGlobals,
486  Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
487  if (!TOrErr)
488  return TOrErr.takeError();
489 
490  std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
491 
492  // Setup optimization remarks.
493  auto DiagFileOrErr = lto::setupOptimizationRemarks(
494  Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
495  Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
496  if (!DiagFileOrErr)
497  return DiagFileOrErr.takeError();
498  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
499 
500  if (Conf.CodeGenOnly) {
501  codegen(Conf, TM.get(), AddStream, Task, Mod);
502  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
503  }
504 
505  if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
506  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
507 
508  renameModuleForThinLTO(Mod, CombinedIndex);
509 
510  dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
511 
512  thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
513 
514  if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
515  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
516 
517  if (!DefinedGlobals.empty())
518  thinLTOInternalizeModule(Mod, DefinedGlobals);
519 
520  if (Conf.PostInternalizeModuleHook &&
521  !Conf.PostInternalizeModuleHook(Task, Mod))
522  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
523 
524  auto ModuleLoader = [&](StringRef Identifier) {
526  "ODR Type uniquing should be enabled on the context");
527  auto I = ModuleMap.find(Identifier);
528  assert(I != ModuleMap.end());
529  return I->second.getLazyModule(Mod.getContext(),
530  /*ShouldLazyLoadMetadata=*/true,
531  /*IsImporting*/ true);
532  };
533 
534  FunctionImporter Importer(CombinedIndex, ModuleLoader);
535  if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
536  return Err;
537 
538  if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
539  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
540 
541  if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
542  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
543  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
544 
545  codegen(Conf, TM.get(), AddStream, Task, Mod);
546  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
547 }
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, TargetMachine::CodeGenFileType FileType)
Definition: ParallelCG.cpp:27
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:915
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:240
Interfaces for registering analysis passes, producing common pass manager configurations, and parsing of pass pipelines.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
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:38
std::string AAPipeline
Definition: Config.h:69
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:232
CodeGenOpt::Level CGOptLevel
Definition: Config.h:43
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...
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:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
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: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...
Error parseAAPipeline(AAManager &AA, StringRef PipelineText)
Parse a textual alias analysis pipeline into the provided AA manager.
bool ShouldDiscardValueNames
Definition: Config.h:120
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Definition: Config.h:73
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
std::string SplitDwarfFile
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition: Config.h:56
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.
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:127
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.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:530
Optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
Definition: Module.cpp:516
OptimizationLevel
LLVM-provided high-level optimization levels.
Definition: PassBuilder.h:146
Implementation of the target library information.
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:37
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition: Config.h:115
std::unique_ptr< Module > splitCodeGen(std::unique_ptr< Module > M, ArrayRef< raw_pwrite_stream *> OSs, ArrayRef< llvm::raw_pwrite_stream *> BCOSs, const std::function< std::unique_ptr< TargetMachine >()> &TMFactory, TargetMachine::CodeGenFileType FileType=TargetMachine::CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
Definition: ParallelCG.cpp:37
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:552
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:488
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:54
Tunable parameters for passes in the default pipelines.
Definition: PassBuilder.h:70
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition: Config.h:175
Pass * Inliner
Inliner - Specifies the inliner to use.
CombinedIndexHookFn CombinedIndexHook
Definition: Config.h:188
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:986
void add(Pass *P) override
Add a pass to the queue of passes to run.
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition: Config.h:109
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:89
std::vector< std::string > MAttrs
Definition: Config.h:40
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
std::string ProfileRemapping
Name remapping file for profile data.
Definition: Config.h:86
void populateLTOPassManager(legacy::PassManagerBase &PM)
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:828
This class provides access to building LLVM&#39;s passes.
Definition: PassBuilder.h:110
Tagged union holding either a T or a Error.
Definition: yaml2obj.h:21
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:95
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:266
bool DisableVerify
Definition: Config.h:46
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:83
TargetOptions Options
Definition: Config.h:39
Optional< CodeModel::Model > CodeModel
Definition: Config.h:42
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:36
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...
PassManager manages ModulePassManagers.
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
Definition: LTOBackend.cpp:460
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
Definition: Config.h:157
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:153
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, SetVector< GlobalValue *> *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Disable as many optimizations as possible.
Definition: PassBuilder.h:150
A manager for alias analyses.
TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
bool UseNewPM
Use the new pass manager.
Definition: Config.h:49
unsigned OptLevel
Definition: Config.h:45
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:35
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
Definition: Config.h:77
Optimize for fast execution as much as possible.
Definition: PassBuilder.h:204
const Triple & getTargetTriple() const
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition: Config.h:80
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:164
size_t size() const
Definition: SmallVector.h:52
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
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.
TargetMachine::CodeGenFileType CGFileType
Definition: Config.h:44
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:204
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
std::string RemarksFilename
Optimization remarks file path.
Definition: Config.h:103
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition: Config.h:59
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
Definition: PassBuilder.h:188
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:242
Optional< Reloc::Model > RelocModel
Definition: Config.h:41
reference get()
Returns a reference to the stored T value.
Definition: Error.h:532
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
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:242
Target - Wrapper for Target specific information.
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:64
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 ...
static Error finalizeOptimizationRemarks(std::unique_ptr< ToolOutputFile > DiagOutputFile)
Definition: LTOBackend.cpp:417
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition: Config.h:112
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
Error thinBackend(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:481
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:384
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
Manages a sequence of passes over a particular unit of IR.
Definition: PassManager.h:464
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
A struct capturing PGO tunables.
Definition: PassBuilder.h:33
TargetOptions Options
#define I(x, y, z)
Definition: MD5.cpp:58
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:283
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition: Config.h:100
std::string RemarksPasses
Optimization remarks pass filter.
Definition: Config.h:106
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:96
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:185
This header provides classes for managing passes over SCCs of the call graph.
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.
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition: Config.h:167
Error backend(Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
Definition: LTOBackend.cpp:427
iterator end()
Definition: MapVector.h:71
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Optimize quickly without destroying debuggability.
Definition: PassBuilder.h:170
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1379
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:170
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:488
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:56
A derived class of LLVMContext that initializes itself according to a given Config object...
Definition: Config.h:223
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
hexagon cext opt
A container for analyses that lazily runs them and caches their results.
void addPass(PassT Pass)
Definition: PassManager.h:548
static LLVM_ATTRIBUTE_NORETURN void reportOpenError(StringRef Path, Twine Msg)
Definition: LTOBackend.cpp:50
This pass exposes codegen information to IR-level passes.
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:161
iterator_range< global_value_iterator > global_values()
Definition: Module.h:688
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
Definition: ThreadPool.cpp:71
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77