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