Coverage Report

Created: 2020-09-22 08:39

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