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