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