clang  9.0.0svn
BackendUtil.cpp
Go to the documentation of this file.
1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
12 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Frontend/Utils.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/LTO/LTOBackend.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Passes/PassBuilder.h"
40 #include "llvm/Support/BuryPointer.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/PrettyStackTrace.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Transforms/Coroutines.h"
50 #include "llvm/Transforms/IPO.h"
51 #include "llvm/Transforms/IPO/AlwaysInliner.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
54 #include "llvm/Transforms/InstCombine/InstCombine.h"
55 #include "llvm/Transforms/Instrumentation.h"
56 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
57 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
58 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
59 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
60 #include "llvm/Transforms/ObjCARC.h"
61 #include "llvm/Transforms/Scalar.h"
62 #include "llvm/Transforms/Scalar/GVN.h"
63 #include "llvm/Transforms/Utils.h"
64 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
65 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
66 #include "llvm/Transforms/Utils/SymbolRewriter.h"
67 #include <memory>
68 using namespace clang;
69 using namespace llvm;
70 
71 namespace {
72 
73 // Default filename used for profile generation.
74 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
75 
76 class EmitAssemblyHelper {
77  DiagnosticsEngine &Diags;
78  const HeaderSearchOptions &HSOpts;
79  const CodeGenOptions &CodeGenOpts;
80  const clang::TargetOptions &TargetOpts;
81  const LangOptions &LangOpts;
82  Module *TheModule;
83 
84  Timer CodeGenerationTime;
85 
86  std::unique_ptr<raw_pwrite_stream> OS;
87 
88  TargetIRAnalysis getTargetIRAnalysis() const {
89  if (TM)
90  return TM->getTargetIRAnalysis();
91 
92  return TargetIRAnalysis();
93  }
94 
95  void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
96 
97  /// Generates the TargetMachine.
98  /// Leaves TM unchanged if it is unable to create the target machine.
99  /// Some of our clang tests specify triples which are not built
100  /// into clang. This is okay because these tests check the generated
101  /// IR, and they require DataLayout which depends on the triple.
102  /// In this case, we allow this method to fail and not report an error.
103  /// When MustCreateTM is used, we print an error if we are unable to load
104  /// the requested target.
105  void CreateTargetMachine(bool MustCreateTM);
106 
107  /// Add passes necessary to emit assembly or LLVM IR.
108  ///
109  /// \return True on success.
110  bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
111  raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
112 
113  std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
114  std::error_code EC;
115  auto F = llvm::make_unique<llvm::ToolOutputFile>(Path, EC,
116  llvm::sys::fs::F_None);
117  if (EC) {
118  Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
119  F.reset();
120  }
121  return F;
122  }
123 
124 public:
125  EmitAssemblyHelper(DiagnosticsEngine &_Diags,
126  const HeaderSearchOptions &HeaderSearchOpts,
127  const CodeGenOptions &CGOpts,
128  const clang::TargetOptions &TOpts,
129  const LangOptions &LOpts, Module *M)
130  : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
131  TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
132  CodeGenerationTime("codegen", "Code Generation Time") {}
133 
134  ~EmitAssemblyHelper() {
135  if (CodeGenOpts.DisableFree)
136  BuryPointer(std::move(TM));
137  }
138 
139  std::unique_ptr<TargetMachine> TM;
140 
141  void EmitAssembly(BackendAction Action,
142  std::unique_ptr<raw_pwrite_stream> OS);
143 
144  void EmitAssemblyWithNewPassManager(BackendAction Action,
145  std::unique_ptr<raw_pwrite_stream> OS);
146 };
147 
148 // We need this wrapper to access LangOpts and CGOpts from extension functions
149 // that we add to the PassManagerBuilder.
150 class PassManagerBuilderWrapper : public PassManagerBuilder {
151 public:
152  PassManagerBuilderWrapper(const Triple &TargetTriple,
153  const CodeGenOptions &CGOpts,
154  const LangOptions &LangOpts)
155  : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
156  LangOpts(LangOpts) {}
157  const Triple &getTargetTriple() const { return TargetTriple; }
158  const CodeGenOptions &getCGOpts() const { return CGOpts; }
159  const LangOptions &getLangOpts() const { return LangOpts; }
160 
161 private:
162  const Triple &TargetTriple;
163  const CodeGenOptions &CGOpts;
164  const LangOptions &LangOpts;
165 };
166 }
167 
168 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
169  if (Builder.OptLevel > 0)
170  PM.add(createObjCARCAPElimPass());
171 }
172 
173 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
174  if (Builder.OptLevel > 0)
175  PM.add(createObjCARCExpandPass());
176 }
177 
178 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
179  if (Builder.OptLevel > 0)
180  PM.add(createObjCARCOptPass());
181 }
182 
183 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
184  legacy::PassManagerBase &PM) {
185  PM.add(createAddDiscriminatorsPass());
186 }
187 
188 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
189  legacy::PassManagerBase &PM) {
190  PM.add(createBoundsCheckingLegacyPass());
191 }
192 
193 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
194  legacy::PassManagerBase &PM) {
195  const PassManagerBuilderWrapper &BuilderWrapper =
196  static_cast<const PassManagerBuilderWrapper&>(Builder);
197  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
198  SanitizerCoverageOptions Opts;
199  Opts.CoverageType =
200  static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
201  Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
202  Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
203  Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
204  Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
205  Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
206  Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
207  Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
208  Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
209  Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
210  Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
211  Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
212  Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
213  PM.add(createSanitizerCoverageModulePass(Opts));
214 }
215 
216 // Check if ASan should use GC-friendly instrumentation for globals.
217 // First of all, there is no point if -fdata-sections is off (expect for MachO,
218 // where this is not a factor). Also, on ELF this feature requires an assembler
219 // extension that only works with -integrated-as at the moment.
220 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
221  if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
222  return false;
223  switch (T.getObjectFormat()) {
224  case Triple::MachO:
225  case Triple::COFF:
226  return true;
227  case Triple::ELF:
228  return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
229  default:
230  return false;
231  }
232 }
233 
234 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
235  legacy::PassManagerBase &PM) {
236  const PassManagerBuilderWrapper &BuilderWrapper =
237  static_cast<const PassManagerBuilderWrapper&>(Builder);
238  const Triple &T = BuilderWrapper.getTargetTriple();
239  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
240  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
241  bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
242  bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
243  bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
244  PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
245  UseAfterScope));
246  PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
247  UseGlobalsGC, UseOdrIndicator));
248 }
249 
250 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
251  legacy::PassManagerBase &PM) {
252  PM.add(createAddressSanitizerFunctionPass(
253  /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
254  PM.add(createAddressSanitizerModulePass(
255  /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
256  /*UseOdrIndicator*/ false));
257 }
258 
259 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
260  legacy::PassManagerBase &PM) {
261  const PassManagerBuilderWrapper &BuilderWrapper =
262  static_cast<const PassManagerBuilderWrapper &>(Builder);
263  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
264  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
265  PM.add(createHWAddressSanitizerPass(/*CompileKernel*/ false, Recover));
266 }
267 
268 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
269  legacy::PassManagerBase &PM) {
270  PM.add(createHWAddressSanitizerPass(
271  /*CompileKernel*/ true, /*Recover*/ true));
272 }
273 
274 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
275  legacy::PassManagerBase &PM,
276  bool CompileKernel) {
277  const PassManagerBuilderWrapper &BuilderWrapper =
278  static_cast<const PassManagerBuilderWrapper&>(Builder);
279  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
280  int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
281  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
282  PM.add(createMemorySanitizerLegacyPassPass(TrackOrigins, Recover, CompileKernel));
283 
284  // MemorySanitizer inserts complex instrumentation that mostly follows
285  // the logic of the original code, but operates on "shadow" values.
286  // It can benefit from re-running some general purpose optimization passes.
287  if (Builder.OptLevel > 0) {
288  PM.add(createEarlyCSEPass());
289  PM.add(createReassociatePass());
290  PM.add(createLICMPass());
291  PM.add(createGVNPass());
292  PM.add(createInstructionCombiningPass());
293  PM.add(createDeadStoreEliminationPass());
294  }
295 }
296 
297 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
298  legacy::PassManagerBase &PM) {
299  addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
300 }
301 
302 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
303  legacy::PassManagerBase &PM) {
304  addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
305 }
306 
307 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
308  legacy::PassManagerBase &PM) {
309  PM.add(createThreadSanitizerLegacyPassPass());
310 }
311 
312 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
313  legacy::PassManagerBase &PM) {
314  const PassManagerBuilderWrapper &BuilderWrapper =
315  static_cast<const PassManagerBuilderWrapper&>(Builder);
316  const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
317  PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
318 }
319 
320 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
321  legacy::PassManagerBase &PM) {
322  const PassManagerBuilderWrapper &BuilderWrapper =
323  static_cast<const PassManagerBuilderWrapper&>(Builder);
324  const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
325  EfficiencySanitizerOptions Opts;
326  if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
327  Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
328  else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
329  Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
330  PM.add(createEfficiencySanitizerPass(Opts));
331 }
332 
333 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
334  const CodeGenOptions &CodeGenOpts) {
335  TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
336  if (!CodeGenOpts.SimplifyLibCalls)
337  TLII->disableAllFunctions();
338  else {
339  // Disable individual libc/libm calls in TargetLibraryInfo.
340  LibFunc F;
341  for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
342  if (TLII->getLibFunc(FuncName, F))
343  TLII->setUnavailable(F);
344  }
345 
346  switch (CodeGenOpts.getVecLib()) {
348  TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
349  break;
351  TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
352  break;
353  default:
354  break;
355  }
356  return TLII;
357 }
358 
359 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
360  legacy::PassManager *MPM) {
361  llvm::SymbolRewriter::RewriteDescriptorList DL;
362 
363  llvm::SymbolRewriter::RewriteMapParser MapParser;
364  for (const auto &MapFile : Opts.RewriteMapFiles)
365  MapParser.parse(MapFile, &DL);
366 
367  MPM->add(createRewriteSymbolsPass(DL));
368 }
369 
370 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
371  switch (CodeGenOpts.OptimizationLevel) {
372  default:
373  llvm_unreachable("Invalid optimization level!");
374  case 0:
375  return CodeGenOpt::None;
376  case 1:
377  return CodeGenOpt::Less;
378  case 2:
379  return CodeGenOpt::Default; // O2/Os/Oz
380  case 3:
381  return CodeGenOpt::Aggressive;
382  }
383 }
384 
386 getCodeModel(const CodeGenOptions &CodeGenOpts) {
387  unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
388  .Case("tiny", llvm::CodeModel::Tiny)
389  .Case("small", llvm::CodeModel::Small)
390  .Case("kernel", llvm::CodeModel::Kernel)
391  .Case("medium", llvm::CodeModel::Medium)
392  .Case("large", llvm::CodeModel::Large)
393  .Case("default", ~1u)
394  .Default(~0u);
395  assert(CodeModel != ~0u && "invalid code model!");
396  if (CodeModel == ~1u)
397  return None;
398  return static_cast<llvm::CodeModel::Model>(CodeModel);
399 }
400 
401 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
402  if (Action == Backend_EmitObj)
403  return TargetMachine::CGFT_ObjectFile;
404  else if (Action == Backend_EmitMCNull)
405  return TargetMachine::CGFT_Null;
406  else {
407  assert(Action == Backend_EmitAssembly && "Invalid action!");
408  return TargetMachine::CGFT_AssemblyFile;
409  }
410 }
411 
412 static void initTargetOptions(llvm::TargetOptions &Options,
413  const CodeGenOptions &CodeGenOpts,
414  const clang::TargetOptions &TargetOpts,
415  const LangOptions &LangOpts,
416  const HeaderSearchOptions &HSOpts) {
417  Options.ThreadModel =
418  llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
419  .Case("posix", llvm::ThreadModel::POSIX)
420  .Case("single", llvm::ThreadModel::Single);
421 
422  // Set float ABI type.
423  assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
424  CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
425  "Invalid Floating Point ABI!");
426  Options.FloatABIType =
427  llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
428  .Case("soft", llvm::FloatABI::Soft)
429  .Case("softfp", llvm::FloatABI::Soft)
430  .Case("hard", llvm::FloatABI::Hard)
431  .Default(llvm::FloatABI::Default);
432 
433  // Set FP fusion mode.
434  switch (LangOpts.getDefaultFPContractMode()) {
436  // Preserve any contraction performed by the front-end. (Strict performs
437  // splitting of the muladd intrinsic in the backend.)
438  Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
439  break;
440  case LangOptions::FPC_On:
441  Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
442  break;
444  Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
445  break;
446  }
447 
448  Options.UseInitArray = CodeGenOpts.UseInitArray;
449  Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
450  Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
451  Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
452 
453  // Set EABI version.
454  Options.EABIVersion = TargetOpts.EABIVersion;
455 
456  if (LangOpts.SjLjExceptions)
457  Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
458  if (LangOpts.SEHExceptions)
459  Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
460  if (LangOpts.DWARFExceptions)
461  Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
462 
463  Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
464  Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
465  Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
466  Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
467  Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
468  Options.FunctionSections = CodeGenOpts.FunctionSections;
469  Options.DataSections = CodeGenOpts.DataSections;
470  Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
471  Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
472  Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
473  Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
474  Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
475  Options.EmitAddrsig = CodeGenOpts.Addrsig;
476 
477  if (CodeGenOpts.getSplitDwarfMode() != CodeGenOptions::NoFission)
478  Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
479  Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
480  Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
481  Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
482  Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
483  Options.MCOptions.MCIncrementalLinkerCompatible =
484  CodeGenOpts.IncrementalLinkerCompatible;
485  Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
486  Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
487  Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
488  Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
489  Options.MCOptions.ABIName = TargetOpts.ABI;
490  for (const auto &Entry : HSOpts.UserEntries)
491  if (!Entry.IsFramework &&
492  (Entry.Group == frontend::IncludeDirGroup::Quoted ||
493  Entry.Group == frontend::IncludeDirGroup::Angled ||
494  Entry.Group == frontend::IncludeDirGroup::System))
495  Options.MCOptions.IASSearchPaths.push_back(
496  Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
497 }
499  if (CodeGenOpts.DisableGCov)
500  return None;
501  if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
502  return None;
503  // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
504  // LLVM's -default-gcov-version flag is set to something invalid.
505  GCOVOptions Options;
506  Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
507  Options.EmitData = CodeGenOpts.EmitGcovArcs;
508  llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
509  Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
510  Options.NoRedZone = CodeGenOpts.DisableRedZone;
511  Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
512  Options.Filter = CodeGenOpts.ProfileFilterFiles;
513  Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
514  Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
515  return Options;
516 }
517 
518 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
519  legacy::FunctionPassManager &FPM) {
520  // Handle disabling of all LLVM passes, where we want to preserve the
521  // internal module before any optimization.
522  if (CodeGenOpts.DisableLLVMPasses)
523  return;
524 
525  // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
526  // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
527  // are inserted before PMBuilder ones - they'd get the default-constructed
528  // TLI with an unknown target otherwise.
529  Triple TargetTriple(TheModule->getTargetTriple());
530  std::unique_ptr<TargetLibraryInfoImpl> TLII(
531  createTLII(TargetTriple, CodeGenOpts));
532 
533  PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
534 
535  // At O0 and O1 we only run the always inliner which is more efficient. At
536  // higher optimization levels we run the normal inliner.
537  if (CodeGenOpts.OptimizationLevel <= 1) {
538  bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
539  !CodeGenOpts.DisableLifetimeMarkers);
540  PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
541  } else {
542  // We do not want to inline hot callsites for SamplePGO module-summary build
543  // because profile annotation will happen again in ThinLTO backend, and we
544  // want the IR of the hot path to match the profile.
545  PMBuilder.Inliner = createFunctionInliningPass(
546  CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
547  (!CodeGenOpts.SampleProfileFile.empty() &&
548  CodeGenOpts.PrepareForThinLTO));
549  }
550 
551  PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
552  PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
553  PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
554  PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
555 
556  PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
557  PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
558  PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
559  PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
560  PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
561 
562  MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
563 
564  if (TM)
565  TM->adjustPassManager(PMBuilder);
566 
567  if (CodeGenOpts.DebugInfoForProfiling ||
568  !CodeGenOpts.SampleProfileFile.empty())
569  PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
571 
572  // In ObjC ARC mode, add the main ARC optimization passes.
573  if (LangOpts.ObjCAutoRefCount) {
574  PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
576  PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
578  PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
580  }
581 
582  if (LangOpts.CoroutinesTS)
583  addCoroutinePassesToExtensionPoints(PMBuilder);
584 
585  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
586  PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
588  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
590  }
591 
592  if (CodeGenOpts.SanitizeCoverageType ||
593  CodeGenOpts.SanitizeCoverageIndirectCalls ||
594  CodeGenOpts.SanitizeCoverageTraceCmp) {
595  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
597  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
599  }
600 
601  if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
602  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
604  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
606  }
607 
608  if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
609  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
611  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
613  }
614 
615  if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
616  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
618  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
620  }
621 
622  if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
623  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
625  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
627  }
628 
629  if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
630  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
632  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
634  }
635 
636  if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
637  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
639  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
641  }
642 
643  if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
644  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
646  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
648  }
649 
650  if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
651  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
653  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
655  }
656 
657  if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
658  PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
660  PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
662  }
663 
664  // Set up the per-function pass manager.
665  FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
666  if (CodeGenOpts.VerifyModule)
667  FPM.add(createVerifierPass());
668 
669  // Set up the per-module pass manager.
670  if (!CodeGenOpts.RewriteMapFiles.empty())
671  addSymbolRewriterPass(CodeGenOpts, &MPM);
672 
673  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
674  MPM.add(createGCOVProfilerPass(*Options));
675  if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
676  MPM.add(createStripSymbolsPass(true));
677  }
678 
679  if (CodeGenOpts.hasProfileClangInstr()) {
680  InstrProfOptions Options;
681  Options.NoRedZone = CodeGenOpts.DisableRedZone;
682  Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
683 
684  // TODO: Surface the option to emit atomic profile counter increments at
685  // the driver level.
686  Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
687 
688  MPM.add(createInstrProfilingLegacyPass(Options));
689  }
690  if (CodeGenOpts.hasProfileIRInstr()) {
691  PMBuilder.EnablePGOInstrGen = true;
692  if (!CodeGenOpts.InstrProfileOutput.empty())
693  PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
694  else
695  PMBuilder.PGOInstrGen = DefaultProfileGenName;
696  }
697  if (CodeGenOpts.hasProfileIRUse())
698  PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
699 
700  if (!CodeGenOpts.SampleProfileFile.empty())
701  PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
702 
703  PMBuilder.populateFunctionPassManager(FPM);
704  PMBuilder.populateModulePassManager(MPM);
705 }
706 
707 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
708  SmallVector<const char *, 16> BackendArgs;
709  BackendArgs.push_back("clang"); // Fake program name.
710  if (!CodeGenOpts.DebugPass.empty()) {
711  BackendArgs.push_back("-debug-pass");
712  BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
713  }
714  if (!CodeGenOpts.LimitFloatPrecision.empty()) {
715  BackendArgs.push_back("-limit-float-precision");
716  BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
717  }
718  BackendArgs.push_back(nullptr);
719  llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
720  BackendArgs.data());
721 }
722 
723 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
724  // Create the TargetMachine for generating code.
725  std::string Error;
726  std::string Triple = TheModule->getTargetTriple();
727  const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
728  if (!TheTarget) {
729  if (MustCreateTM)
730  Diags.Report(diag::err_fe_unable_to_create_target) << Error;
731  return;
732  }
733 
735  std::string FeaturesStr =
736  llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
737  llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
738  CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
739 
740  llvm::TargetOptions Options;
741  initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
742  TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
743  Options, RM, CM, OptLevel));
744 }
745 
746 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
747  BackendAction Action,
748  raw_pwrite_stream &OS,
749  raw_pwrite_stream *DwoOS) {
750  // Add LibraryInfo.
751  llvm::Triple TargetTriple(TheModule->getTargetTriple());
752  std::unique_ptr<TargetLibraryInfoImpl> TLII(
753  createTLII(TargetTriple, CodeGenOpts));
754  CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
755 
756  // Normal mode, emit a .s or .o file by running the code generator. Note,
757  // this also adds codegenerator level optimization passes.
758  TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
759 
760  // Add ObjC ARC final-cleanup optimizations. This is done as part of the
761  // "codegen" passes so that it isn't run multiple times when there is
762  // inlining happening.
763  if (CodeGenOpts.OptimizationLevel > 0)
764  CodeGenPasses.add(createObjCARCContractPass());
765 
766  if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
767  /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
768  Diags.Report(diag::err_fe_unable_to_interface_with_target);
769  return false;
770  }
771 
772  return true;
773 }
774 
776  std::unique_ptr<raw_pwrite_stream> OS) {
777  TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
778 
779  setCommandLineOpts(CodeGenOpts);
780 
781  bool UsesCodeGen = (Action != Backend_EmitNothing &&
782  Action != Backend_EmitBC &&
783  Action != Backend_EmitLL);
784  CreateTargetMachine(UsesCodeGen);
785 
786  if (UsesCodeGen && !TM)
787  return;
788  if (TM)
789  TheModule->setDataLayout(TM->createDataLayout());
790 
791  legacy::PassManager PerModulePasses;
792  PerModulePasses.add(
793  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
794 
795  legacy::FunctionPassManager PerFunctionPasses(TheModule);
796  PerFunctionPasses.add(
797  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
798 
799  CreatePasses(PerModulePasses, PerFunctionPasses);
800 
801  legacy::PassManager CodeGenPasses;
802  CodeGenPasses.add(
803  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
804 
805  std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
806 
807  switch (Action) {
808  case Backend_EmitNothing:
809  break;
810 
811  case Backend_EmitBC:
812  if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
813  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
814  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
815  if (!ThinLinkOS)
816  return;
817  }
818  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
819  CodeGenOpts.EnableSplitLTOUnit);
820  PerModulePasses.add(createWriteThinLTOBitcodePass(
821  *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
822  } else {
823  // Emit a module summary by default for Regular LTO except for ld64
824  // targets
825  bool EmitLTOSummary =
826  (CodeGenOpts.PrepareForLTO &&
827  !CodeGenOpts.DisableLLVMPasses &&
828  llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
829  llvm::Triple::Apple);
830  if (EmitLTOSummary) {
831  if (!TheModule->getModuleFlag("ThinLTO"))
832  TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
833  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
834  CodeGenOpts.EnableSplitLTOUnit);
835  }
836 
837  PerModulePasses.add(createBitcodeWriterPass(
838  *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
839  }
840  break;
841 
842  case Backend_EmitLL:
843  PerModulePasses.add(
844  createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
845  break;
846 
847  default:
848  if (!CodeGenOpts.SplitDwarfFile.empty() &&
849  (CodeGenOpts.getSplitDwarfMode() == CodeGenOptions::SplitFileFission)) {
850  DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
851  if (!DwoOS)
852  return;
853  }
854  if (!AddEmitPasses(CodeGenPasses, Action, *OS,
855  DwoOS ? &DwoOS->os() : nullptr))
856  return;
857  }
858 
859  // Before executing passes, print the final values of the LLVM options.
860  cl::PrintOptionValues();
861 
862  // Run passes. For now we do all passes at once, but eventually we
863  // would like to have the option of streaming code generation.
864 
865  {
866  PrettyStackTraceString CrashInfo("Per-function optimization");
867 
868  PerFunctionPasses.doInitialization();
869  for (Function &F : *TheModule)
870  if (!F.isDeclaration())
871  PerFunctionPasses.run(F);
872  PerFunctionPasses.doFinalization();
873  }
874 
875  {
876  PrettyStackTraceString CrashInfo("Per-module optimization passes");
877  PerModulePasses.run(*TheModule);
878  }
879 
880  {
881  PrettyStackTraceString CrashInfo("Code generation");
882  CodeGenPasses.run(*TheModule);
883  }
884 
885  if (ThinLinkOS)
886  ThinLinkOS->keep();
887  if (DwoOS)
888  DwoOS->keep();
889 }
890 
891 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
892  switch (Opts.OptimizationLevel) {
893  default:
894  llvm_unreachable("Invalid optimization level!");
895 
896  case 1:
897  return PassBuilder::O1;
898 
899  case 2:
900  switch (Opts.OptimizeSize) {
901  default:
902  llvm_unreachable("Invalid optimization level for size!");
903 
904  case 0:
905  return PassBuilder::O2;
906 
907  case 1:
908  return PassBuilder::Os;
909 
910  case 2:
911  return PassBuilder::Oz;
912  }
913 
914  case 3:
915  return PassBuilder::O3;
916  }
917 }
918 
919 /// A clean version of `EmitAssembly` that uses the new pass manager.
920 ///
921 /// Not all features are currently supported in this system, but where
922 /// necessary it falls back to the legacy pass manager to at least provide
923 /// basic functionality.
924 ///
925 /// This API is planned to have its functionality finished and then to replace
926 /// `EmitAssembly` at some point in the future when the default switches.
927 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
928  BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
929  TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
930  setCommandLineOpts(CodeGenOpts);
931 
932  // The new pass manager always makes a target machine available to passes
933  // during construction.
934  CreateTargetMachine(/*MustCreateTM*/ true);
935  if (!TM)
936  // This will already be diagnosed, just bail.
937  return;
938  TheModule->setDataLayout(TM->createDataLayout());
939 
940  Optional<PGOOptions> PGOOpt;
941 
942  if (CodeGenOpts.hasProfileIRInstr())
943  // -fprofile-generate.
944  PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
945  ? DefaultProfileGenName
946  : CodeGenOpts.InstrProfileOutput,
947  "", "", "", true,
948  CodeGenOpts.DebugInfoForProfiling);
949  else if (CodeGenOpts.hasProfileIRUse())
950  // -fprofile-use.
951  PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "",
952  CodeGenOpts.ProfileRemappingFile, false,
953  CodeGenOpts.DebugInfoForProfiling);
954  else if (!CodeGenOpts.SampleProfileFile.empty())
955  // -fprofile-sample-use
956  PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile,
957  CodeGenOpts.ProfileRemappingFile, false,
958  CodeGenOpts.DebugInfoForProfiling);
959  else if (CodeGenOpts.DebugInfoForProfiling)
960  // -fdebug-info-for-profiling
961  PGOOpt = PGOOptions("", "", "", "", false, true);
962 
963  PassBuilder PB(TM.get(), PGOOpt);
964 
965  LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
966  FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
967  CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
968  ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
969 
970  // Register the AA manager first so that our version is the one used.
971  FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
972 
973  // Register the target library analysis directly and give it a customized
974  // preset TLI.
975  Triple TargetTriple(TheModule->getTargetTriple());
976  std::unique_ptr<TargetLibraryInfoImpl> TLII(
977  createTLII(TargetTriple, CodeGenOpts));
978  FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
979  MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
980 
981  // Register all the basic analyses with the managers.
982  PB.registerModuleAnalyses(MAM);
983  PB.registerCGSCCAnalyses(CGAM);
984  PB.registerFunctionAnalyses(FAM);
985  PB.registerLoopAnalyses(LAM);
986  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
987 
988  ModulePassManager MPM(CodeGenOpts.DebugPassManager);
989 
990  if (!CodeGenOpts.DisableLLVMPasses) {
991  bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
992  bool IsLTO = CodeGenOpts.PrepareForLTO;
993 
994  if (CodeGenOpts.OptimizationLevel == 0) {
995  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
996  MPM.addPass(GCOVProfilerPass(*Options));
997 
998  // Build a minimal pipeline based on the semantics required by Clang,
999  // which is just that always inlining occurs.
1000  MPM.addPass(AlwaysInlinerPass());
1001 
1002  // At -O0 we directly run necessary sanitizer passes.
1003  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1004  MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1005 
1006  // Lastly, add semantically necessary passes for LTO.
1007  if (IsLTO || IsThinLTO) {
1008  MPM.addPass(CanonicalizeAliasesPass());
1009  MPM.addPass(NameAnonGlobalPass());
1010  }
1011  } else {
1012  // Map our optimization levels into one of the distinct levels used to
1013  // configure the pipeline.
1014  PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1015 
1016  // Register callbacks to schedule sanitizer passes at the appropriate part of
1017  // the pipeline.
1018  // FIXME: either handle asan/the remaining sanitizers or error out
1019  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1020  PB.registerScalarOptimizerLateEPCallback(
1021  [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1022  FPM.addPass(BoundsCheckingPass());
1023  });
1024  if (LangOpts.Sanitize.has(SanitizerKind::Memory))
1025  PB.registerOptimizerLastEPCallback(
1026  [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1027  FPM.addPass(MemorySanitizerPass());
1028  });
1029  if (LangOpts.Sanitize.has(SanitizerKind::Thread))
1030  PB.registerOptimizerLastEPCallback(
1031  [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1032  FPM.addPass(ThreadSanitizerPass());
1033  });
1034  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1035  PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1036  MPM.addPass(GCOVProfilerPass(*Options));
1037  });
1038 
1039  if (IsThinLTO) {
1040  MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1041  Level, CodeGenOpts.DebugPassManager);
1042  MPM.addPass(CanonicalizeAliasesPass());
1043  MPM.addPass(NameAnonGlobalPass());
1044  } else if (IsLTO) {
1045  MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1046  CodeGenOpts.DebugPassManager);
1047  MPM.addPass(CanonicalizeAliasesPass());
1048  MPM.addPass(NameAnonGlobalPass());
1049  } else {
1050  MPM = PB.buildPerModuleDefaultPipeline(Level,
1051  CodeGenOpts.DebugPassManager);
1052  }
1053  }
1054  }
1055 
1056  // FIXME: We still use the legacy pass manager to do code generation. We
1057  // create that pass manager here and use it as needed below.
1058  legacy::PassManager CodeGenPasses;
1059  bool NeedCodeGen = false;
1060  std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1061 
1062  // Append any output we need to the pass manager.
1063  switch (Action) {
1064  case Backend_EmitNothing:
1065  break;
1066 
1067  case Backend_EmitBC:
1068  if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1069  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1070  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1071  if (!ThinLinkOS)
1072  return;
1073  }
1074  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1075  CodeGenOpts.EnableSplitLTOUnit);
1076  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1077  : nullptr));
1078  } else {
1079  // Emit a module summary by default for Regular LTO except for ld64
1080  // targets
1081  bool EmitLTOSummary =
1082  (CodeGenOpts.PrepareForLTO &&
1083  !CodeGenOpts.DisableLLVMPasses &&
1084  llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1085  llvm::Triple::Apple);
1086  if (EmitLTOSummary) {
1087  if (!TheModule->getModuleFlag("ThinLTO"))
1088  TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1089  TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1090  CodeGenOpts.EnableSplitLTOUnit);
1091  }
1092  MPM.addPass(
1093  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1094  }
1095  break;
1096 
1097  case Backend_EmitLL:
1098  MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1099  break;
1100 
1101  case Backend_EmitAssembly:
1102  case Backend_EmitMCNull:
1103  case Backend_EmitObj:
1104  NeedCodeGen = true;
1105  CodeGenPasses.add(
1106  createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1107  if (!CodeGenOpts.SplitDwarfFile.empty()) {
1108  DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
1109  if (!DwoOS)
1110  return;
1111  }
1112  if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1113  DwoOS ? &DwoOS->os() : nullptr))
1114  // FIXME: Should we handle this error differently?
1115  return;
1116  break;
1117  }
1118 
1119  // Before executing passes, print the final values of the LLVM options.
1120  cl::PrintOptionValues();
1121 
1122  // Now that we have all of the passes ready, run them.
1123  {
1124  PrettyStackTraceString CrashInfo("Optimizer");
1125  MPM.run(*TheModule, MAM);
1126  }
1127 
1128  // Now if needed, run the legacy PM for codegen.
1129  if (NeedCodeGen) {
1130  PrettyStackTraceString CrashInfo("Code generation");
1131  CodeGenPasses.run(*TheModule);
1132  }
1133 
1134  if (ThinLinkOS)
1135  ThinLinkOS->keep();
1136  if (DwoOS)
1137  DwoOS->keep();
1138 }
1139 
1140 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1141  Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1142  if (!BMsOrErr)
1143  return BMsOrErr.takeError();
1144 
1145  // The bitcode file may contain multiple modules, we want the one that is
1146  // marked as being the ThinLTO module.
1147  if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1148  return *Bm;
1149 
1150  return make_error<StringError>("Could not find module summary",
1151  inconvertibleErrorCode());
1152 }
1153 
1155  for (BitcodeModule &BM : BMs) {
1156  Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1157  if (LTOInfo && LTOInfo->IsThinLTO)
1158  return &BM;
1159  }
1160  return nullptr;
1161 }
1162 
1163 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1164  const HeaderSearchOptions &HeaderOpts,
1165  const CodeGenOptions &CGOpts,
1166  const clang::TargetOptions &TOpts,
1167  const LangOptions &LOpts,
1168  std::unique_ptr<raw_pwrite_stream> OS,
1169  std::string SampleProfile,
1170  std::string ProfileRemapping,
1171  BackendAction Action) {
1172  StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1173  ModuleToDefinedGVSummaries;
1174  CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1175 
1176  setCommandLineOpts(CGOpts);
1177 
1178  // We can simply import the values mentioned in the combined index, since
1179  // we should only invoke this using the individual indexes written out
1180  // via a WriteIndexesThinBackend.
1181  FunctionImporter::ImportMapTy ImportList;
1182  for (auto &GlobalList : *CombinedIndex) {
1183  // Ignore entries for undefined references.
1184  if (GlobalList.second.SummaryList.empty())
1185  continue;
1186 
1187  auto GUID = GlobalList.first;
1188  for (auto &Summary : GlobalList.second.SummaryList) {
1189  // Skip the summaries for the importing module. These are included to
1190  // e.g. record required linkage changes.
1191  if (Summary->modulePath() == M->getModuleIdentifier())
1192  continue;
1193  // Add an entry to provoke importing by thinBackend.
1194  ImportList[Summary->modulePath()].insert(GUID);
1195  }
1196  }
1197 
1198  std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1199  MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1200 
1201  for (auto &I : ImportList) {
1202  ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1203  llvm::MemoryBuffer::getFile(I.first());
1204  if (!MBOrErr) {
1205  errs() << "Error loading imported file '" << I.first()
1206  << "': " << MBOrErr.getError().message() << "\n";
1207  return;
1208  }
1209 
1210  Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1211  if (!BMOrErr) {
1212  handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1213  errs() << "Error loading imported file '" << I.first()
1214  << "': " << EIB.message() << '\n';
1215  });
1216  return;
1217  }
1218  ModuleMap.insert({I.first(), *BMOrErr});
1219 
1220  OwnedImports.push_back(std::move(*MBOrErr));
1221  }
1222  auto AddStream = [&](size_t Task) {
1223  return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1224  };
1225  lto::Config Conf;
1226  if (CGOpts.SaveTempsFilePrefix != "") {
1227  if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1228  /* UseInputModulePath */ false)) {
1229  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1230  errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1231  << '\n';
1232  });
1233  }
1234  }
1235  Conf.CPU = TOpts.CPU;
1236  Conf.CodeModel = getCodeModel(CGOpts);
1237  Conf.MAttrs = TOpts.Features;
1238  Conf.RelocModel = CGOpts.RelocationModel;
1239  Conf.CGOptLevel = getCGOptLevel(CGOpts);
1240  initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1241  Conf.SampleProfile = std::move(SampleProfile);
1242  Conf.ProfileRemapping = std::move(ProfileRemapping);
1243  Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1244  Conf.DebugPassManager = CGOpts.DebugPassManager;
1245  Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1246  Conf.RemarksFilename = CGOpts.OptRecordFile;
1247  Conf.DwoPath = CGOpts.SplitDwarfFile;
1248  switch (Action) {
1249  case Backend_EmitNothing:
1250  Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1251  return false;
1252  };
1253  break;
1254  case Backend_EmitLL:
1255  Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1256  M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1257  return false;
1258  };
1259  break;
1260  case Backend_EmitBC:
1261  Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1262  WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1263  return false;
1264  };
1265  break;
1266  default:
1267  Conf.CGFileType = getCodeGenFileType(Action);
1268  break;
1269  }
1270  if (Error E = thinBackend(
1271  Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1272  ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1273  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1274  errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1275  });
1276  }
1277 }
1278 
1280  const HeaderSearchOptions &HeaderOpts,
1281  const CodeGenOptions &CGOpts,
1282  const clang::TargetOptions &TOpts,
1283  const LangOptions &LOpts,
1284  const llvm::DataLayout &TDesc, Module *M,
1285  BackendAction Action,
1286  std::unique_ptr<raw_pwrite_stream> OS) {
1287  std::unique_ptr<llvm::Module> EmptyModule;
1288  if (!CGOpts.ThinLTOIndexFile.empty()) {
1289  // If we are performing a ThinLTO importing compile, load the function index
1290  // into memory and pass it into runThinLTOBackend, which will run the
1291  // function importer and invoke LTO passes.
1293  llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1294  /*IgnoreEmptyThinLTOIndexFile*/true);
1295  if (!IndexOrErr) {
1296  logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1297  "Error loading index file '" +
1298  CGOpts.ThinLTOIndexFile + "': ");
1299  return;
1300  }
1301  std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1302  // A null CombinedIndex means we should skip ThinLTO compilation
1303  // (LLVM will optionally ignore empty index files, returning null instead
1304  // of an error).
1305  if (CombinedIndex) {
1306  if (!CombinedIndex->skipModuleByDistributedBackend()) {
1307  runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1308  LOpts, std::move(OS), CGOpts.SampleProfileFile,
1309  CGOpts.ProfileRemappingFile, Action);
1310  return;
1311  }
1312  // Distributed indexing detected that nothing from the module is needed
1313  // for the final linking. So we can skip the compilation. We sill need to
1314  // output an empty object file to make sure that a linker does not fail
1315  // trying to read it. Also for some features, like CFI, we must skip
1316  // the compilation as CombinedIndex does not contain all required
1317  // information.
1318  EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1319  EmptyModule->setTargetTriple(M->getTargetTriple());
1320  M = EmptyModule.get();
1321  }
1322  }
1323 
1324  EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1325 
1326  if (CGOpts.ExperimentalNewPassManager)
1327  AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1328  else
1329  AsmHelper.EmitAssembly(Action, std::move(OS));
1330 
1331  // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1332  // DataLayout.
1333  if (AsmHelper.TM) {
1334  std::string DLDesc = M->getDataLayout().getStringRepresentation();
1335  if (DLDesc != TDesc.getStringRepresentation()) {
1336  unsigned DiagID = Diags.getCustomDiagID(
1337  DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1338  "expected target description '%1'");
1339  Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1340  }
1341  }
1342 }
1343 
1344 static const char* getSectionNameForBitcode(const Triple &T) {
1345  switch (T.getObjectFormat()) {
1346  case Triple::MachO:
1347  return "__LLVM,__bitcode";
1348  case Triple::COFF:
1349  case Triple::ELF:
1350  case Triple::Wasm:
1351  case Triple::UnknownObjectFormat:
1352  return ".llvmbc";
1353  }
1354  llvm_unreachable("Unimplemented ObjectFormatType");
1355 }
1356 
1357 static const char* getSectionNameForCommandline(const Triple &T) {
1358  switch (T.getObjectFormat()) {
1359  case Triple::MachO:
1360  return "__LLVM,__cmdline";
1361  case Triple::COFF:
1362  case Triple::ELF:
1363  case Triple::Wasm:
1364  case Triple::UnknownObjectFormat:
1365  return ".llvmcmd";
1366  }
1367  llvm_unreachable("Unimplemented ObjectFormatType");
1368 }
1369 
1370 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1371 // __LLVM,__bitcode section.
1372 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1373  llvm::MemoryBufferRef Buf) {
1374  if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1375  return;
1376 
1377  // Save llvm.compiler.used and remote it.
1378  SmallVector<Constant*, 2> UsedArray;
1379  SmallPtrSet<GlobalValue*, 4> UsedGlobals;
1380  Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1381  GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1382  for (auto *GV : UsedGlobals) {
1383  if (GV->getName() != "llvm.embedded.module" &&
1384  GV->getName() != "llvm.cmdline")
1385  UsedArray.push_back(
1386  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1387  }
1388  if (Used)
1389  Used->eraseFromParent();
1390 
1391  // Embed the bitcode for the llvm module.
1392  std::string Data;
1393  ArrayRef<uint8_t> ModuleData;
1394  Triple T(M->getTargetTriple());
1395  // Create a constant that contains the bitcode.
1396  // In case of embedding a marker, ignore the input Buf and use the empty
1397  // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1398  if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1399  if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1400  (const unsigned char *)Buf.getBufferEnd())) {
1401  // If the input is LLVM Assembly, bitcode is produced by serializing
1402  // the module. Use-lists order need to be perserved in this case.
1403  llvm::raw_string_ostream OS(Data);
1404  llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1405  ModuleData =
1406  ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1407  } else
1408  // If the input is LLVM bitcode, write the input byte stream directly.
1409  ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1410  Buf.getBufferSize());
1411  }
1412  llvm::Constant *ModuleConstant =
1413  llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1414  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1415  *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1416  ModuleConstant);
1417  GV->setSection(getSectionNameForBitcode(T));
1418  UsedArray.push_back(
1419  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1420  if (llvm::GlobalVariable *Old =
1421  M->getGlobalVariable("llvm.embedded.module", true)) {
1422  assert(Old->hasOneUse() &&
1423  "llvm.embedded.module can only be used once in llvm.compiler.used");
1424  GV->takeName(Old);
1425  Old->eraseFromParent();
1426  } else {
1427  GV->setName("llvm.embedded.module");
1428  }
1429 
1430  // Skip if only bitcode needs to be embedded.
1431  if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1432  // Embed command-line options.
1433  ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1434  CGOpts.CmdArgs.size());
1435  llvm::Constant *CmdConstant =
1436  llvm::ConstantDataArray::get(M->getContext(), CmdData);
1437  GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1438  llvm::GlobalValue::PrivateLinkage,
1439  CmdConstant);
1440  GV->setSection(getSectionNameForCommandline(T));
1441  UsedArray.push_back(
1442  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1443  if (llvm::GlobalVariable *Old =
1444  M->getGlobalVariable("llvm.cmdline", true)) {
1445  assert(Old->hasOneUse() &&
1446  "llvm.cmdline can only be used once in llvm.compiler.used");
1447  GV->takeName(Old);
1448  Old->eraseFromParent();
1449  } else {
1450  GV->setName("llvm.cmdline");
1451  }
1452  }
1453 
1454  if (UsedArray.empty())
1455  return;
1456 
1457  // Recreate llvm.compiler.used.
1458  ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1459  auto *NewUsed = new GlobalVariable(
1460  *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1461  llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1462  NewUsed->setSection("llvm.metadata");
1463 }
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
Paths for &#39;#include <>&#39; added by &#39;-I&#39;.
static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:34
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:30
Run CodeGen, but don&#39;t emit anything.
Definition: BackendUtil.h:36
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:184
The base class of the type hierarchy.
Definition: Type.h:1407
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1295
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2815
static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
static Optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts)
std::vector< std::string > RewriteMapFiles
Set of files defining the rules for the symbol rewriting.
Don&#39;t emit anything (benchmarking mode)
Definition: BackendUtil.h:35
Options for controlling the target.
Definition: TargetOptions.h:27
std::string SplitDwarfFile
The name for the split debug info file that we&#39;ll break out.
static void runThinLTOBackend(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)
std::string DebugPass
Enable additional debugging information.
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
Definition: Sanitizers.h:58
Emit LLVM bitcode files.
Definition: BackendUtil.h:33
std::vector< Entry > UserEntries
User specified include entries.
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
std::string CodeModel
The code model to use (-mcmodel).
Describes a module or submodule.
Definition: Module.h:65
BackendAction
Definition: BackendUtil.h:31
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
static void addThreadSanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Defines the Diagnostic-related interfaces.
static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts)
static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
std::string FloatABI
The ABI to use for passing floating point arguments.
std::string ThreadModel
The thread model to use.
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
char CoverageVersion[4]
The version string to put into coverage files.
static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
for(unsigned I=0, E=TL.getNumArgs();I !=E;++I)
Defines the clang::LangOptions interface.
static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM)
void print(raw_ostream &OS, unsigned Indent=0) const
Print the module map for this module to the given stream.
Definition: Module.cpp:405
static TargetLibraryInfoImpl * createTLII(llvm::Triple &TargetTriple, const CodeGenOptions &CodeGenOpts)
static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Emit native object files.
Definition: BackendUtil.h:37
Emit native assembly files.
Definition: BackendUtil.h:32
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:37
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:43
static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
static void addSymbolRewriterPass(const CodeGenOptions &Opts, legacy::PassManager *MPM)
static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
Defines the clang::TargetOptions class.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings startin...
Definition: TargetOptions.h:56
static void initTargetOptions(llvm::TargetOptions &Options, const CodeGenOptions &CodeGenOpts, const clang::TargetOptions &TargetOpts, const LangOptions &LangOpts, const HeaderSearchOptions &HSOpts)
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:776
llvm::EABI EABIVersion
The EABI version to use.
Definition: TargetOptions.h:46
&#39;#include ""&#39; paths, added by &#39;gcc -iquote&#39;.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
Like Angled, but marks system directories.
static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
Optional< types::ID > Type
Dataflow Directional Tag Classes.
static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM, bool CompileKernel)
bool FrontendTimesIsEnabled
If the user specifies the -ftime-report argument on an Clang command line then the value of this bool...
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
bool hasProfileIRUse() const
Check if IR level profile use is on.
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, const llvm::DataLayout &TDesc, llvm::Module *M, BackendAction Action, std::unique_ptr< raw_pwrite_stream > OS)
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
llvm::Expected< llvm::BitcodeModule > FindThinLTOModule(llvm::MemoryBufferRef MBRef)
static const char * getSectionNameForBitcode(const Triple &T)
static const char * getSectionNameForCommandline(const Triple &T)
Indicates that the tracking object is a descendant of a referenced-counted OSObject, used in the Darwin kernel.
std::string ProfileExcludeFiles
Regexes separated by a semi-colon to filter the files to not instrument.
static void addBoundsCheckingPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
static Optional< llvm::CodeModel::Model > getCodeModel(const CodeGenOptions &CodeGenOpts)
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM)
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
const std::vector< std::string > & getNoBuiltinFuncs() const
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:52
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1573
static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate and -fprofile-generate.
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
std::vector< std::string > SanitizerBlacklistFiles
Paths to blacklist files specifying which objects (files, functions, variables) should not be instrum...
Definition: LangOptions.h:188
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
static void addMemorySanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM)
static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts)