clang  15.0.0git
BackendUtil.cpp
Go to the documentation of this file.
1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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 
11 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Frontend/Utils.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/StackSafetyAnalysis.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeReader.h"
26 #include "llvm/Bitcode/BitcodeWriter.h"
27 #include "llvm/Bitcode/BitcodeWriterPass.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/SchedulerRegistry.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/IRPrintingPasses.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ModuleSummaryIndex.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/LTO/LTOBackend.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/MC/TargetRegistry.h"
42 #include "llvm/Object/OffloadBinary.h"
43 #include "llvm/Passes/PassBuilder.h"
44 #include "llvm/Passes/PassPlugin.h"
45 #include "llvm/Passes/StandardInstrumentations.h"
46 #include "llvm/Support/BuryPointer.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/PrettyStackTrace.h"
50 #include "llvm/Support/TimeProfiler.h"
51 #include "llvm/Support/Timer.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
57 #include "llvm/Transforms/Coroutines/CoroEarly.h"
58 #include "llvm/Transforms/Coroutines/CoroElide.h"
59 #include "llvm/Transforms/Coroutines/CoroSplit.h"
60 #include "llvm/Transforms/IPO.h"
61 #include "llvm/Transforms/IPO/AlwaysInliner.h"
62 #include "llvm/Transforms/IPO/LowerTypeTests.h"
63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64 #include "llvm/Transforms/InstCombine/InstCombine.h"
65 #include "llvm/Transforms/Instrumentation.h"
66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
68 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
69 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
70 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
71 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
72 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
73 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
74 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
75 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
76 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
77 #include "llvm/Transforms/ObjCARC.h"
78 #include "llvm/Transforms/Scalar.h"
79 #include "llvm/Transforms/Scalar/EarlyCSE.h"
80 #include "llvm/Transforms/Scalar/GVN.h"
81 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
82 #include "llvm/Transforms/Utils.h"
83 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
84 #include "llvm/Transforms/Utils/Debugify.h"
85 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
86 #include "llvm/Transforms/Utils/ModuleUtils.h"
87 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
88 #include "llvm/Transforms/Utils/SymbolRewriter.h"
89 #include <memory>
90 using namespace clang;
91 using namespace llvm;
92 
93 #define HANDLE_EXTENSION(Ext) \
94  llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
95 #include "llvm/Support/Extension.def"
96 
97 namespace llvm {
98 extern cl::opt<bool> DebugInfoCorrelate;
99 }
100 
101 namespace {
102 
103 // Default filename used for profile generation.
104 std::string getDefaultProfileGenName() {
105  return DebugInfoCorrelate ? "default_%p.proflite" : "default_%m.profraw";
106 }
107 
108 class EmitAssemblyHelper {
109  DiagnosticsEngine &Diags;
110  const HeaderSearchOptions &HSOpts;
111  const CodeGenOptions &CodeGenOpts;
112  const clang::TargetOptions &TargetOpts;
113  const LangOptions &LangOpts;
114  Module *TheModule;
115 
116  Timer CodeGenerationTime;
117 
118  std::unique_ptr<raw_pwrite_stream> OS;
119 
120  Triple TargetTriple;
121 
122  TargetIRAnalysis getTargetIRAnalysis() const {
123  if (TM)
124  return TM->getTargetIRAnalysis();
125 
126  return TargetIRAnalysis();
127  }
128 
129  /// Generates the TargetMachine.
130  /// Leaves TM unchanged if it is unable to create the target machine.
131  /// Some of our clang tests specify triples which are not built
132  /// into clang. This is okay because these tests check the generated
133  /// IR, and they require DataLayout which depends on the triple.
134  /// In this case, we allow this method to fail and not report an error.
135  /// When MustCreateTM is used, we print an error if we are unable to load
136  /// the requested target.
137  void CreateTargetMachine(bool MustCreateTM);
138 
139  /// Add passes necessary to emit assembly or LLVM IR.
140  ///
141  /// \return True on success.
142  bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
143  raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
144 
145  std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
146  std::error_code EC;
147  auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
148  llvm::sys::fs::OF_None);
149  if (EC) {
150  Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
151  F.reset();
152  }
153  return F;
154  }
155 
156  void
157  RunOptimizationPipeline(BackendAction Action,
158  std::unique_ptr<raw_pwrite_stream> &OS,
159  std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS);
160  void RunCodegenPipeline(BackendAction Action,
161  std::unique_ptr<raw_pwrite_stream> &OS,
162  std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
163 
164  /// Check whether we should emit a module summary for regular LTO.
165  /// The module summary should be emitted by default for regular LTO
166  /// except for ld64 targets.
167  ///
168  /// \return True if the module summary should be emitted.
169  bool shouldEmitRegularLTOSummary() const {
170  return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
171  TargetTriple.getVendor() != llvm::Triple::Apple;
172  }
173 
174 public:
175  EmitAssemblyHelper(DiagnosticsEngine &_Diags,
176  const HeaderSearchOptions &HeaderSearchOpts,
177  const CodeGenOptions &CGOpts,
178  const clang::TargetOptions &TOpts,
179  const LangOptions &LOpts, Module *M)
180  : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
181  TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
182  CodeGenerationTime("codegen", "Code Generation Time"),
183  TargetTriple(TheModule->getTargetTriple()) {}
184 
185  ~EmitAssemblyHelper() {
186  if (CodeGenOpts.DisableFree)
187  BuryPointer(std::move(TM));
188  }
189 
190  std::unique_ptr<TargetMachine> TM;
191 
192  // Emit output using the new pass manager for the optimization pipeline.
193  void EmitAssembly(BackendAction Action,
194  std::unique_ptr<raw_pwrite_stream> OS);
195 };
196 }
197 
198 static SanitizerCoverageOptions
200  SanitizerCoverageOptions Opts;
201  Opts.CoverageType =
202  static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
203  Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
204  Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
205  Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
206  Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
207  Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
208  Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
209  Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
210  Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
211  Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
212  Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
213  Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
214  Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
215  Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
216  Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
217  Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
218  return Opts;
219 }
220 
221 // Check if ASan should use GC-friendly instrumentation for globals.
222 // First of all, there is no point if -fdata-sections is off (expect for MachO,
223 // where this is not a factor). Also, on ELF this feature requires an assembler
224 // extension that only works with -integrated-as at the moment.
225 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
226  if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
227  return false;
228  switch (T.getObjectFormat()) {
229  case Triple::MachO:
230  case Triple::COFF:
231  return true;
232  case Triple::ELF:
233  return !CGOpts.DisableIntegratedAS;
234  case Triple::GOFF:
235  llvm::report_fatal_error("ASan not implemented for GOFF");
236  case Triple::XCOFF:
237  llvm::report_fatal_error("ASan not implemented for XCOFF.");
238  case Triple::Wasm:
239  case Triple::DXContainer:
240  case Triple::SPIRV:
241  case Triple::UnknownObjectFormat:
242  break;
243  }
244  return false;
245 }
246 
247 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
248  const CodeGenOptions &CodeGenOpts) {
249  TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
250 
251  switch (CodeGenOpts.getVecLib()) {
253  TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
254  break;
256  switch(TargetTriple.getArch()) {
257  default:
258  break;
259  case llvm::Triple::x86_64:
260  TLII->addVectorizableFunctionsFromVecLib
261  (TargetLibraryInfoImpl::LIBMVEC_X86);
262  break;
263  }
264  break;
266  TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
267  break;
269  TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
270  break;
272  TLII->addVectorizableFunctionsFromVecLib(
273  TargetLibraryInfoImpl::DarwinLibSystemM);
274  break;
275  default:
276  break;
277  }
278  return TLII;
279 }
280 
281 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
282  switch (CodeGenOpts.OptimizationLevel) {
283  default:
284  llvm_unreachable("Invalid optimization level!");
285  case 0:
286  return CodeGenOpt::None;
287  case 1:
288  return CodeGenOpt::Less;
289  case 2:
290  return CodeGenOpt::Default; // O2/Os/Oz
291  case 3:
292  return CodeGenOpt::Aggressive;
293  }
294 }
295 
297 getCodeModel(const CodeGenOptions &CodeGenOpts) {
298  unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
299  .Case("tiny", llvm::CodeModel::Tiny)
300  .Case("small", llvm::CodeModel::Small)
301  .Case("kernel", llvm::CodeModel::Kernel)
302  .Case("medium", llvm::CodeModel::Medium)
303  .Case("large", llvm::CodeModel::Large)
304  .Case("default", ~1u)
305  .Default(~0u);
306  assert(CodeModel != ~0u && "invalid code model!");
307  if (CodeModel == ~1u)
308  return None;
309  return static_cast<llvm::CodeModel::Model>(CodeModel);
310 }
311 
312 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
313  if (Action == Backend_EmitObj)
314  return CGFT_ObjectFile;
315  else if (Action == Backend_EmitMCNull)
316  return CGFT_Null;
317  else {
318  assert(Action == Backend_EmitAssembly && "Invalid action!");
319  return CGFT_AssemblyFile;
320  }
321 }
322 
324  return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
325  Action != Backend_EmitLL;
326 }
327 
329  llvm::TargetOptions &Options,
330  const CodeGenOptions &CodeGenOpts,
331  const clang::TargetOptions &TargetOpts,
332  const LangOptions &LangOpts,
333  const HeaderSearchOptions &HSOpts) {
334  switch (LangOpts.getThreadModel()) {
336  Options.ThreadModel = llvm::ThreadModel::POSIX;
337  break;
339  Options.ThreadModel = llvm::ThreadModel::Single;
340  break;
341  }
342 
343  // Set float ABI type.
344  assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
345  CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
346  "Invalid Floating Point ABI!");
347  Options.FloatABIType =
348  llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
349  .Case("soft", llvm::FloatABI::Soft)
350  .Case("softfp", llvm::FloatABI::Soft)
351  .Case("hard", llvm::FloatABI::Hard)
352  .Default(llvm::FloatABI::Default);
353 
354  // Set FP fusion mode.
355  switch (LangOpts.getDefaultFPContractMode()) {
357  // Preserve any contraction performed by the front-end. (Strict performs
358  // splitting of the muladd intrinsic in the backend.)
359  Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
360  break;
361  case LangOptions::FPM_On:
363  Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
364  break;
366  Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
367  break;
368  }
369 
370  Options.BinutilsVersion =
371  llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
372  Options.UseInitArray = CodeGenOpts.UseInitArray;
373  Options.LowerGlobalDtorsViaCxaAtExit =
374  CodeGenOpts.RegisterGlobalDtorsWithAtExit;
375  Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
376  Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
377  Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
378 
379  // Set EABI version.
380  Options.EABIVersion = TargetOpts.EABIVersion;
381 
382  if (LangOpts.hasSjLjExceptions())
383  Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
384  if (LangOpts.hasSEHExceptions())
385  Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
386  if (LangOpts.hasDWARFExceptions())
387  Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
388  if (LangOpts.hasWasmExceptions())
389  Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
390 
391  Options.NoInfsFPMath = LangOpts.NoHonorInfs;
392  Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
393  Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
394  Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
395  Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
396 
397  Options.BBSections =
398  llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
399  .Case("all", llvm::BasicBlockSection::All)
400  .Case("labels", llvm::BasicBlockSection::Labels)
401  .StartsWith("list=", llvm::BasicBlockSection::List)
402  .Case("none", llvm::BasicBlockSection::None)
404 
405  if (Options.BBSections == llvm::BasicBlockSection::List) {
406  ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
407  MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
408  if (!MBOrErr) {
409  Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
410  << MBOrErr.getError().message();
411  return false;
412  }
413  Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
414  }
415 
416  Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
417  Options.FunctionSections = CodeGenOpts.FunctionSections;
418  Options.DataSections = CodeGenOpts.DataSections;
419  Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
420  Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
421  Options.UniqueBasicBlockSectionNames =
422  CodeGenOpts.UniqueBasicBlockSectionNames;
423  Options.TLSSize = CodeGenOpts.TLSSize;
424  Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
425  Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
426  Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
427  Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
428  Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
429  Options.EmitAddrsig = CodeGenOpts.Addrsig;
430  Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
431  Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
432  Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
433  Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
434  Options.LoopAlignment = CodeGenOpts.LoopAlignment;
435  Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
436  Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
437  Options.Hotpatch = CodeGenOpts.HotPatch;
438  Options.JMCInstrument = CodeGenOpts.JMCInstrument;
439 
440  switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
442  Options.SwiftAsyncFramePointer =
443  SwiftAsyncFramePointerMode::DeploymentBased;
444  break;
445 
447  Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
448  break;
449 
451  Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
452  break;
453  }
454 
455  Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
456  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
457  Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
458  Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
459  Options.MCOptions.MCUseDwarfDirectory =
460  CodeGenOpts.NoDwarfDirectoryAsm
461  ? llvm::MCTargetOptions::DisableDwarfDirectory
462  : llvm::MCTargetOptions::EnableDwarfDirectory;
463  Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
464  Options.MCOptions.MCIncrementalLinkerCompatible =
465  CodeGenOpts.IncrementalLinkerCompatible;
466  Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
467  Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
468  Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
469  Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
470  Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
471  Options.MCOptions.ABIName = TargetOpts.ABI;
472  for (const auto &Entry : HSOpts.UserEntries)
473  if (!Entry.IsFramework &&
474  (Entry.Group == frontend::IncludeDirGroup::Quoted ||
475  Entry.Group == frontend::IncludeDirGroup::Angled ||
476  Entry.Group == frontend::IncludeDirGroup::System))
477  Options.MCOptions.IASSearchPaths.push_back(
478  Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
479  Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
480  Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
481  Options.MisExpect = CodeGenOpts.MisExpect;
482 
483  return true;
484 }
485 
487  const LangOptions &LangOpts) {
488  if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
489  return None;
490  // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
491  // LLVM's -default-gcov-version flag is set to something invalid.
492  GCOVOptions Options;
493  Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
494  Options.EmitData = CodeGenOpts.EmitGcovArcs;
495  llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
496  Options.NoRedZone = CodeGenOpts.DisableRedZone;
497  Options.Filter = CodeGenOpts.ProfileFilterFiles;
498  Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
499  Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
500  return Options;
501 }
502 
505  const LangOptions &LangOpts) {
506  if (!CodeGenOpts.hasProfileClangInstr())
507  return None;
508  InstrProfOptions Options;
509  Options.NoRedZone = CodeGenOpts.DisableRedZone;
510  Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
511  Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
512  return Options;
513 }
514 
515 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
516  SmallVector<const char *, 16> BackendArgs;
517  BackendArgs.push_back("clang"); // Fake program name.
518  if (!CodeGenOpts.DebugPass.empty()) {
519  BackendArgs.push_back("-debug-pass");
520  BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
521  }
522  if (!CodeGenOpts.LimitFloatPrecision.empty()) {
523  BackendArgs.push_back("-limit-float-precision");
524  BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
525  }
526  // Check for the default "clang" invocation that won't set any cl::opt values.
527  // Skip trying to parse the command line invocation to avoid the issues
528  // described below.
529  if (BackendArgs.size() == 1)
530  return;
531  BackendArgs.push_back(nullptr);
532  // FIXME: The command line parser below is not thread-safe and shares a global
533  // state, so this call might crash or overwrite the options of another Clang
534  // instance in the same process.
535  llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
536  BackendArgs.data());
537 }
538 
539 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
540  // Create the TargetMachine for generating code.
542  std::string Triple = TheModule->getTargetTriple();
543  const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
544  if (!TheTarget) {
545  if (MustCreateTM)
546  Diags.Report(diag::err_fe_unable_to_create_target) << Error;
547  return;
548  }
549 
551  std::string FeaturesStr =
552  llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
553  llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
554  CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
555 
556  llvm::TargetOptions Options;
557  if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
558  HSOpts))
559  return;
560  TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
561  Options, RM, CM, OptLevel));
562 }
563 
564 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
565  BackendAction Action,
566  raw_pwrite_stream &OS,
567  raw_pwrite_stream *DwoOS) {
568  // Add LibraryInfo.
569  std::unique_ptr<TargetLibraryInfoImpl> TLII(
570  createTLII(TargetTriple, CodeGenOpts));
571  CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
572 
573  // Normal mode, emit a .s or .o file by running the code generator. Note,
574  // this also adds codegenerator level optimization passes.
575  CodeGenFileType CGFT = getCodeGenFileType(Action);
576 
577  // Add ObjC ARC final-cleanup optimizations. This is done as part of the
578  // "codegen" passes so that it isn't run multiple times when there is
579  // inlining happening.
580  if (CodeGenOpts.OptimizationLevel > 0)
581  CodeGenPasses.add(createObjCARCContractPass());
582 
583  if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
584  /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
585  Diags.Report(diag::err_fe_unable_to_interface_with_target);
586  return false;
587  }
588 
589  return true;
590 }
591 
592 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
593  switch (Opts.OptimizationLevel) {
594  default:
595  llvm_unreachable("Invalid optimization level!");
596 
597  case 0:
598  return OptimizationLevel::O0;
599 
600  case 1:
601  return OptimizationLevel::O1;
602 
603  case 2:
604  switch (Opts.OptimizeSize) {
605  default:
606  llvm_unreachable("Invalid optimization level for size!");
607 
608  case 0:
609  return OptimizationLevel::O2;
610 
611  case 1:
612  return OptimizationLevel::Os;
613 
614  case 2:
615  return OptimizationLevel::Oz;
616  }
617 
618  case 3:
619  return OptimizationLevel::O3;
620  }
621 }
622 
623 static void addSanitizers(const Triple &TargetTriple,
624  const CodeGenOptions &CodeGenOpts,
625  const LangOptions &LangOpts, PassBuilder &PB) {
626  PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
627  OptimizationLevel Level) {
628  if (CodeGenOpts.hasSanitizeCoverage()) {
629  auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
630  MPM.addPass(ModuleSanitizerCoveragePass(
631  SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
632  CodeGenOpts.SanitizeCoverageIgnorelistFiles));
633  }
634 
635  auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
636  if (LangOpts.Sanitize.has(Mask)) {
637  int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
638  bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
639 
640  MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
641  CodeGenOpts.SanitizeMemoryParamRetval);
642  MPM.addPass(ModuleMemorySanitizerPass(options));
643  FunctionPassManager FPM;
644  FPM.addPass(MemorySanitizerPass(options));
645  if (Level != OptimizationLevel::O0) {
646  // MemorySanitizer inserts complex instrumentation that mostly
647  // follows the logic of the original code, but operates on
648  // "shadow" values. It can benefit from re-running some
649  // general purpose optimization passes.
650  FPM.addPass(EarlyCSEPass());
651  // TODO: Consider add more passes like in
652  // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
653  // difference on size. It's not clear if the rest is still
654  // usefull. InstCombinePass breakes
655  // compiler-rt/test/msan/select_origin.cpp.
656  }
657  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
658  }
659  };
660  MSanPass(SanitizerKind::Memory, false);
661  MSanPass(SanitizerKind::KernelMemory, true);
662 
663  if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
664  MPM.addPass(ModuleThreadSanitizerPass());
665  MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
666  }
667 
668  auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
669  if (LangOpts.Sanitize.has(Mask)) {
670  bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
671  bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
672  llvm::AsanDtorKind DestructorKind =
673  CodeGenOpts.getSanitizeAddressDtor();
674  AddressSanitizerOptions Opts;
675  Opts.CompileKernel = CompileKernel;
676  Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
677  Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
678  Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
679  MPM.addPass(ModuleAddressSanitizerPass(
680  Opts, UseGlobalGC, UseOdrIndicator, DestructorKind));
681  }
682  };
683  ASanPass(SanitizerKind::Address, false);
684  ASanPass(SanitizerKind::KernelAddress, true);
685 
686  auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
687  if (LangOpts.Sanitize.has(Mask)) {
688  bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
689  MPM.addPass(HWAddressSanitizerPass(
690  {CompileKernel, Recover,
691  /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
692  }
693  };
694  HWASanPass(SanitizerKind::HWAddress, false);
695  HWASanPass(SanitizerKind::KernelHWAddress, true);
696 
697  if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
698  MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
699  }
700  });
701 }
702 
703 void EmitAssemblyHelper::RunOptimizationPipeline(
704  BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
705  std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) {
706  Optional<PGOOptions> PGOOpt;
707 
708  if (CodeGenOpts.hasProfileIRInstr())
709  // -fprofile-generate.
710  PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
711  ? getDefaultProfileGenName()
712  : CodeGenOpts.InstrProfileOutput,
713  "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
714  CodeGenOpts.DebugInfoForProfiling);
715  else if (CodeGenOpts.hasProfileIRUse()) {
716  // -fprofile-use.
717  auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
718  : PGOOptions::NoCSAction;
719  PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
720  CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
721  CSAction, CodeGenOpts.DebugInfoForProfiling);
722  } else if (!CodeGenOpts.SampleProfileFile.empty())
723  // -fprofile-sample-use
724  PGOOpt = PGOOptions(
725  CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
726  PGOOptions::SampleUse, PGOOptions::NoCSAction,
727  CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
728  else if (CodeGenOpts.PseudoProbeForProfiling)
729  // -fpseudo-probe-for-profiling
730  PGOOpt =
731  PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
732  CodeGenOpts.DebugInfoForProfiling, true);
733  else if (CodeGenOpts.DebugInfoForProfiling)
734  // -fdebug-info-for-profiling
735  PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
736  PGOOptions::NoCSAction, true);
737 
738  // Check to see if we want to generate a CS profile.
739  if (CodeGenOpts.hasProfileCSIRInstr()) {
740  assert(!CodeGenOpts.hasProfileCSIRUse() &&
741  "Cannot have both CSProfileUse pass and CSProfileGen pass at "
742  "the same time");
743  if (PGOOpt) {
744  assert(PGOOpt->Action != PGOOptions::IRInstr &&
745  PGOOpt->Action != PGOOptions::SampleUse &&
746  "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
747  " pass");
748  PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
749  ? getDefaultProfileGenName()
750  : CodeGenOpts.InstrProfileOutput;
751  PGOOpt->CSAction = PGOOptions::CSIRInstr;
752  } else
753  PGOOpt = PGOOptions("",
754  CodeGenOpts.InstrProfileOutput.empty()
755  ? getDefaultProfileGenName()
756  : CodeGenOpts.InstrProfileOutput,
757  "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
758  CodeGenOpts.DebugInfoForProfiling);
759  }
760  if (TM)
761  TM->setPGOOption(PGOOpt);
762 
763  PipelineTuningOptions PTO;
764  PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
765  // For historical reasons, loop interleaving is set to mirror setting for loop
766  // unrolling.
767  PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
768  PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
769  PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
770  PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
771  // Only enable CGProfilePass when using integrated assembler, since
772  // non-integrated assemblers don't recognize .cgprofile section.
773  PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
774 
775  LoopAnalysisManager LAM;
776  FunctionAnalysisManager FAM;
777  CGSCCAnalysisManager CGAM;
778  ModuleAnalysisManager MAM;
779 
780  bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
781  PassInstrumentationCallbacks PIC;
782  PrintPassOptions PrintPassOpts;
783  PrintPassOpts.Indent = DebugPassStructure;
784  PrintPassOpts.SkipAnalyses = DebugPassStructure;
785  StandardInstrumentations SI(CodeGenOpts.DebugPassManager ||
786  DebugPassStructure,
787  /*VerifyEach*/ false, PrintPassOpts);
788  SI.registerCallbacks(PIC, &FAM);
789  PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
790 
791  // Attempt to load pass plugins and register their callbacks with PB.
792  for (auto &PluginFN : CodeGenOpts.PassPlugins) {
793  auto PassPlugin = PassPlugin::Load(PluginFN);
794  if (PassPlugin) {
795  PassPlugin->registerPassBuilderCallbacks(PB);
796  } else {
797  Diags.Report(diag::err_fe_unable_to_load_plugin)
798  << PluginFN << toString(PassPlugin.takeError());
799  }
800  }
801 #define HANDLE_EXTENSION(Ext) \
802  get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
803 #include "llvm/Support/Extension.def"
804 
805  // Register the target library analysis directly and give it a customized
806  // preset TLI.
807  std::unique_ptr<TargetLibraryInfoImpl> TLII(
808  createTLII(TargetTriple, CodeGenOpts));
809  FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
810 
811  // Register all the basic analyses with the managers.
812  PB.registerModuleAnalyses(MAM);
813  PB.registerCGSCCAnalyses(CGAM);
814  PB.registerFunctionAnalyses(FAM);
815  PB.registerLoopAnalyses(LAM);
816  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
817 
818  ModulePassManager MPM;
819 
820  if (!CodeGenOpts.DisableLLVMPasses) {
821  // Map our optimization levels into one of the distinct levels used to
822  // configure the pipeline.
823  OptimizationLevel Level = mapToLevel(CodeGenOpts);
824 
825  bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
826  bool IsLTO = CodeGenOpts.PrepareForLTO;
827 
828  if (LangOpts.ObjCAutoRefCount) {
829  PB.registerPipelineStartEPCallback(
830  [](ModulePassManager &MPM, OptimizationLevel Level) {
831  if (Level != OptimizationLevel::O0)
832  MPM.addPass(
833  createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
834  });
835  PB.registerPipelineEarlySimplificationEPCallback(
836  [](ModulePassManager &MPM, OptimizationLevel Level) {
837  if (Level != OptimizationLevel::O0)
838  MPM.addPass(ObjCARCAPElimPass());
839  });
840  PB.registerScalarOptimizerLateEPCallback(
841  [](FunctionPassManager &FPM, OptimizationLevel Level) {
842  if (Level != OptimizationLevel::O0)
843  FPM.addPass(ObjCARCOptPass());
844  });
845  }
846 
847  // If we reached here with a non-empty index file name, then the index
848  // file was empty and we are not performing ThinLTO backend compilation
849  // (used in testing in a distributed build environment).
850  bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
851  // If so drop any the type test assume sequences inserted for whole program
852  // vtables so that codegen doesn't complain.
853  if (IsThinLTOPostLink)
854  PB.registerPipelineStartEPCallback(
855  [](ModulePassManager &MPM, OptimizationLevel Level) {
856  MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
857  /*ImportSummary=*/nullptr,
858  /*DropTypeTests=*/true));
859  });
860 
861  if (CodeGenOpts.InstrumentFunctions ||
862  CodeGenOpts.InstrumentFunctionEntryBare ||
863  CodeGenOpts.InstrumentFunctionsAfterInlining ||
864  CodeGenOpts.InstrumentForProfiling) {
865  PB.registerPipelineStartEPCallback(
866  [](ModulePassManager &MPM, OptimizationLevel Level) {
867  MPM.addPass(createModuleToFunctionPassAdaptor(
868  EntryExitInstrumenterPass(/*PostInlining=*/false)));
869  });
870  PB.registerOptimizerLastEPCallback(
871  [](ModulePassManager &MPM, OptimizationLevel Level) {
872  MPM.addPass(createModuleToFunctionPassAdaptor(
873  EntryExitInstrumenterPass(/*PostInlining=*/true)));
874  });
875  }
876 
877  // Register callbacks to schedule sanitizer passes at the appropriate part
878  // of the pipeline.
879  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
880  PB.registerScalarOptimizerLateEPCallback(
881  [](FunctionPassManager &FPM, OptimizationLevel Level) {
882  FPM.addPass(BoundsCheckingPass());
883  });
884 
885  // Don't add sanitizers if we are here from ThinLTO PostLink. That already
886  // done on PreLink stage.
887  if (!IsThinLTOPostLink)
888  addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
889 
890  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
891  PB.registerPipelineStartEPCallback(
892  [Options](ModulePassManager &MPM, OptimizationLevel Level) {
893  MPM.addPass(GCOVProfilerPass(*Options));
894  });
895  if (Optional<InstrProfOptions> Options =
896  getInstrProfOptions(CodeGenOpts, LangOpts))
897  PB.registerPipelineStartEPCallback(
898  [Options](ModulePassManager &MPM, OptimizationLevel Level) {
899  MPM.addPass(InstrProfiling(*Options, false));
900  });
901 
902  if (CodeGenOpts.OptimizationLevel == 0) {
903  MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
904  } else if (IsThinLTO) {
905  MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
906  } else if (IsLTO) {
907  MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
908  } else {
909  MPM = PB.buildPerModuleDefaultPipeline(Level);
910  }
911 
912  if (!CodeGenOpts.MemoryProfileOutput.empty()) {
913  MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
914  MPM.addPass(ModuleMemProfilerPass());
915  }
916  }
917 
918  // Add a verifier pass if requested. We don't have to do this if the action
919  // requires code generation because there will already be a verifier pass in
920  // the code-generation pipeline.
921  if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
922  MPM.addPass(VerifierPass());
923 
924  switch (Action) {
925  case Backend_EmitBC:
926  if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
927  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
928  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
929  if (!ThinLinkOS)
930  return;
931  }
932  if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
933  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
934  CodeGenOpts.EnableSplitLTOUnit);
935  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
936  : nullptr));
937  } else {
938  // Emit a module summary by default for Regular LTO except for ld64
939  // targets
940  bool EmitLTOSummary = shouldEmitRegularLTOSummary();
941  if (EmitLTOSummary) {
942  if (!TheModule->getModuleFlag("ThinLTO"))
943  TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
944  if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
945  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
946  uint32_t(1));
947  }
948  MPM.addPass(
949  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
950  }
951  break;
952 
953  case Backend_EmitLL:
954  MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
955  break;
956 
957  default:
958  break;
959  }
960 
961  // Now that we have all of the passes ready, run them.
962  {
963  PrettyStackTraceString CrashInfo("Optimizer");
964  llvm::TimeTraceScope TimeScope("Optimizer");
965  MPM.run(*TheModule, MAM);
966  }
967 }
968 
969 void EmitAssemblyHelper::RunCodegenPipeline(
970  BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
971  std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
972  // We still use the legacy PM to run the codegen pipeline since the new PM
973  // does not work with the codegen pipeline.
974  // FIXME: make the new PM work with the codegen pipeline.
975  legacy::PassManager CodeGenPasses;
976 
977  // Append any output we need to the pass manager.
978  switch (Action) {
980  case Backend_EmitMCNull:
981  case Backend_EmitObj:
982  CodeGenPasses.add(
983  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
984  if (!CodeGenOpts.SplitDwarfOutput.empty()) {
985  DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
986  if (!DwoOS)
987  return;
988  }
989  if (!AddEmitPasses(CodeGenPasses, Action, *OS,
990  DwoOS ? &DwoOS->os() : nullptr))
991  // FIXME: Should we handle this error differently?
992  return;
993  break;
994  default:
995  return;
996  }
997 
998  {
999  PrettyStackTraceString CrashInfo("Code generation");
1000  llvm::TimeTraceScope TimeScope("CodeGenPasses");
1001  CodeGenPasses.run(*TheModule);
1002  }
1003 }
1004 
1006  std::unique_ptr<raw_pwrite_stream> OS) {
1007  TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1008  setCommandLineOpts(CodeGenOpts);
1009 
1010  bool RequiresCodeGen = actionRequiresCodeGen(Action);
1011  CreateTargetMachine(RequiresCodeGen);
1012 
1013  if (RequiresCodeGen && !TM)
1014  return;
1015  if (TM)
1016  TheModule->setDataLayout(TM->createDataLayout());
1017 
1018  // Before executing passes, print the final values of the LLVM options.
1019  cl::PrintOptionValues();
1020 
1021  std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1022  RunOptimizationPipeline(Action, OS, ThinLinkOS);
1023  RunCodegenPipeline(Action, OS, DwoOS);
1024 
1025  if (ThinLinkOS)
1026  ThinLinkOS->keep();
1027  if (DwoOS)
1028  DwoOS->keep();
1029 }
1030 
1031 static void runThinLTOBackend(
1032  DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1033  const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1034  const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1035  std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1036  std::string ProfileRemapping, BackendAction Action) {
1037  StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1038  ModuleToDefinedGVSummaries;
1039  CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1040 
1041  setCommandLineOpts(CGOpts);
1042 
1043  // We can simply import the values mentioned in the combined index, since
1044  // we should only invoke this using the individual indexes written out
1045  // via a WriteIndexesThinBackend.
1046  FunctionImporter::ImportMapTy ImportList;
1047  if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1048  return;
1049 
1050  auto AddStream = [&](size_t Task) {
1051  return std::make_unique<CachedFileStream>(std::move(OS),
1052  CGOpts.ObjectFilenameForDebug);
1053  };
1054  lto::Config Conf;
1055  if (CGOpts.SaveTempsFilePrefix != "") {
1056  if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1057  /* UseInputModulePath */ false)) {
1058  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1059  errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1060  << '\n';
1061  });
1062  }
1063  }
1064  Conf.CPU = TOpts.CPU;
1065  Conf.CodeModel = getCodeModel(CGOpts);
1066  Conf.MAttrs = TOpts.Features;
1067  Conf.RelocModel = CGOpts.RelocationModel;
1068  Conf.CGOptLevel = getCGOptLevel(CGOpts);
1069  Conf.OptLevel = CGOpts.OptimizationLevel;
1070  initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1071  Conf.SampleProfile = std::move(SampleProfile);
1072  Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1073  // For historical reasons, loop interleaving is set to mirror setting for loop
1074  // unrolling.
1075  Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1076  Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1077  Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1078  // Only enable CGProfilePass when using integrated assembler, since
1079  // non-integrated assemblers don't recognize .cgprofile section.
1080  Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1081 
1082  // Context sensitive profile.
1083  if (CGOpts.hasProfileCSIRInstr()) {
1084  Conf.RunCSIRInstr = true;
1085  Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1086  } else if (CGOpts.hasProfileCSIRUse()) {
1087  Conf.RunCSIRInstr = false;
1088  Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1089  }
1090 
1091  Conf.ProfileRemapping = std::move(ProfileRemapping);
1092  Conf.DebugPassManager = CGOpts.DebugPassManager;
1093  Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1094  Conf.RemarksFilename = CGOpts.OptRecordFile;
1095  Conf.RemarksPasses = CGOpts.OptRecordPasses;
1096  Conf.RemarksFormat = CGOpts.OptRecordFormat;
1097  Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1098  Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1099  switch (Action) {
1100  case Backend_EmitNothing:
1101  Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1102  return false;
1103  };
1104  break;
1105  case Backend_EmitLL:
1106  Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1107  M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1108  return false;
1109  };
1110  break;
1111  case Backend_EmitBC:
1112  Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1113  WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1114  return false;
1115  };
1116  break;
1117  default:
1118  Conf.CGFileType = getCodeGenFileType(Action);
1119  break;
1120  }
1121  if (Error E =
1122  thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1123  ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1124  /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1125  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1126  errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1127  });
1128  }
1129 }
1130 
1132  const HeaderSearchOptions &HeaderOpts,
1133  const CodeGenOptions &CGOpts,
1134  const clang::TargetOptions &TOpts,
1135  const LangOptions &LOpts,
1136  StringRef TDesc, Module *M,
1137  BackendAction Action,
1138  std::unique_ptr<raw_pwrite_stream> OS) {
1139 
1140  llvm::TimeTraceScope TimeScope("Backend");
1141 
1142  std::unique_ptr<llvm::Module> EmptyModule;
1143  if (!CGOpts.ThinLTOIndexFile.empty()) {
1144  // If we are performing a ThinLTO importing compile, load the function index
1145  // into memory and pass it into runThinLTOBackend, which will run the
1146  // function importer and invoke LTO passes.
1147  std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1148  if (Error E = llvm::getModuleSummaryIndexForFile(
1149  CGOpts.ThinLTOIndexFile,
1150  /*IgnoreEmptyThinLTOIndexFile*/ true)
1151  .moveInto(CombinedIndex)) {
1152  logAllUnhandledErrors(std::move(E), errs(),
1153  "Error loading index file '" +
1154  CGOpts.ThinLTOIndexFile + "': ");
1155  return;
1156  }
1157 
1158  // A null CombinedIndex means we should skip ThinLTO compilation
1159  // (LLVM will optionally ignore empty index files, returning null instead
1160  // of an error).
1161  if (CombinedIndex) {
1162  if (!CombinedIndex->skipModuleByDistributedBackend()) {
1163  runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1164  TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1165  CGOpts.ProfileRemappingFile, Action);
1166  return;
1167  }
1168  // Distributed indexing detected that nothing from the module is needed
1169  // for the final linking. So we can skip the compilation. We sill need to
1170  // output an empty object file to make sure that a linker does not fail
1171  // trying to read it. Also for some features, like CFI, we must skip
1172  // the compilation as CombinedIndex does not contain all required
1173  // information.
1174  EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1175  EmptyModule->setTargetTriple(M->getTargetTriple());
1176  M = EmptyModule.get();
1177  }
1178  }
1179 
1180  EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1181  AsmHelper.EmitAssembly(Action, std::move(OS));
1182 
1183  // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1184  // DataLayout.
1185  if (AsmHelper.TM) {
1186  std::string DLDesc = M->getDataLayout().getStringRepresentation();
1187  if (DLDesc != TDesc) {
1188  unsigned DiagID = Diags.getCustomDiagID(
1189  DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1190  "expected target description '%1'");
1191  Diags.Report(DiagID) << DLDesc << TDesc;
1192  }
1193  }
1194 }
1195 
1196 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1197 // __LLVM,__bitcode section.
1198 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1199  llvm::MemoryBufferRef Buf) {
1200  if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1201  return;
1202  llvm::embedBitcodeInModule(
1203  *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1204  CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1205  CGOpts.CmdArgs);
1206 }
1207 
1208 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1209  DiagnosticsEngine &Diags) {
1210  if (CGOpts.OffloadObjects.empty())
1211  return;
1212 
1213  for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1214  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1215  llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1216  if (std::error_code EC = ObjectOrErr.getError()) {
1217  auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1218  "could not open '%0' for embedding");
1219  Diags.Report(DiagID) << OffloadObject;
1220  return;
1221  }
1222 
1223  llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1224  Align(object::OffloadBinary::getAlignment()));
1225  }
1226 }
clang::CodeGenOptions::BinutilsVersion
std::string BinutilsVersion
Definition: CodeGenOptions.h:125
clang::CodeGenOptions::Argv0
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
Definition: CodeGenOptions.h:404
clang::LangOptions::hasSEHExceptions
bool hasSEHExceptions() const
Definition: LangOptions.h:580
addSanitizers
static void addSanitizers(const Triple &TargetTriple, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
Definition: BackendUtil.cpp:623
llvm
YAML serialization mapping.
Definition: Dominators.h:30
clang::CodeGenOptions::ThinLinkBitcodeFile
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
Definition: CodeGenOptions.h:270
initTargetOptions
static bool initTargetOptions(DiagnosticsEngine &Diags, llvm::TargetOptions &Options, const CodeGenOptions &CodeGenOpts, const clang::TargetOptions &TargetOpts, const LangOptions &LangOpts, const HeaderSearchOptions &HSOpts)
Definition: BackendUtil.cpp:328
clang::frontend::EmitAssembly
@ EmitAssembly
Emit a .s file.
Definition: FrontendOptions.h:58
clang::CodeGenOptions::InstrProfileOutput
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
Definition: CodeGenOptions.h:248
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::CodeGenOptions::SanitizeRecover
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
Definition: CodeGenOptions.h:350
getCodeGenFileType
static CodeGenFileType getCodeGenFileType(BackendAction Action)
Definition: BackendUtil.cpp:312
getCodeModel
static Optional< llvm::CodeModel::Model > getCodeModel(const CodeGenOptions &CodeGenOpts)
Definition: BackendUtil.cpp:297
llvm::SmallVector
Definition: LLVM.h:38
clang::CodeGenOptions::CommandLineArgs
std::vector< std::string > CommandLineArgs
Definition: CodeGenOptions.h:405
clang::CodeGenOptions::SwiftAsyncFramePointerKind::Auto
@ Auto
clang::CodeGenOptions::hasSanitizeCoverage
bool hasSanitizeCoverage() const
Definition: CodeGenOptions.h:480
clang::SanitizerSet::has
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:155
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::CodeGenOptions::SampleProfileFile
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
Definition: CodeGenOptions.h:251
clang::CodeGenOptions::SaveTempsFilePrefix
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
Definition: CodeGenOptions.h:273
clang::LangOptions::FPM_On
@ FPM_On
Definition: LangOptions.h:253
llvm::Optional
Definition: LLVM.h:40
clang::CodeGenOptions::CodeModel
std::string CodeModel
The code model to use (-mcmodel).
Definition: CodeGenOptions.h:147
clang::Backend_EmitLL
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:33
actionRequiresCodeGen
static bool actionRequiresCodeGen(BackendAction Action)
Definition: BackendUtil.cpp:323
clang::CodeGenOptions::hasProfileCSIRUse
bool hasProfileCSIRUse() const
Check if CSIR profile use is on.
Definition: CodeGenOptions.h:467
clang::LangOptions::hasDWARFExceptions
bool hasDWARFExceptions() const
Definition: LangOptions.h:584
clang::CodeGenOptions::ObjectFilenameForDebug
std::string ObjectFilenameForDebug
Output filename used in the COFF debug information.
Definition: CodeGenOptions.h:231
clang::CodeGenOptions::DebugPass
std::string DebugPass
Enable additional debugging information.
Definition: CodeGenOptions.h:167
clang::CodeGenOptions::ProfileFilterFiles
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
Definition: CodeGenOptions.h:158
CodeGenOptions.h
clang::CodeGenOptions::ProfileRemappingFile
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
Definition: CodeGenOptions.h:261
clang::CodeGenOptions::Always
@ Always
clang::CodeGenOptions::SplitDwarfFile
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: CodeGenOptions.h:225
clang::XRayInstrKind::All
constexpr XRayInstrMask All
Definition: XRayInstr.h:43
clang::frontend::System
@ System
Like Angled, but marks system directories.
Definition: HeaderSearchOptions.h:43
BackendUtil.h
clang::CodeGenOptions::FloatABI
std::string FloatABI
The ABI to use for passing floating point arguments.
Definition: CodeGenOptions.h:187
clang::Module
Describes a module or submodule.
Definition: Module.h:96
HeaderSearchOptions.h
clang::CodeGenOptions::CmdArgs
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
Definition: CodeGenOptions.h:356
clang::CodeGenOptions::MASSV
@ MASSV
Definition: CodeGenOptions.h:61
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::CodeGenOptions::MemoryProfileOutput
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
Definition: CodeGenOptions.h:254
clang::LangOptions::hasWasmExceptions
bool hasWasmExceptions() const
Definition: LangOptions.h:588
clang::HeaderSearchOptions::Sysroot
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
Definition: HeaderSearchOptions.h:100
clang::BackendAction
BackendAction
Definition: BackendUtil.h:30
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:90
setCommandLineOpts
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts)
Definition: BackendUtil.cpp:515
clang::LangOptions::ThreadModelKind::POSIX
@ POSIX
POSIX Threads.
clang::CodeGenOptions::SplitDwarfOutput
std::string SplitDwarfOutput
Output filename for the split debug info, not used in the skeleton CU.
Definition: CodeGenOptions.h:228
LangOptions.h
Diagnostic.h
getGCOVOptions
static Optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
Definition: BackendUtil.cpp:486
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:200
Utils.h
clang::TargetOptions::ABI
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
clang::CodeGenOptions::PassPlugins
std::vector< std::string > PassPlugins
List of dynamic shared object files to be loaded as pass plugins.
Definition: CodeGenOptions.h:374
clang::interp::Load
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:618
clang::CodeGenOptions::OptRecordFormat
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
Definition: CodeGenOptions.h:292
runThinLTOBackend
static void runThinLTOBackend(DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M, const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts, const LangOptions &LOpts, std::unique_ptr< raw_pwrite_stream > OS, std::string SampleProfile, std::string ProfileRemapping, BackendAction Action)
Definition: BackendUtil.cpp:1031
clang::frontend::Quoted
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Definition: HeaderSearchOptions.h:34
clang::CodeGenOptions::OffloadObjects
std::vector< std::string > OffloadObjects
List of filenames passed in using the -fembed-offload-object option.
Definition: CodeGenOptions.h:281
clang::LangOptions::hasSjLjExceptions
bool hasSjLjExceptions() const
Definition: LangOptions.h:576
clang::Backend_EmitBC
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition: BackendUtil.h:32
clang::Backend_EmitMCNull
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition: BackendUtil.h:35
llvm::DebugInfoCorrelate
cl::opt< bool > DebugInfoCorrelate
clang::EmbedBitcode
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
Definition: BackendUtil.cpp:1198
clang::CodeGenOptions
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Definition: CodeGenOptions.h:49
clang::CodeGenOptions::CoverageVersion
char CoverageVersion[4]
The version string to put into coverage files.
Definition: CodeGenOptions.h:164
clang::CodeGenOptions::LimitFloatPrecision
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
Definition: CodeGenOptions.h:200
clang::LangOptions::Sanitize
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:368
clang::frontend::Angled
@ Angled
Paths for '#include <>' added by '-I'.
Definition: HeaderSearchOptions.h:37
clang::CodeGenOptions::Embed_Off
@ Embed_Off
Definition: CodeGenOptions.h:94
clang::TargetOptions::Features
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
getCGOptLevel
static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts)
Definition: BackendUtil.cpp:281
getInstrProfOptions
static Optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
Definition: BackendUtil.cpp:504
clang::CodeGenOptions::hasProfileIRUse
bool hasProfileIRUse() const
Check if IR level profile use is on.
Definition: CodeGenOptions.h:461
clang::CodeGenOptions::Darwin_libsystem_m
@ Darwin_libsystem_m
Definition: CodeGenOptions.h:63
clang::LangOptions::NoSanitizeFiles
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
Definition: LangOptions.h:374
clang::CodeGenOptions::RelocationModel
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
Definition: CodeGenOptions.h:234
TargetOptions.h
clang::EmbedObject
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
Definition: BackendUtil.cpp:1208
clang::LangOptions::ThreadModelKind::Single
@ Single
Single Threaded Environment.
clang::EmitBackendOutput
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, std::unique_ptr< raw_pwrite_stream > OS)
clang::CodeGenOptions::hasProfileCSIRInstr
bool hasProfileCSIRInstr() const
Check if CS IR level profile instrumentation is on.
Definition: CodeGenOptions.h:451
clang::LangOptions::FPM_FastHonorPragmas
@ FPM_FastHonorPragmas
Definition: LangOptions.h:259
clang::HeaderSearchOptions::UserEntries
std::vector< Entry > UserEntries
User specified include entries.
Definition: HeaderSearchOptions.h:103
clang::CodeGenOptions::LIBMVEC
@ LIBMVEC
Definition: CodeGenOptions.h:60
clang::CodeGenOptions::hasProfileClangInstr
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
Definition: CodeGenOptions.h:441
getSancovOptsFromCGOpts
static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts)
Definition: BackendUtil.cpp:199
clang::Backend_EmitAssembly
@ Backend_EmitAssembly
Emit native assembly files.
Definition: BackendUtil.h:31
clang::TargetOptions::CPU
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
clang::CodeGenOptions::BBSections
std::string BBSections
Definition: CodeGenOptions.h:119
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:78
clang::CodeGenOptions::StackUsageOutput
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
Definition: CodeGenOptions.h:400
clang::DiagnosticsEngine::getCustomDiagID
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:868
clang
Definition: CalledOnceCheck.h:17
clang::CodeGenOptions::Accelerate
@ Accelerate
Definition: CodeGenOptions.h:59
asanUseGlobalsGC
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
Definition: BackendUtil.cpp:225
FrontendDiagnostic.h
clang::CodeGenOptions::OptRecordFile
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
Definition: CodeGenOptions.h:285
clang::CodeGenOptions::SVML
@ SVML
Definition: CodeGenOptions.h:62
clang::Module::print
void print(raw_ostream &OS, unsigned Indent=0, bool Dump=false) const
Print the module map for this module to the given stream.
Definition: Module.cpp:434
clang::prec::Level
Level
Definition: OperatorPrecedence.h:26
clang::CodeGenOptions::ThinLTOIndexFile
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
Definition: CodeGenOptions.h:265
clang::CodeGenOptions::Embed_Marker
@ Embed_Marker
Definition: CodeGenOptions.h:97
clang::Backend_EmitNothing
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition: BackendUtil.h:34
clang::TargetOptions::EABIVersion
llvm::EABI EABIVersion
The EABI version to use.
Definition: TargetOptions.h:48
clang::CodeGenOptions::ProfileExcludeFiles
std::string ProfileExcludeFiles
Regexes separated by a semi-colon to filter the files to not instrument.
Definition: CodeGenOptions.h:161
clang::LangOptions::FPM_Off
@ FPM_Off
Definition: LangOptions.h:250
clang::Backend_EmitObj
@ Backend_EmitObj
Emit native object files.
Definition: BackendUtil.h:36
clang::TargetOptions
Options for controlling the target.
Definition: TargetOptions.h:26
createTLII
static TargetLibraryInfoImpl * createTLII(llvm::Triple &TargetTriple, const CodeGenOptions &CodeGenOpts)
Definition: BackendUtil.cpp:247
clang::CodeGenOptions::ProfileInstrumentUsePath
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
Definition: CodeGenOptions.h:257
clang::CodeGenOptions::Embed_Bitcode
@ Embed_Bitcode
Definition: CodeGenOptions.h:96
clang::CodeGenOptions::hasProfileIRInstr
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
Definition: CodeGenOptions.h:446
clang::LangOptions::FPM_Fast
@ FPM_Fast
Definition: LangOptions.h:256
clang::CodeGenOptions::OptRecordPasses
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
Definition: CodeGenOptions.h:289
clang::SanitizerMask
Definition: Sanitizers.h:30
clang::ento::ObjKind::OS
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
mapToLevel
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts)
Definition: BackendUtil.cpp:592
clang::HeaderSearchOptions
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Definition: HeaderSearchOptions.h:68
clang::CodeGenOptions::Never
@ Never
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1537
Type
MatchType Type
Definition: ASTMatchFinder.cpp:71