19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/TargetLibraryInfo.h"
23#include "llvm/Analysis/TargetTransformInfo.h"
24#include "llvm/Bitcode/BitcodeReader.h"
25#include "llvm/Bitcode/BitcodeWriter.h"
26#include "llvm/Bitcode/BitcodeWriterPass.h"
27#include "llvm/CodeGen/TargetSubtargetInfo.h"
28#include "llvm/Config/llvm-config.h"
29#include "llvm/Frontend/Driver/CodeGenOptions.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DebugInfo.h"
32#include "llvm/IR/LLVMRemarkStreamer.h"
33#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/ModuleSummaryIndex.h"
36#include "llvm/IR/PassManager.h"
37#include "llvm/IR/Verifier.h"
38#include "llvm/IRPrinter/IRPrintingPasses.h"
39#include "llvm/LTO/LTOBackend.h"
40#include "llvm/MC/TargetRegistry.h"
41#include "llvm/Object/OffloadBinary.h"
42#include "llvm/Passes/PassBuilder.h"
43#include "llvm/Passes/PassPlugin.h"
44#include "llvm/Passes/StandardInstrumentations.h"
45#include "llvm/ProfileData/InstrProfCorrelator.h"
46#include "llvm/Support/BuryPointer.h"
47#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/PrettyStackTrace.h"
51#include "llvm/Support/Program.h"
52#include "llvm/Support/TimeProfiler.h"
53#include "llvm/Support/Timer.h"
54#include "llvm/Support/ToolOutputFile.h"
55#include "llvm/Support/VirtualFileSystem.h"
56#include "llvm/Support/raw_ostream.h"
57#include "llvm/Target/TargetMachine.h"
58#include "llvm/Target/TargetOptions.h"
59#include "llvm/TargetParser/SubtargetFeature.h"
60#include "llvm/TargetParser/Triple.h"
61#include "llvm/Transforms/HipStdPar/HipStdPar.h"
62#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
63#include "llvm/Transforms/IPO/InferFunctionAttrs.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/AddressSanitizer.h"
68#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
69#include "llvm/Transforms/Instrumentation/AllocToken.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/MemProfInstrumentation.h"
78#include "llvm/Transforms/Instrumentation/MemProfUse.h"
79#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
80#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
81#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
82#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
83#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
84#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
85#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
86#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
87#include "llvm/Transforms/ObjCARC.h"
88#include "llvm/Transforms/Scalar/EarlyCSE.h"
89#include "llvm/Transforms/Scalar/GVN.h"
90#include "llvm/Transforms/Scalar/JumpThreading.h"
91#include "llvm/Transforms/Utils/Debugify.h"
92#include "llvm/Transforms/Utils/ModuleUtils.h"
99#define HANDLE_EXTENSION(Ext) \
100 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
101#include "llvm/Support/Extension.def"
106 "sanitizer-early-opt-ep", cl::Optional,
107 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
112 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
114 "Function attribute to apply to cold functions as determined by PGO"),
115 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
116 "Default (no attribute)"),
117 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
118 "Mark cold functions with optsize."),
119 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
120 "Mark cold functions with minsize."),
121 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
122 "Mark cold functions with optnone.")));
124LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
134 ? llvm::driver::getDefaultProfileGenName()
136 if (CodeGenOpts.ContinuousProfileSync)
143class EmitAssemblyHelper {
144 CompilerInstance &CI;
145 DiagnosticsEngine &Diags;
146 const CodeGenOptions &CodeGenOpts;
147 const clang::TargetOptions &TargetOpts;
148 const LangOptions &LangOpts;
149 llvm::Module *TheModule;
150 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
152 std::unique_ptr<raw_pwrite_stream> OS;
156 TargetIRAnalysis getTargetIRAnalysis()
const {
158 return TM->getTargetIRAnalysis();
160 return TargetIRAnalysis();
171 void CreateTargetMachine(
bool MustCreateTM);
176 bool AddEmitPasses(legacy::PassManager &CodeGenPasses,
BackendAction Action,
177 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
179 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
181 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
182 llvm::sys::fs::OF_None);
184 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
190 void RunOptimizationPipeline(
191 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
192 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
194 std::unique_ptr<raw_pwrite_stream> &OS,
195 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
202 bool shouldEmitRegularLTOSummary()
const {
203 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
204 TargetTriple.getVendor() != llvm::Triple::Apple;
210 bool shouldEmitUnifiedLTOModueFlag()
const {
211 return CodeGenOpts.UnifiedLTO &&
212 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
216 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
218 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
219 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
220 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
221 TheModule(M), VFS(std::move(VFS)),
222 TargetTriple(TheModule->getTargetTriple()) {}
224 ~EmitAssemblyHelper() {
225 if (CodeGenOpts.DisableFree)
226 BuryPointer(std::move(TM));
229 std::unique_ptr<TargetMachine> TM;
232 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
233 BackendConsumer *BC);
239 AllocTokenOptions Opts;
243 Opts.Extended = CGOpts.SanitizeAllocTokenExtended;
244 Opts.FastABI = CGOpts.SanitizeAllocTokenFastABI;
248static SanitizerCoverageOptions
250 SanitizerCoverageOptions Opts;
252 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
253 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
254 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
255 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
256 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
257 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
258 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
259 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
260 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
261 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
262 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
263 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
264 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
265 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
266 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
267 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
268 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
269 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
273static SanitizerBinaryMetadataOptions
275 SanitizerBinaryMetadataOptions Opts;
276 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
277 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
278 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
287 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
289 switch (
T.getObjectFormat()) {
294 return !CGOpts.DisableIntegratedAS;
296 llvm::report_fatal_error(
"ASan not implemented for GOFF");
298 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
300 case Triple::DXContainer:
302 case Triple::UnknownObjectFormat:
308static std::optional<llvm::CodeModel::Model>
310 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
311 .Case(
"tiny", llvm::CodeModel::Tiny)
312 .Case(
"small", llvm::CodeModel::Small)
313 .Case(
"kernel", llvm::CodeModel::Kernel)
314 .Case(
"medium", llvm::CodeModel::Medium)
315 .Case(
"large", llvm::CodeModel::Large)
316 .Cases({
"default",
""}, ~1u)
318 assert(CodeModel != ~0u &&
"invalid code model!");
319 if (CodeModel == ~1u)
321 return static_cast<llvm::CodeModel::Model
>(CodeModel);
326 return CodeGenFileType::ObjectFile;
328 return CodeGenFileType::Null;
331 return CodeGenFileType::AssemblyFile;
341 StringRef MainFilename) {
343 return std::string{};
345 std::string FlatCmdLine;
346 raw_string_ostream OS(FlatCmdLine);
347 bool PrintedOneArg =
false;
348 if (!StringRef(Args[0]).
contains(
"-cc1")) {
349 llvm::sys::printArg(OS,
"-cc1",
true);
350 PrintedOneArg =
true;
352 for (
unsigned i = 0; i < Args.size(); i++) {
353 StringRef Arg = Args[i];
356 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
360 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
363 if (Arg.starts_with(
"-fmessage-length"))
367 llvm::sys::printArg(OS, Arg,
true);
368 PrintedOneArg =
true;
375 llvm::TargetOptions &Options) {
380 switch (LangOpts.getThreadModel()) {
382 Options.ThreadModel = llvm::ThreadModel::POSIX;
385 Options.ThreadModel = llvm::ThreadModel::Single;
390 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
392 "Invalid Floating Point ABI!");
393 Options.FloatABIType =
394 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
395 .Case(
"soft", llvm::FloatABI::Soft)
396 .Case(
"softfp", llvm::FloatABI::Soft)
397 .Case(
"hard", llvm::FloatABI::Hard)
398 .Default(llvm::FloatABI::Default);
401 switch (LangOpts.getDefaultFPContractMode()) {
405 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
409 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
412 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
416 Options.BinutilsVersion =
417 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
418 Options.UseInitArray = CodeGenOpts.UseInitArray;
419 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
425 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
427 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
429 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
431 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
433 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
434 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
435 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
437 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
439 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
440 .Case(
"all", llvm::BasicBlockSection::All)
441 .StartsWith(
"list=", llvm::BasicBlockSection::List)
442 .Case(
"none", llvm::BasicBlockSection::None)
443 .Default(llvm::BasicBlockSection::None);
445 if (Options.BBSections == llvm::BasicBlockSection::List) {
446 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
450 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
451 << MBOrErr.getError().message();
454 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
457 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
458 Options.FunctionSections = CodeGenOpts.FunctionSections;
459 Options.DataSections = CodeGenOpts.DataSections;
460 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
461 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
462 Options.UniqueBasicBlockSectionNames =
463 CodeGenOpts.UniqueBasicBlockSectionNames;
464 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
465 Options.TLSSize = CodeGenOpts.TLSSize;
466 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
467 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
468 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
469 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
471 Options.EmitAddrsig = CodeGenOpts.Addrsig;
472 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
473 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
474 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
475 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
476 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
477 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
478 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
480 Options.Hotpatch = CodeGenOpts.HotPatch;
481 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
482 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
484 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
486 Options.SwiftAsyncFramePointer =
487 SwiftAsyncFramePointerMode::DeploymentBased;
491 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
495 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
500 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
501 Options.MCOptions.EmitCompactUnwindNonCanonical =
502 CodeGenOpts.EmitCompactUnwindNonCanonical;
503 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
504 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
505 Options.MCOptions.MCUseDwarfDirectory =
506 CodeGenOpts.NoDwarfDirectoryAsm
507 ? llvm::MCTargetOptions::DisableDwarfDirectory
508 : llvm::MCTargetOptions::EnableDwarfDirectory;
509 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
510 Options.MCOptions.MCIncrementalLinkerCompatible =
511 CodeGenOpts.IncrementalLinkerCompatible;
512 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
513 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
514 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
515 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
516 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
517 Options.MCOptions.Crel = CodeGenOpts.Crel;
518 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
519 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
520 Options.MCOptions.CompressDebugSections =
521 CodeGenOpts.getCompressDebugSections();
522 if (CodeGenOpts.OutputAsmVariant != 3)
523 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
524 Options.MCOptions.ABIName = TargetOpts.
ABI;
525 for (
const auto &Entry : HSOpts.UserEntries)
526 if (!Entry.IsFramework &&
530 Options.MCOptions.IASSearchPaths.push_back(
531 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
532 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
536 Options.MCOptions.PPCUseFullRegisterNames =
537 CodeGenOpts.PPCUseFullRegisterNames;
538 Options.MisExpect = CodeGenOpts.MisExpect;
543static std::optional<GCOVOptions>
554 Options.NoRedZone = CodeGenOpts.DisableRedZone;
557 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
561static std::optional<InstrProfOptions>
566 InstrProfOptions Options;
567 Options.NoRedZone = CodeGenOpts.DisableRedZone;
571 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
576 vfs::FileSystem &VFS) {
578 BackendArgs.push_back(
"clang");
580 BackendArgs.push_back(
"-debug-pass");
581 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
584 BackendArgs.push_back(
"-limit-float-precision");
590 if (BackendArgs.size() == 1)
592 BackendArgs.push_back(
nullptr);
596 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
601void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
604 const llvm::Triple &Triple = TheModule->getTargetTriple();
605 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
608 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
612 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
613 std::string FeaturesStr =
616 std::optional<CodeGenOptLevel> OptLevelOrNone =
617 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
618 assert(OptLevelOrNone &&
"Invalid optimization level!");
619 CodeGenOptLevel OptLevel = *OptLevelOrNone;
621 llvm::TargetOptions Options;
624 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
625 Options, RM, CM, OptLevel));
630bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
632 raw_pwrite_stream &OS,
633 raw_pwrite_stream *DwoOS) {
635 std::unique_ptr<TargetLibraryInfoImpl> TLII(
636 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
637 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
643 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
644 !CodeGenOpts.VerifyModule)) {
645 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
653 switch (Opts.OptimizationLevel) {
655 llvm_unreachable(
"Invalid optimization level!");
658 return OptimizationLevel::O0;
661 return OptimizationLevel::O1;
664 switch (Opts.OptimizeSize) {
666 llvm_unreachable(
"Invalid optimization level for size!");
669 return OptimizationLevel::O2;
672 return OptimizationLevel::Os;
675 return OptimizationLevel::Oz;
679 return OptimizationLevel::O3;
686 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
687 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
688 TargetTriple.isARM() || TargetTriple.isThumb())
692 PB.registerOptimizerLastEPCallback(
693 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
694 if (Level == OptimizationLevel::O0 &&
696 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
701 PB.registerPeepholeEPCallback(
702 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
703 if (Level != OptimizationLevel::O0 &&
705 FPM.addPass(KCFIPass());
712 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
713 ThinOrFullLTOPhase) {
717 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
723 MPM.addPass(SanitizerBinaryMetadataPass(
725 PB.getVirtualFileSystemPtr(),
729 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
731 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
734 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
735 CodeGenOpts.SanitizeMemoryParamRetval);
736 MPM.addPass(MemorySanitizerPass(
options));
737 if (Level != OptimizationLevel::O0) {
742 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
743 FunctionPassManager FPM;
744 FPM.addPass(EarlyCSEPass(
true ));
745 FPM.addPass(InstCombinePass());
746 FPM.addPass(JumpThreadingPass());
747 FPM.addPass(GVNPass());
748 FPM.addPass(InstCombinePass());
749 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
753 MSanPass(SanitizerKind::Memory,
false);
754 MSanPass(SanitizerKind::KernelMemory,
true);
756 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
757 MPM.addPass(ModuleThreadSanitizerPass());
758 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
762 MPM.addPass(TypeSanitizerPass());
764 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
765 MPM.addPass(NumericalStabilitySanitizerPass());
767 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
768 MPM.addPass(RealtimeSanitizerPass());
770 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
773 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
774 llvm::AsanDtorKind DestructorKind =
775 CodeGenOpts.getSanitizeAddressDtor();
776 AddressSanitizerOptions Opts;
777 Opts.CompileKernel = CompileKernel;
779 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
780 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
781 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
785 ASanPass(SanitizerKind::Address,
false);
786 ASanPass(SanitizerKind::KernelAddress,
true);
788 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
791 MPM.addPass(HWAddressSanitizerPass(
792 {CompileKernel, Recover,
793 CodeGenOpts.OptimizationLevel == 0}));
796 HWASanPass(SanitizerKind::HWAddress,
false);
797 HWASanPass(SanitizerKind::KernelHWAddress,
true);
799 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
801 PB.getVirtualFileSystemPtr()));
805 PB.registerOptimizerEarlyEPCallback(
806 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
807 ThinOrFullLTOPhase Phase) {
808 ModulePassManager NewMPM;
809 SanitizersCallback(NewMPM, Level, Phase);
810 if (!NewMPM.isEmpty()) {
812 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
813 MPM.addPass(std::move(NewMPM));
818 PB.registerOptimizerLastEPCallback(SanitizersCallback);
824 uint64_t AllowRuntimeCheckSkipHotCutoff =
827 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
830 PB.registerOptimizerEarlyEPCallback(
831 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
832 ModulePassManager &MPM, OptimizationLevel Level,
833 ThinOrFullLTOPhase Phase) {
834 LowerAllowCheckPass::Options Opts;
836 if (ScaledCutoffs.has_value())
837 Opts.cutoffs = ScaledCutoffs.value();
838 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
840 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
848 PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
849 OptimizationLevel Level,
850 ThinOrFullLTOPhase) {
851 if (Level == OptimizationLevel::O0 &&
852 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
856 MPM.addPass(InferFunctionAttrsPass());
862void EmitAssemblyHelper::RunOptimizationPipeline(
863 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
864 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
865 std::optional<PGOOptions> PGOOpt;
872 CodeGenOpts.DebugInfoForProfiling,
874 CodeGenOpts.AtomicProfileUpdate);
878 : PGOOptions::NoCSAction;
883 CodeGenOpts.DebugInfoForProfiling);
890 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
894 PGOOptions::NoAction, PGOOptions::NoCSAction,
896 else if (CodeGenOpts.PseudoProbeForProfiling)
898 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
900 CodeGenOpts.DebugInfoForProfiling,
true);
901 else if (CodeGenOpts.DebugInfoForProfiling)
903 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
909 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
912 assert(PGOOpt->Action != PGOOptions::IRInstr &&
913 PGOOpt->Action != PGOOptions::SampleUse &&
914 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
917 PGOOpt->CSAction = PGOOptions::CSIRInstr;
920 "", PGOOptions::NoAction,
922 CodeGenOpts.DebugInfoForProfiling);
925 TM->setPGOOption(PGOOpt);
927 PipelineTuningOptions PTO;
928 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
929 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
930 PTO.LoopFusion = CodeGenOpts.FuseLoops;
933 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
934 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
935 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
936 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
939 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
940 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
942 LoopAnalysisManager LAM;
943 FunctionAnalysisManager FAM;
944 CGSCCAnalysisManager CGAM;
945 ModuleAnalysisManager MAM;
947 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
948 PassInstrumentationCallbacks PIC;
949 PrintPassOptions PrintPassOpts;
950 PrintPassOpts.Indent = DebugPassStructure;
951 PrintPassOpts.SkipAnalyses = DebugPassStructure;
952 StandardInstrumentations SI(
953 TheModule->getContext(),
954 (CodeGenOpts.DebugPassManager || DebugPassStructure),
955 CodeGenOpts.VerifyEach, PrintPassOpts);
956 SI.registerCallbacks(PIC, &MAM);
960 switch (CodeGenOpts.getAssignmentTrackingMode()) {
961 case CodeGenOptions::AssignmentTrackingOpts::Forced:
962 PB.registerPipelineStartEPCallback(
963 [&](ModulePassManager &MPM, OptimizationLevel Level) {
964 MPM.addPass(AssignmentTrackingPass());
967 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
970 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
971 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
972 PB.registerPipelineStartEPCallback(
973 [&](ModulePassManager &MPM, OptimizationLevel Level) {
975 if (Level != OptimizationLevel::O0)
976 MPM.addPass(AssignmentTrackingPass());
980 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
985 DebugifyEachInstrumentation Debugify;
986 DebugInfoPerPass DebugInfoBeforePass;
987 if (CodeGenOpts.EnableDIPreservationVerify) {
988 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
989 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
992 Debugify.setOrigDIVerifyBugsReportFilePath(
994 Debugify.registerCallbacks(PIC, MAM);
996#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
1003 if (!F.getSubprogram())
1005 for (BasicBlock &BB : F)
1006 for (Instruction &I : BB)
1007 if (!I.getDebugLoc())
1008 I.setDebugLoc(DebugLoc::getCompilerGenerated());
1014 auto PassPlugin = PassPlugin::Load(PluginFN);
1016 PassPlugin->registerPassBuilderCallbacks(PB);
1018 Diags.
Report(diag::err_fe_unable_to_load_plugin)
1019 << PluginFN <<
toString(PassPlugin.takeError());
1024#define HANDLE_EXTENSION(Ext) \
1025 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1026#include "llvm/Support/Extension.def"
1030 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1031 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1032 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1035 PB.registerModuleAnalyses(MAM);
1036 PB.registerCGSCCAnalyses(CGAM);
1037 PB.registerFunctionAnalyses(FAM);
1038 PB.registerLoopAnalyses(LAM);
1039 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1041 ModulePassManager MPM;
1043 if (CodeGenOpts.VerifyModule)
1044 MPM.addPass(VerifierPass());
1046 if (!CodeGenOpts.DisableLLVMPasses) {
1051 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1052 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1054 if (LangOpts.ObjCAutoRefCount) {
1055 PB.registerPipelineStartEPCallback(
1056 [](ModulePassManager &MPM, OptimizationLevel Level) {
1057 if (Level != OptimizationLevel::O0)
1059 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1061 PB.registerScalarOptimizerLateEPCallback(
1062 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1063 if (Level != OptimizationLevel::O0)
1064 FPM.addPass(ObjCARCOptPass());
1074 if (IsThinLTOPostLink)
1075 PB.registerPipelineStartEPCallback(
1076 [](ModulePassManager &MPM, OptimizationLevel Level) {
1077 MPM.addPass(LowerTypeTestsPass(
1080 lowertypetests::DropTestKind::Assume));
1085 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1086 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1087 OptimizationLevel Level) {
1088 BoundsCheckingPass::Options Options;
1091 static_assert(SanitizerKind::SO_LocalBounds <=
1092 std::numeric_limits<
1093 decltype(Options.GuardKind)::value_type>
::max(),
1094 "Update type of llvm.allow.ubsan.check to represent "
1095 "SanitizerKind::SO_LocalBounds.");
1096 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1103 CodeGenOpts.SanitizeMinimalRuntime),
1108 FPM.addPass(BoundsCheckingPass(Options));
1113 if (!IsThinLTOPostLink) {
1119 if (std::optional<GCOVOptions> Options =
1121 PB.registerPipelineStartEPCallback(
1122 [
this, Options](ModulePassManager &MPM, OptimizationLevel Level) {
1126 if (std::optional<InstrProfOptions> Options =
1128 PB.registerPipelineStartEPCallback(
1129 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1130 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1136 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1137 OptimizationLevel Level,
1138 ThinOrFullLTOPhase) {
1139 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1140 MPM.addPass(ModuleMemProfilerPass());
1144 if (CodeGenOpts.FatLTO) {
1145 MPM.addPass(PB.buildFatLTODefaultPipeline(
1146 Level, PrepareForThinLTO,
1147 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1148 }
else if (PrepareForThinLTO) {
1149 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1150 }
else if (PrepareForLTO) {
1151 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1153 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1158 if (CodeGenOpts.LinkBitcodePostopt)
1159 MPM.addPass(LinkInModulesPass(BC));
1161 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1162 LangOpts.HIPStdParInterposeAlloc)
1163 MPM.addPass(HipStdParAllocationInterpositionPass());
1171 MPM.addPass(VerifierPass());
1174 CodeGenOpts.FatLTO) {
1175 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1176 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1177 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1178 CodeGenOpts.EnableSplitLTOUnit);
1185 MPM.addPass(ThinLTOBitcodeWriterPass(
1186 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1188 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1194 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1195 if (EmitLTOSummary) {
1196 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1197 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1198 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1199 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1203 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1206 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1211 if (shouldEmitUnifiedLTOModueFlag() &&
1212 !TheModule->getModuleFlag(
"UnifiedLTO"))
1213 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1220 if (PrintPipelinePasses) {
1221 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1222 auto PassName = PIC.getPassNameForClassName(ClassName);
1223 return PassName.empty() ? ClassName : PassName;
1231 PrettyStackTraceString CrashInfo(
"Optimizer");
1232 llvm::TimeTraceScope TimeScope(
"Optimizer");
1238 MPM.run(*TheModule, MAM);
1244void EmitAssemblyHelper::RunCodegenPipeline(
1245 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1246 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1250 legacy::PassManager CodeGenPasses;
1258 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1264 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1265 DwoOS ? &DwoOS->os() :
nullptr))
1276 if (PrintPipelinePasses) {
1281 PrettyStackTraceString CrashInfo(
"Code generation");
1282 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1285 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1288 CodeGenPasses.run(*TheModule);
1295 std::unique_ptr<raw_pwrite_stream> OS,
1296 BackendConsumer *BC) {
1300 CreateTargetMachine(RequiresCodeGen);
1302 if (RequiresCodeGen && !TM)
1305 TheModule->setDataLayout(TM->createDataLayout());
1308 cl::PrintOptionValues();
1310 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1311 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1312 RunCodegenPipeline(Action, OS, DwoOS);
1322 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1323 std::string SampleProfile, std::string ProfileRemapping,
1328 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1329 ModuleToDefinedGVSummaries;
1330 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1337 FunctionImporter::ImportIDTable ImportIDs;
1338 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1339 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1342 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1343 return std::make_unique<CachedFileStream>(std::move(OS),
1344 CGOpts.ObjectFilenameForDebug);
1347 if (CGOpts.SaveTempsFilePrefix !=
"") {
1348 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1350 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1351 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1356 Conf.CPU = TOpts.CPU;
1358 Conf.MAttrs = TOpts.Features;
1359 Conf.RelocModel = CGOpts.RelocationModel;
1360 std::optional<CodeGenOptLevel> OptLevelOrNone =
1361 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1362 assert(OptLevelOrNone &&
"Invalid optimization level!");
1363 Conf.CGOptLevel = *OptLevelOrNone;
1364 Conf.OptLevel = CGOpts.OptimizationLevel;
1366 Conf.SampleProfile = std::move(SampleProfile);
1367 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1368 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1369 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1372 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1373 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1374 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1377 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1380 if (CGOpts.hasProfileCSIRInstr()) {
1381 Conf.RunCSIRInstr =
true;
1383 }
else if (CGOpts.hasProfileCSIRUse()) {
1384 Conf.RunCSIRInstr =
false;
1385 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1388 Conf.ProfileRemapping = std::move(ProfileRemapping);
1389 Conf.DebugPassManager = CGOpts.DebugPassManager;
1390 Conf.VerifyEach = CGOpts.VerifyEach;
1391 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1392 Conf.RemarksFilename = CGOpts.OptRecordFile;
1393 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1394 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1395 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1396 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1399 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1404 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1405 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1410 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1411 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1422 finalizeLLVMOptimizationRemarks(M->getContext());
1424 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1425 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1426 nullptr, Conf.CodeGenOnly,
1427 nullptr, CGOpts.CmdArgs)) {
1428 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1429 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1435 StringRef TDesc, llvm::Module *M,
1438 std::unique_ptr<raw_pwrite_stream> OS,
1440 llvm::TimeTraceScope TimeScope(
"Backend");
1443 std::unique_ptr<llvm::Module> EmptyModule;
1448 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1449 if (
Error E = llvm::getModuleSummaryIndexForFile(
1452 .moveInto(CombinedIndex)) {
1453 logAllUnhandledErrors(std::move(E), errs(),
1454 "Error loading index file '" +
1462 if (CombinedIndex) {
1463 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1475 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1476 EmptyModule->setTargetTriple(M->getTargetTriple());
1477 M = EmptyModule.get();
1481 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1482 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1487 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1488 if (DLDesc != TDesc) {
1491 "expected target description '%1'");
1492 Diags.
Report(DiagID) << DLDesc << TDesc;
1500 llvm::MemoryBufferRef Buf) {
1503 llvm::embedBitcodeInModule(
1515 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1516 VFS.getBufferForFile(OffloadObject);
1517 if (ObjectOrErr.getError()) {
1519 "could not open '%0' for embedding");
1520 Diags.
Report(DiagID) << OffloadObject;
1524 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1525 Align(object::OffloadBinary::getAlignment()));
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 void runThinLTOBackend(CompilerInstance &CI, ModuleSummaryIndex *CombinedIndex, llvm::Module *M, std::unique_ptr< raw_pwrite_stream > OS, std::string SampleProfile, std::string ProfileRemapping, BackendAction Action)
static SanitizerBinaryMetadataOptions getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts)
static AllocTokenOptions getAllocTokenOptions(const LangOptions &LangOpts, const CodeGenOptions &CGOpts)
static std::optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool initTargetOptions(const CompilerInstance &CI, DiagnosticsEngine &Diags, llvm::TargetOptions &Options)
static void addAllocTokenPass(const Triple &TargetTriple, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts, vfs::FileSystem &VFS)
static std::string getProfileGenName(const CodeGenOptions &CodeGenOpts)
static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts, PassBuilder &PB)
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 CodeGenFileType getCodeGenFileType(BackendAction Action)
static std::string flattenClangCommandLine(ArrayRef< std::string > Args, StringRef MainFilename)
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.
static bool contains(const std::set< tok::TokenKind > &Terminators, const Token &Tok)
Defines the clang::TargetOptions class.
__DEVICE__ int max(int __a, int __b)
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
SanitizerSet SanitizeMergeHandlers
Set of sanitizer checks that can merge handlers (smaller code size at the expense of debuggability).
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
std::string BinutilsVersion
bool hasDWARFExceptions() const
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::vector< std::string > SanitizeCoverageAllowlistFiles
Path to allowlist file specifying which objects (files, functions) should exclusively be instrumented...
std::vector< std::string > SanitizeCoverageIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
bool hasSanitizeCoverage() const
std::string MainFileName
The user provided name for the "main file", if non-empty.
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
bool hasProfileCSIRUse() const
Check if CSIR profile use is on.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
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.
bool hasWasmExceptions() const
bool hasSjLjExceptions() const
SanitizerMaskCutoffs SanitizeSkipHotCutoffs
Set of thresholds in a range [0.0, 1.0]: the top hottest code responsible for the given fraction of P...
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::optional< double > AllowRuntimeCheckSkipHotCutoff
std::vector< std::string > CommandLineArgs
bool hasSEHExceptions() const
std::string MemoryProfileUsePath
Name of the profile file to use as input for -fmemory-profile-use.
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.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
llvm::TimerGroup & getTimerGroup() const
llvm::Timer & getFrontendTimer() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
HeaderSearchOptions & getHeaderSearchOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
@ Single
Single Threaded Environment.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
SanitizerSet Sanitize
Set of enabled sanitizers.
std::optional< llvm::AllocTokenMode > AllocTokenMode
The allocation token mode.
std::optional< uint64_t > AllocTokenMax
Maximum number of allocation tokens (0 = no max), nullopt if none set (use target default).
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
std::optional< std::vector< unsigned > > getAllScaled(unsigned ScalingFactor) const
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string CPU
If given, the name of the target CPU to generate code for.
llvm::EABI EABIVersion
The EABI version to use.
@ Angled
Paths for '#include <>' added by '-I'.
@ System
Like Angled, but marks system directories.
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
llvm::cl::opt< bool > ClSanitizeGuardChecks
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Diagnostic wrappers for TextAPI types for error reporting.
LLVM_ABI 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.