clang 19.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/PGOInstrumentation.h"
80#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
81#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
82#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
83#include "llvm/Transforms/ObjCARC.h"
84#include "llvm/Transforms/Scalar/EarlyCSE.h"
85#include "llvm/Transforms/Scalar/GVN.h"
86#include "llvm/Transforms/Scalar/JumpThreading.h"
87#include "llvm/Transforms/Utils/Debugify.h"
88#include "llvm/Transforms/Utils/EntryExitInstrumenter.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.X86RelaxRelocations = CodeGenOpts.RelaxELFRelocations;
474 Options.MCOptions.CompressDebugSections =
475 CodeGenOpts.getCompressDebugSections();
476 Options.MCOptions.ABIName = TargetOpts.ABI;
477 for (const auto &Entry : HSOpts.UserEntries)
478 if (!Entry.IsFramework &&
479 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
480 Entry.Group == frontend::IncludeDirGroup::Angled ||
481 Entry.Group == frontend::IncludeDirGroup::System))
482 Options.MCOptions.IASSearchPaths.push_back(
483 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
484 Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
485 Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
486 Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile;
487 Options.MCOptions.PPCUseFullRegisterNames =
488 CodeGenOpts.PPCUseFullRegisterNames;
489 Options.MisExpect = CodeGenOpts.MisExpect;
490
491 return true;
492}
493
494static std::optional<GCOVOptions>
495getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) {
496 if (CodeGenOpts.CoverageNotesFile.empty() &&
497 CodeGenOpts.CoverageDataFile.empty())
498 return std::nullopt;
499 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
500 // LLVM's -default-gcov-version flag is set to something invalid.
501 GCOVOptions Options;
502 Options.EmitNotes = !CodeGenOpts.CoverageNotesFile.empty();
503 Options.EmitData = !CodeGenOpts.CoverageDataFile.empty();
504 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
505 Options.NoRedZone = CodeGenOpts.DisableRedZone;
506 Options.Filter = CodeGenOpts.ProfileFilterFiles;
507 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
508 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
509 return Options;
510}
511
512static std::optional<InstrProfOptions>
514 const LangOptions &LangOpts) {
515 if (!CodeGenOpts.hasProfileClangInstr())
516 return std::nullopt;
517 InstrProfOptions Options;
518 Options.NoRedZone = CodeGenOpts.DisableRedZone;
519 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
520 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
521 return Options;
522}
523
524static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
526 BackendArgs.push_back("clang"); // Fake program name.
527 if (!CodeGenOpts.DebugPass.empty()) {
528 BackendArgs.push_back("-debug-pass");
529 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
530 }
531 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
532 BackendArgs.push_back("-limit-float-precision");
533 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
534 }
535 // Check for the default "clang" invocation that won't set any cl::opt values.
536 // Skip trying to parse the command line invocation to avoid the issues
537 // described below.
538 if (BackendArgs.size() == 1)
539 return;
540 BackendArgs.push_back(nullptr);
541 // FIXME: The command line parser below is not thread-safe and shares a global
542 // state, so this call might crash or overwrite the options of another Clang
543 // instance in the same process.
544 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
545 BackendArgs.data());
546}
547
548void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
549 // Create the TargetMachine for generating code.
550 std::string Error;
551 std::string Triple = TheModule->getTargetTriple();
552 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
553 if (!TheTarget) {
554 if (MustCreateTM)
555 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
556 return;
557 }
558
559 std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
560 std::string FeaturesStr =
561 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
562 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
563 std::optional<CodeGenOptLevel> OptLevelOrNone =
564 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
565 assert(OptLevelOrNone && "Invalid optimization level!");
566 CodeGenOptLevel OptLevel = *OptLevelOrNone;
567
568 llvm::TargetOptions Options;
569 if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
570 HSOpts))
571 return;
572 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
573 Options, RM, CM, OptLevel));
574 TM->setLargeDataThreshold(CodeGenOpts.LargeDataThreshold);
575}
576
577bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
578 BackendAction Action,
579 raw_pwrite_stream &OS,
580 raw_pwrite_stream *DwoOS) {
581 // Add LibraryInfo.
582 std::unique_ptr<TargetLibraryInfoImpl> TLII(
583 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
584 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
585
586 // Normal mode, emit a .s or .o file by running the code generator. Note,
587 // this also adds codegenerator level optimization passes.
588 CodeGenFileType CGFT = getCodeGenFileType(Action);
589
590 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
591 // "codegen" passes so that it isn't run multiple times when there is
592 // inlining happening.
593 if (CodeGenOpts.OptimizationLevel > 0)
594 CodeGenPasses.add(createObjCARCContractPass());
595
596 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
597 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
598 Diags.Report(diag::err_fe_unable_to_interface_with_target);
599 return false;
600 }
601
602 return true;
603}
604
605static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
606 switch (Opts.OptimizationLevel) {
607 default:
608 llvm_unreachable("Invalid optimization level!");
609
610 case 0:
611 return OptimizationLevel::O0;
612
613 case 1:
614 return OptimizationLevel::O1;
615
616 case 2:
617 switch (Opts.OptimizeSize) {
618 default:
619 llvm_unreachable("Invalid optimization level for size!");
620
621 case 0:
622 return OptimizationLevel::O2;
623
624 case 1:
625 return OptimizationLevel::Os;
626
627 case 2:
628 return OptimizationLevel::Oz;
629 }
630
631 case 3:
632 return OptimizationLevel::O3;
633 }
634}
635
636static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts,
637 PassBuilder &PB) {
638 // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
639 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
640 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
641 return;
642
643 // Ensure we lower KCFI operand bundles with -O0.
644 PB.registerOptimizerLastEPCallback(
645 [&](ModulePassManager &MPM, OptimizationLevel Level) {
646 if (Level == OptimizationLevel::O0 &&
647 LangOpts.Sanitize.has(SanitizerKind::KCFI))
648 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
649 });
650
651 // When optimizations are requested, run KCIFPass after InstCombine to
652 // avoid unnecessary checks.
653 PB.registerPeepholeEPCallback(
654 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
655 if (Level != OptimizationLevel::O0 &&
656 LangOpts.Sanitize.has(SanitizerKind::KCFI))
657 FPM.addPass(KCFIPass());
658 });
659}
660
661static void addSanitizers(const Triple &TargetTriple,
662 const CodeGenOptions &CodeGenOpts,
663 const LangOptions &LangOpts, PassBuilder &PB) {
664 auto SanitizersCallback = [&](ModulePassManager &MPM,
665 OptimizationLevel Level) {
666 if (CodeGenOpts.hasSanitizeCoverage()) {
667 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
668 MPM.addPass(SanitizerCoveragePass(
669 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
671 }
672
673 if (CodeGenOpts.hasSanitizeBinaryMetadata()) {
674 MPM.addPass(SanitizerBinaryMetadataPass(
677 }
678
679 auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
680 if (LangOpts.Sanitize.has(Mask)) {
681 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
682 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
683
684 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
685 CodeGenOpts.SanitizeMemoryParamRetval);
686 MPM.addPass(MemorySanitizerPass(options));
687 if (Level != OptimizationLevel::O0) {
688 // MemorySanitizer inserts complex instrumentation that mostly follows
689 // the logic of the original code, but operates on "shadow" values. It
690 // can benefit from re-running some general purpose optimization
691 // passes.
692 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
693 FunctionPassManager FPM;
694 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
695 FPM.addPass(InstCombinePass());
696 FPM.addPass(JumpThreadingPass());
697 FPM.addPass(GVNPass());
698 FPM.addPass(InstCombinePass());
699 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
700 }
701 }
702 };
703 MSanPass(SanitizerKind::Memory, false);
704 MSanPass(SanitizerKind::KernelMemory, true);
705
706 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
707 MPM.addPass(ModuleThreadSanitizerPass());
708 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
709 }
710
711 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
712 if (LangOpts.Sanitize.has(Mask)) {
713 bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
714 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
715 llvm::AsanDtorKind DestructorKind =
716 CodeGenOpts.getSanitizeAddressDtor();
717 AddressSanitizerOptions Opts;
718 Opts.CompileKernel = CompileKernel;
719 Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
720 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
721 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
722 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
723 DestructorKind));
724 }
725 };
726 ASanPass(SanitizerKind::Address, false);
727 ASanPass(SanitizerKind::KernelAddress, true);
728
729 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
730 if (LangOpts.Sanitize.has(Mask)) {
731 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
732 MPM.addPass(HWAddressSanitizerPass(
733 {CompileKernel, Recover,
734 /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
735 }
736 };
737 HWASanPass(SanitizerKind::HWAddress, false);
738 HWASanPass(SanitizerKind::KernelHWAddress, true);
739
740 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
741 MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
742 }
743 };
745 PB.registerOptimizerEarlyEPCallback(
746 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level) {
747 ModulePassManager NewMPM;
748 SanitizersCallback(NewMPM, Level);
749 if (!NewMPM.isEmpty()) {
750 // Sanitizers can abandon<GlobalsAA>.
751 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
752 MPM.addPass(std::move(NewMPM));
753 }
754 });
755 } else {
756 // LastEP does not need GlobalsAA.
757 PB.registerOptimizerLastEPCallback(SanitizersCallback);
758 }
759
760 if (LowerAllowCheckPass::IsRequested()) {
761 // We can optimize after inliner, and PGO profile matching. The hook below
762 // is called at the end `buildFunctionSimplificationPipeline`, which called
763 // from `buildInlinerPipeline`, which called after profile matching.
764 PB.registerScalarOptimizerLateEPCallback(
765 [](FunctionPassManager &FPM, OptimizationLevel Level) {
766 FPM.addPass(LowerAllowCheckPass());
767 });
768 }
769}
770
771void EmitAssemblyHelper::RunOptimizationPipeline(
772 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
773 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
774 std::optional<PGOOptions> PGOOpt;
775
776 if (CodeGenOpts.hasProfileIRInstr())
777 // -fprofile-generate.
778 PGOOpt = PGOOptions(
779 CodeGenOpts.InstrProfileOutput.empty() ? getDefaultProfileGenName()
780 : CodeGenOpts.InstrProfileOutput,
781 "", "", CodeGenOpts.MemoryProfileUsePath, nullptr, PGOOptions::IRInstr,
782 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
783 CodeGenOpts.DebugInfoForProfiling,
784 /*PseudoProbeForProfiling=*/false, CodeGenOpts.AtomicProfileUpdate);
785 else if (CodeGenOpts.hasProfileIRUse()) {
786 // -fprofile-use.
787 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
788 : PGOOptions::NoCSAction;
789 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
790 CodeGenOpts.ProfileRemappingFile,
791 CodeGenOpts.MemoryProfileUsePath, VFS,
792 PGOOptions::IRUse, CSAction, ClPGOColdFuncAttr,
793 CodeGenOpts.DebugInfoForProfiling);
794 } else if (!CodeGenOpts.SampleProfileFile.empty())
795 // -fprofile-sample-use
796 PGOOpt = PGOOptions(
797 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
798 CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse,
799 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
800 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
801 else if (!CodeGenOpts.MemoryProfileUsePath.empty())
802 // -fmemory-profile-use (without any of the above options)
803 PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, VFS,
804 PGOOptions::NoAction, PGOOptions::NoCSAction,
805 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
806 else if (CodeGenOpts.PseudoProbeForProfiling)
807 // -fpseudo-probe-for-profiling
808 PGOOpt =
809 PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
810 PGOOptions::NoAction, PGOOptions::NoCSAction,
811 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling, true);
812 else if (CodeGenOpts.DebugInfoForProfiling)
813 // -fdebug-info-for-profiling
814 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
815 PGOOptions::NoAction, PGOOptions::NoCSAction,
816 ClPGOColdFuncAttr, true);
817
818 // Check to see if we want to generate a CS profile.
819 if (CodeGenOpts.hasProfileCSIRInstr()) {
820 assert(!CodeGenOpts.hasProfileCSIRUse() &&
821 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
822 "the same time");
823 if (PGOOpt) {
824 assert(PGOOpt->Action != PGOOptions::IRInstr &&
825 PGOOpt->Action != PGOOptions::SampleUse &&
826 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
827 " pass");
828 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
829 ? getDefaultProfileGenName()
830 : CodeGenOpts.InstrProfileOutput;
831 PGOOpt->CSAction = PGOOptions::CSIRInstr;
832 } else
833 PGOOpt = PGOOptions("",
834 CodeGenOpts.InstrProfileOutput.empty()
835 ? getDefaultProfileGenName()
836 : CodeGenOpts.InstrProfileOutput,
837 "", /*MemoryProfile=*/"", nullptr,
838 PGOOptions::NoAction, PGOOptions::CSIRInstr,
839 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
840 }
841 if (TM)
842 TM->setPGOOption(PGOOpt);
843
844 PipelineTuningOptions PTO;
845 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
846 // For historical reasons, loop interleaving is set to mirror setting for loop
847 // unrolling.
848 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
849 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
850 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
851 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
852 // Only enable CGProfilePass when using integrated assembler, since
853 // non-integrated assemblers don't recognize .cgprofile section.
854 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
855 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
856
857 LoopAnalysisManager LAM;
858 FunctionAnalysisManager FAM;
859 CGSCCAnalysisManager CGAM;
860 ModuleAnalysisManager MAM;
861
862 bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
863 PassInstrumentationCallbacks PIC;
864 PrintPassOptions PrintPassOpts;
865 PrintPassOpts.Indent = DebugPassStructure;
866 PrintPassOpts.SkipAnalyses = DebugPassStructure;
867 StandardInstrumentations SI(
868 TheModule->getContext(),
869 (CodeGenOpts.DebugPassManager || DebugPassStructure),
870 CodeGenOpts.VerifyEach, PrintPassOpts);
871 SI.registerCallbacks(PIC, &MAM);
872 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
873
874 // Handle the assignment tracking feature options.
875 switch (CodeGenOpts.getAssignmentTrackingMode()) {
876 case CodeGenOptions::AssignmentTrackingOpts::Forced:
877 PB.registerPipelineStartEPCallback(
878 [&](ModulePassManager &MPM, OptimizationLevel Level) {
879 MPM.addPass(AssignmentTrackingPass());
880 });
881 break;
882 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
883 // Disable assignment tracking in LTO builds for now as the performance
884 // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
885 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
886 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
887 PB.registerPipelineStartEPCallback(
888 [&](ModulePassManager &MPM, OptimizationLevel Level) {
889 // Only use assignment tracking if optimisations are enabled.
890 if (Level != OptimizationLevel::O0)
891 MPM.addPass(AssignmentTrackingPass());
892 });
893 }
894 break;
895 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
896 break;
897 }
898
899 // Enable verify-debuginfo-preserve-each for new PM.
900 DebugifyEachInstrumentation Debugify;
901 DebugInfoPerPass DebugInfoBeforePass;
902 if (CodeGenOpts.EnableDIPreservationVerify) {
903 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
904 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
905
906 if (!CodeGenOpts.DIBugsReportFilePath.empty())
907 Debugify.setOrigDIVerifyBugsReportFilePath(
908 CodeGenOpts.DIBugsReportFilePath);
909 Debugify.registerCallbacks(PIC, MAM);
910 }
911 // Attempt to load pass plugins and register their callbacks with PB.
912 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
913 auto PassPlugin = PassPlugin::Load(PluginFN);
914 if (PassPlugin) {
915 PassPlugin->registerPassBuilderCallbacks(PB);
916 } else {
917 Diags.Report(diag::err_fe_unable_to_load_plugin)
918 << PluginFN << toString(PassPlugin.takeError());
919 }
920 }
921 for (const auto &PassCallback : CodeGenOpts.PassBuilderCallbacks)
922 PassCallback(PB);
923#define HANDLE_EXTENSION(Ext) \
924 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
925#include "llvm/Support/Extension.def"
926
927 // Register the target library analysis directly and give it a customized
928 // preset TLI.
929 std::unique_ptr<TargetLibraryInfoImpl> TLII(
930 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
931 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
932
933 // Register all the basic analyses with the managers.
934 PB.registerModuleAnalyses(MAM);
935 PB.registerCGSCCAnalyses(CGAM);
936 PB.registerFunctionAnalyses(FAM);
937 PB.registerLoopAnalyses(LAM);
938 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
939
940 ModulePassManager MPM;
941 // Add a verifier pass, before any other passes, to catch CodeGen issues.
942 if (CodeGenOpts.VerifyModule)
943 MPM.addPass(VerifierPass());
944
945 if (!CodeGenOpts.DisableLLVMPasses) {
946 // Map our optimization levels into one of the distinct levels used to
947 // configure the pipeline.
948 OptimizationLevel Level = mapToLevel(CodeGenOpts);
949
950 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
951 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
952
953 if (LangOpts.ObjCAutoRefCount) {
954 PB.registerPipelineStartEPCallback(
955 [](ModulePassManager &MPM, OptimizationLevel Level) {
956 if (Level != OptimizationLevel::O0)
957 MPM.addPass(
958 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
959 });
960 PB.registerPipelineEarlySimplificationEPCallback(
961 [](ModulePassManager &MPM, OptimizationLevel Level) {
962 if (Level != OptimizationLevel::O0)
963 MPM.addPass(ObjCARCAPElimPass());
964 });
965 PB.registerScalarOptimizerLateEPCallback(
966 [](FunctionPassManager &FPM, OptimizationLevel Level) {
967 if (Level != OptimizationLevel::O0)
968 FPM.addPass(ObjCARCOptPass());
969 });
970 }
971
972 // If we reached here with a non-empty index file name, then the index
973 // file was empty and we are not performing ThinLTO backend compilation
974 // (used in testing in a distributed build environment).
975 bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
976 // If so drop any the type test assume sequences inserted for whole program
977 // vtables so that codegen doesn't complain.
978 if (IsThinLTOPostLink)
979 PB.registerPipelineStartEPCallback(
980 [](ModulePassManager &MPM, OptimizationLevel Level) {
981 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
982 /*ImportSummary=*/nullptr,
983 /*DropTypeTests=*/true));
984 });
985
986 if (CodeGenOpts.InstrumentFunctions ||
987 CodeGenOpts.InstrumentFunctionEntryBare ||
988 CodeGenOpts.InstrumentFunctionsAfterInlining ||
989 CodeGenOpts.InstrumentForProfiling) {
990 PB.registerPipelineStartEPCallback(
991 [](ModulePassManager &MPM, OptimizationLevel Level) {
992 MPM.addPass(createModuleToFunctionPassAdaptor(
993 EntryExitInstrumenterPass(/*PostInlining=*/false)));
994 });
995 PB.registerOptimizerLastEPCallback(
996 [](ModulePassManager &MPM, OptimizationLevel Level) {
997 MPM.addPass(createModuleToFunctionPassAdaptor(
998 EntryExitInstrumenterPass(/*PostInlining=*/true)));
999 });
1000 }
1001
1002 // Register callbacks to schedule sanitizer passes at the appropriate part
1003 // of the pipeline.
1004 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1005 PB.registerScalarOptimizerLateEPCallback(
1006 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1007 FPM.addPass(BoundsCheckingPass());
1008 });
1009
1010 // Don't add sanitizers if we are here from ThinLTO PostLink. That already
1011 // done on PreLink stage.
1012 if (!IsThinLTOPostLink) {
1013 addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1014 addKCFIPass(TargetTriple, LangOpts, PB);
1015 }
1016
1017 if (std::optional<GCOVOptions> Options =
1018 getGCOVOptions(CodeGenOpts, LangOpts))
1019 PB.registerPipelineStartEPCallback(
1020 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1021 MPM.addPass(GCOVProfilerPass(*Options));
1022 });
1023 if (std::optional<InstrProfOptions> Options =
1024 getInstrProfOptions(CodeGenOpts, LangOpts))
1025 PB.registerPipelineStartEPCallback(
1026 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1027 MPM.addPass(InstrProfilingLoweringPass(*Options, false));
1028 });
1029
1030 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
1031 // the PGOOptions, and set this up there.
1032 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1033 PB.registerOptimizerLastEPCallback(
1034 [](ModulePassManager &MPM, OptimizationLevel Level) {
1035 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1036 MPM.addPass(ModuleMemProfilerPass());
1037 });
1038 }
1039
1040 if (CodeGenOpts.FatLTO) {
1041 MPM.addPass(PB.buildFatLTODefaultPipeline(
1042 Level, PrepareForThinLTO,
1043 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1044 } else if (PrepareForThinLTO) {
1045 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1046 } else if (PrepareForLTO) {
1047 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1048 } else {
1049 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1050 }
1051 }
1052
1053 // Link against bitcodes supplied via the -mlink-builtin-bitcode option
1054 if (CodeGenOpts.LinkBitcodePostopt)
1055 MPM.addPass(LinkInModulesPass(BC, false));
1056
1057 // Add a verifier pass if requested. We don't have to do this if the action
1058 // requires code generation because there will already be a verifier pass in
1059 // the code-generation pipeline.
1060 // Since we already added a verifier pass above, this
1061 // might even not run the analysis, if previous passes caused no changes.
1062 if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
1063 MPM.addPass(VerifierPass());
1064
1065 if (Action == Backend_EmitBC || Action == Backend_EmitLL ||
1066 CodeGenOpts.FatLTO) {
1067 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1068 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1069 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1070 CodeGenOpts.EnableSplitLTOUnit);
1071 if (Action == Backend_EmitBC) {
1072 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1073 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1074 if (!ThinLinkOS)
1075 return;
1076 }
1077 MPM.addPass(ThinLTOBitcodeWriterPass(
1078 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1079 } else if (Action == Backend_EmitLL) {
1080 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1081 /*EmitLTOSummary=*/true));
1082 }
1083 } else {
1084 // Emit a module summary by default for Regular LTO except for ld64
1085 // targets
1086 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1087 if (EmitLTOSummary) {
1088 if (!TheModule->getModuleFlag("ThinLTO") && !CodeGenOpts.UnifiedLTO)
1089 TheModule->addModuleFlag(llvm::Module::Error, "ThinLTO", uint32_t(0));
1090 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1091 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1092 uint32_t(1));
1093 }
1094 if (Action == Backend_EmitBC) {
1095 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1096 EmitLTOSummary));
1097 } else if (Action == Backend_EmitLL) {
1098 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1099 EmitLTOSummary));
1100 }
1101 }
1102
1103 if (shouldEmitUnifiedLTOModueFlag())
1104 TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
1105 }
1106
1107 // Print a textual, '-passes=' compatible, representation of pipeline if
1108 // requested.
1109 if (PrintPipelinePasses) {
1110 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1111 auto PassName = PIC.getPassNameForClassName(ClassName);
1112 return PassName.empty() ? ClassName : PassName;
1113 });
1114 outs() << "\n";
1115 return;
1116 }
1117
1118 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1119 LangOpts.HIPStdParInterposeAlloc)
1120 MPM.addPass(HipStdParAllocationInterpositionPass());
1121
1122 // Now that we have all of the passes ready, run them.
1123 {
1124 PrettyStackTraceString CrashInfo("Optimizer");
1125 llvm::TimeTraceScope TimeScope("Optimizer");
1126 MPM.run(*TheModule, MAM);
1127 }
1128}
1129
1130void EmitAssemblyHelper::RunCodegenPipeline(
1131 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1132 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1133 // We still use the legacy PM to run the codegen pipeline since the new PM
1134 // does not work with the codegen pipeline.
1135 // FIXME: make the new PM work with the codegen pipeline.
1136 legacy::PassManager CodeGenPasses;
1137
1138 // Append any output we need to the pass manager.
1139 switch (Action) {
1141 case Backend_EmitMCNull:
1142 case Backend_EmitObj:
1143 CodeGenPasses.add(
1144 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1145 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1146 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1147 if (!DwoOS)
1148 return;
1149 }
1150 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1151 DwoOS ? &DwoOS->os() : nullptr))
1152 // FIXME: Should we handle this error differently?
1153 return;
1154 break;
1155 default:
1156 return;
1157 }
1158
1159 // If -print-pipeline-passes is requested, don't run the legacy pass manager.
1160 // FIXME: when codegen is switched to use the new pass manager, it should also
1161 // emit pass names here.
1162 if (PrintPipelinePasses) {
1163 return;
1164 }
1165
1166 {
1167 PrettyStackTraceString CrashInfo("Code generation");
1168 llvm::TimeTraceScope TimeScope("CodeGenPasses");
1169 CodeGenPasses.run(*TheModule);
1170 }
1171}
1172
1173void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1174 std::unique_ptr<raw_pwrite_stream> OS,
1175 BackendConsumer *BC) {
1176 TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1177 setCommandLineOpts(CodeGenOpts);
1178
1179 bool RequiresCodeGen = actionRequiresCodeGen(Action);
1180 CreateTargetMachine(RequiresCodeGen);
1181
1182 if (RequiresCodeGen && !TM)
1183 return;
1184 if (TM)
1185 TheModule->setDataLayout(TM->createDataLayout());
1186
1187 // Before executing passes, print the final values of the LLVM options.
1188 cl::PrintOptionValues();
1189
1190 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1191 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1192 RunCodegenPipeline(Action, OS, DwoOS);
1193
1194 if (ThinLinkOS)
1195 ThinLinkOS->keep();
1196 if (DwoOS)
1197 DwoOS->keep();
1198}
1199
1201 DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex,
1202 llvm::Module *M, const HeaderSearchOptions &HeaderOpts,
1203 const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
1204 const LangOptions &LOpts, std::unique_ptr<raw_pwrite_stream> OS,
1205 std::string SampleProfile, std::string ProfileRemapping,
1206 BackendAction Action) {
1207 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1208 ModuleToDefinedGVSummaries;
1209 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1210
1211 setCommandLineOpts(CGOpts);
1212
1213 // We can simply import the values mentioned in the combined index, since
1214 // we should only invoke this using the individual indexes written out
1215 // via a WriteIndexesThinBackend.
1216 FunctionImporter::ImportMapTy ImportList;
1217 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1218 return;
1219
1220 auto AddStream = [&](size_t Task, const Twine &ModuleName) {
1221 return std::make_unique<CachedFileStream>(std::move(OS),
1222 CGOpts.ObjectFilenameForDebug);
1223 };
1224 lto::Config Conf;
1225 if (CGOpts.SaveTempsFilePrefix != "") {
1226 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1227 /* UseInputModulePath */ false)) {
1228 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1229 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1230 << '\n';
1231 });
1232 }
1233 }
1234 Conf.CPU = TOpts.CPU;
1235 Conf.CodeModel = getCodeModel(CGOpts);
1236 Conf.MAttrs = TOpts.Features;
1237 Conf.RelocModel = CGOpts.RelocationModel;
1238 std::optional<CodeGenOptLevel> OptLevelOrNone =
1239 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1240 assert(OptLevelOrNone && "Invalid optimization level!");
1241 Conf.CGOptLevel = *OptLevelOrNone;
1242 Conf.OptLevel = CGOpts.OptimizationLevel;
1243 initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1244 Conf.SampleProfile = std::move(SampleProfile);
1245 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1246 // For historical reasons, loop interleaving is set to mirror setting for loop
1247 // unrolling.
1248 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1249 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1250 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1251 // Only enable CGProfilePass when using integrated assembler, since
1252 // non-integrated assemblers don't recognize .cgprofile section.
1253 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1254
1255 // Context sensitive profile.
1256 if (CGOpts.hasProfileCSIRInstr()) {
1257 Conf.RunCSIRInstr = true;
1258 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1259 } else if (CGOpts.hasProfileCSIRUse()) {
1260 Conf.RunCSIRInstr = false;
1261 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1262 }
1263
1264 Conf.ProfileRemapping = std::move(ProfileRemapping);
1265 Conf.DebugPassManager = CGOpts.DebugPassManager;
1266 Conf.VerifyEach = CGOpts.VerifyEach;
1267 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1268 Conf.RemarksFilename = CGOpts.OptRecordFile;
1269 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1270 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1271 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1272 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1273 switch (Action) {
1275 Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) {
1276 return false;
1277 };
1278 break;
1279 case Backend_EmitLL:
1280 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1281 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1282 return false;
1283 };
1284 break;
1285 case Backend_EmitBC:
1286 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1287 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1288 return false;
1289 };
1290 break;
1291 default:
1292 Conf.CGFileType = getCodeGenFileType(Action);
1293 break;
1294 }
1295 if (Error E =
1296 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1297 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1298 /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1299 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1300 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1301 });
1302 }
1303}
1304
1306 DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderOpts,
1307 const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
1308 const LangOptions &LOpts, StringRef TDesc, llvm::Module *M,
1310 std::unique_ptr<raw_pwrite_stream> OS, BackendConsumer *BC) {
1311
1312 llvm::TimeTraceScope TimeScope("Backend");
1313
1314 std::unique_ptr<llvm::Module> EmptyModule;
1315 if (!CGOpts.ThinLTOIndexFile.empty()) {
1316 // If we are performing a ThinLTO importing compile, load the function index
1317 // into memory and pass it into runThinLTOBackend, which will run the
1318 // function importer and invoke LTO passes.
1319 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1320 if (Error E = llvm::getModuleSummaryIndexForFile(
1321 CGOpts.ThinLTOIndexFile,
1322 /*IgnoreEmptyThinLTOIndexFile*/ true)
1323 .moveInto(CombinedIndex)) {
1324 logAllUnhandledErrors(std::move(E), errs(),
1325 "Error loading index file '" +
1326 CGOpts.ThinLTOIndexFile + "': ");
1327 return;
1328 }
1329
1330 // A null CombinedIndex means we should skip ThinLTO compilation
1331 // (LLVM will optionally ignore empty index files, returning null instead
1332 // of an error).
1333 if (CombinedIndex) {
1334 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1335 runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1336 TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1337 CGOpts.ProfileRemappingFile, Action);
1338 return;
1339 }
1340 // Distributed indexing detected that nothing from the module is needed
1341 // for the final linking. So we can skip the compilation. We sill need to
1342 // output an empty object file to make sure that a linker does not fail
1343 // trying to read it. Also for some features, like CFI, we must skip
1344 // the compilation as CombinedIndex does not contain all required
1345 // information.
1346 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1347 EmptyModule->setTargetTriple(M->getTargetTriple());
1348 M = EmptyModule.get();
1349 }
1350 }
1351
1352 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M, VFS);
1353 AsmHelper.EmitAssembly(Action, std::move(OS), BC);
1354
1355 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1356 // DataLayout.
1357 if (AsmHelper.TM) {
1358 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1359 if (DLDesc != TDesc) {
1360 unsigned DiagID = Diags.getCustomDiagID(
1361 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1362 "expected target description '%1'");
1363 Diags.Report(DiagID) << DLDesc << TDesc;
1364 }
1365 }
1366}
1367
1368// With -fembed-bitcode, save a copy of the llvm IR as data in the
1369// __LLVM,__bitcode section.
1370void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1371 llvm::MemoryBufferRef Buf) {
1372 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1373 return;
1374 llvm::embedBitcodeInModule(
1375 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1376 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1377 CGOpts.CmdArgs);
1378}
1379
1380void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1381 DiagnosticsEngine &Diags) {
1382 if (CGOpts.OffloadObjects.empty())
1383 return;
1384
1385 for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1386 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1387 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1388 if (ObjectOrErr.getError()) {
1389 auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1390 "could not open '%0' for embedding");
1391 Diags.Report(DiagID) << OffloadObject;
1392 return;
1393 }
1394
1395 llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1396 Align(object::OffloadBinary::getAlignment()));
1397 }
1398}
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.
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:461
bool hasWasmExceptions() const
Definition: LangOptions.h:704
bool hasSjLjExceptions() const
Definition: LangOptions.h:692
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:467
bool hasDWARFExceptions() const
Definition: LangOptions.h:700
bool hasSEHExceptions() const
Definition: LangOptions.h:696
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
Definition: LangOptions.h:473
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
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."))
Definition: Format.h:5428
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:159