Coverage Report

Created: 2024-01-17 10:31

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