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