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/LowerTypeTests.h"
64#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
65#include "llvm/Transforms/InstCombine/InstCombine.h"
66#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
68#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
69#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
70#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
71#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
72#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
73#include "llvm/Transforms/Instrumentation/KCFI.h"
74#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
75#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
76#include "llvm/Transforms/Instrumentation/MemProfUse.h"
77#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
78#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
79#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
80#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
81#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
82#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
83#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
84#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
85#include "llvm/Transforms/ObjCARC.h"
86#include "llvm/Transforms/Scalar/EarlyCSE.h"
87#include "llvm/Transforms/Scalar/GVN.h"
88#include "llvm/Transforms/Scalar/JumpThreading.h"
89#include "llvm/Transforms/Utils/Debugify.h"
90#include "llvm/Transforms/Utils/ModuleUtils.h"
97#define HANDLE_EXTENSION(Ext) \
98 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
99#include "llvm/Support/Extension.def"
104 "sanitizer-early-opt-ep", cl::Optional,
105 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
110 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
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.")));
122LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
132 ? llvm::driver::getDefaultProfileGenName()
134 if (CodeGenOpts.ContinuousProfileSync)
141class EmitAssemblyHelper {
142 CompilerInstance &CI;
143 DiagnosticsEngine &Diags;
144 const CodeGenOptions &CodeGenOpts;
145 const clang::TargetOptions &TargetOpts;
146 const LangOptions &LangOpts;
147 llvm::Module *TheModule;
148 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
150 std::unique_ptr<raw_pwrite_stream> OS;
154 TargetIRAnalysis getTargetIRAnalysis()
const {
156 return TM->getTargetIRAnalysis();
158 return TargetIRAnalysis();
169 void CreateTargetMachine(
bool MustCreateTM);
174 bool AddEmitPasses(legacy::PassManager &CodeGenPasses,
BackendAction Action,
175 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
177 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
179 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
180 llvm::sys::fs::OF_None);
182 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
188 void RunOptimizationPipeline(
189 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
190 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
192 std::unique_ptr<raw_pwrite_stream> &OS,
193 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
200 bool shouldEmitRegularLTOSummary()
const {
201 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
202 TargetTriple.getVendor() != llvm::Triple::Apple;
208 bool shouldEmitUnifiedLTOModueFlag()
const {
209 return CodeGenOpts.UnifiedLTO &&
210 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
214 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
216 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
217 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
218 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
219 TheModule(M), VFS(std::move(VFS)),
220 TargetTriple(TheModule->getTargetTriple()) {}
222 ~EmitAssemblyHelper() {
223 if (CodeGenOpts.DisableFree)
224 BuryPointer(std::move(TM));
227 std::unique_ptr<TargetMachine> TM;
230 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
231 BackendConsumer *BC);
235static SanitizerCoverageOptions
237 SanitizerCoverageOptions Opts;
239 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
240 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
241 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
242 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
243 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
244 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
245 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
246 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
247 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
248 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
249 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
250 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
251 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
252 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
253 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
254 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
255 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
256 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
260static SanitizerBinaryMetadataOptions
262 SanitizerBinaryMetadataOptions Opts;
263 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
264 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
265 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
274 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
276 switch (
T.getObjectFormat()) {
281 return !CGOpts.DisableIntegratedAS;
283 llvm::report_fatal_error(
"ASan not implemented for GOFF");
285 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
287 case Triple::DXContainer:
289 case Triple::UnknownObjectFormat:
295static std::optional<llvm::CodeModel::Model>
297 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
298 .Case(
"tiny", llvm::CodeModel::Tiny)
299 .Case(
"small", llvm::CodeModel::Small)
300 .Case(
"kernel", llvm::CodeModel::Kernel)
301 .Case(
"medium", llvm::CodeModel::Medium)
302 .Case(
"large", llvm::CodeModel::Large)
303 .Cases(
"default",
"", ~1u)
305 assert(CodeModel != ~0u &&
"invalid code model!");
306 if (CodeModel == ~1u)
308 return static_cast<llvm::CodeModel::Model
>(CodeModel);
313 return CodeGenFileType::ObjectFile;
315 return CodeGenFileType::Null;
318 return CodeGenFileType::AssemblyFile;
328 StringRef MainFilename) {
330 return std::string{};
332 std::string FlatCmdLine;
333 raw_string_ostream OS(FlatCmdLine);
334 bool PrintedOneArg =
false;
335 if (!StringRef(Args[0]).
contains(
"-cc1")) {
336 llvm::sys::printArg(OS,
"-cc1",
true);
337 PrintedOneArg =
true;
339 for (
unsigned i = 0; i < Args.size(); i++) {
340 StringRef Arg = Args[i];
343 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
347 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
350 if (Arg.starts_with(
"-fmessage-length"))
354 llvm::sys::printArg(OS, Arg,
true);
355 PrintedOneArg =
true;
362 llvm::TargetOptions &Options) {
367 switch (LangOpts.getThreadModel()) {
369 Options.ThreadModel = llvm::ThreadModel::POSIX;
372 Options.ThreadModel = llvm::ThreadModel::Single;
377 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
379 "Invalid Floating Point ABI!");
380 Options.FloatABIType =
381 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
382 .Case(
"soft", llvm::FloatABI::Soft)
383 .Case(
"softfp", llvm::FloatABI::Soft)
384 .Case(
"hard", llvm::FloatABI::Hard)
385 .Default(llvm::FloatABI::Default);
388 switch (LangOpts.getDefaultFPContractMode()) {
392 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
396 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
399 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
403 Options.BinutilsVersion =
404 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
405 Options.UseInitArray = CodeGenOpts.UseInitArray;
406 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
412 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
414 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
416 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
418 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
420 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
421 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
422 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
423 Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
424 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
425 (LangOpts.getDefaultFPContractMode() ==
427 LangOpts.getDefaultFPContractMode() ==
430 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
432 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
433 .Case(
"all", llvm::BasicBlockSection::All)
434 .StartsWith(
"list=", llvm::BasicBlockSection::List)
435 .Case(
"none", llvm::BasicBlockSection::None)
436 .Default(llvm::BasicBlockSection::None);
438 if (Options.BBSections == llvm::BasicBlockSection::List) {
439 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
440 MemoryBuffer::getFile(CodeGenOpts.
BBSections.substr(5));
442 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
443 << MBOrErr.getError().message();
446 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
449 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
450 Options.FunctionSections = CodeGenOpts.FunctionSections;
451 Options.DataSections = CodeGenOpts.DataSections;
452 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
453 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
454 Options.UniqueBasicBlockSectionNames =
455 CodeGenOpts.UniqueBasicBlockSectionNames;
456 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
457 Options.TLSSize = CodeGenOpts.TLSSize;
458 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
459 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
460 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
461 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
463 Options.EmitAddrsig = CodeGenOpts.Addrsig;
464 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
465 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
466 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
467 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
468 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
469 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
471 Options.Hotpatch = CodeGenOpts.HotPatch;
472 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
473 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
475 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
477 Options.SwiftAsyncFramePointer =
478 SwiftAsyncFramePointerMode::DeploymentBased;
482 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
486 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
491 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
492 Options.MCOptions.EmitCompactUnwindNonCanonical =
493 CodeGenOpts.EmitCompactUnwindNonCanonical;
494 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
495 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
496 Options.MCOptions.MCUseDwarfDirectory =
497 CodeGenOpts.NoDwarfDirectoryAsm
498 ? llvm::MCTargetOptions::DisableDwarfDirectory
499 : llvm::MCTargetOptions::EnableDwarfDirectory;
500 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
501 Options.MCOptions.MCIncrementalLinkerCompatible =
502 CodeGenOpts.IncrementalLinkerCompatible;
503 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
504 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
505 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
506 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
507 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
508 Options.MCOptions.Crel = CodeGenOpts.Crel;
509 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
510 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
511 Options.MCOptions.CompressDebugSections =
512 CodeGenOpts.getCompressDebugSections();
513 if (CodeGenOpts.OutputAsmVariant != 3)
514 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
515 Options.MCOptions.ABIName = TargetOpts.
ABI;
516 for (
const auto &Entry : HSOpts.UserEntries)
517 if (!Entry.IsFramework &&
521 Options.MCOptions.IASSearchPaths.push_back(
522 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
523 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
527 Options.MCOptions.PPCUseFullRegisterNames =
528 CodeGenOpts.PPCUseFullRegisterNames;
529 Options.MisExpect = CodeGenOpts.MisExpect;
534static std::optional<GCOVOptions>
545 Options.NoRedZone = CodeGenOpts.DisableRedZone;
548 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
552static std::optional<InstrProfOptions>
557 InstrProfOptions Options;
558 Options.NoRedZone = CodeGenOpts.DisableRedZone;
562 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
567 vfs::FileSystem &VFS) {
569 BackendArgs.push_back(
"clang");
571 BackendArgs.push_back(
"-debug-pass");
572 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
575 BackendArgs.push_back(
"-limit-float-precision");
581 if (BackendArgs.size() == 1)
583 BackendArgs.push_back(
nullptr);
587 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
592void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
595 const llvm::Triple &Triple = TheModule->getTargetTriple();
596 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
599 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
603 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
604 std::string FeaturesStr =
607 std::optional<CodeGenOptLevel> OptLevelOrNone =
608 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
609 assert(OptLevelOrNone &&
"Invalid optimization level!");
610 CodeGenOptLevel OptLevel = *OptLevelOrNone;
612 llvm::TargetOptions Options;
615 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
616 Options, RM, CM, OptLevel));
621bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
623 raw_pwrite_stream &OS,
624 raw_pwrite_stream *DwoOS) {
626 std::unique_ptr<TargetLibraryInfoImpl> TLII(
627 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
628 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
634 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
635 !CodeGenOpts.VerifyModule)) {
636 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
644 switch (Opts.OptimizationLevel) {
646 llvm_unreachable(
"Invalid optimization level!");
649 return OptimizationLevel::O0;
652 return OptimizationLevel::O1;
655 switch (Opts.OptimizeSize) {
657 llvm_unreachable(
"Invalid optimization level for size!");
660 return OptimizationLevel::O2;
663 return OptimizationLevel::Os;
666 return OptimizationLevel::Oz;
670 return OptimizationLevel::O3;
677 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
678 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
682 PB.registerOptimizerLastEPCallback(
683 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
684 if (Level == OptimizationLevel::O0 &&
686 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
691 PB.registerPeepholeEPCallback(
692 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
693 if (Level != OptimizationLevel::O0 &&
695 FPM.addPass(KCFIPass());
702 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
703 ThinOrFullLTOPhase) {
706 MPM.addPass(SanitizerCoveragePass(
712 MPM.addPass(SanitizerBinaryMetadataPass(
717 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
719 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
722 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
723 CodeGenOpts.SanitizeMemoryParamRetval);
724 MPM.addPass(MemorySanitizerPass(options));
725 if (Level != OptimizationLevel::O0) {
730 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
731 FunctionPassManager FPM;
732 FPM.addPass(EarlyCSEPass(
true ));
733 FPM.addPass(InstCombinePass());
734 FPM.addPass(JumpThreadingPass());
735 FPM.addPass(GVNPass());
736 FPM.addPass(InstCombinePass());
737 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
741 MSanPass(SanitizerKind::Memory,
false);
742 MSanPass(SanitizerKind::KernelMemory,
true);
744 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
745 MPM.addPass(ModuleThreadSanitizerPass());
746 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
750 MPM.addPass(TypeSanitizerPass());
752 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
753 MPM.addPass(NumericalStabilitySanitizerPass());
755 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
756 MPM.addPass(RealtimeSanitizerPass());
758 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
761 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
762 llvm::AsanDtorKind DestructorKind =
763 CodeGenOpts.getSanitizeAddressDtor();
764 AddressSanitizerOptions Opts;
765 Opts.CompileKernel = CompileKernel;
767 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
768 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
769 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
773 ASanPass(SanitizerKind::Address,
false);
774 ASanPass(SanitizerKind::KernelAddress,
true);
776 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
779 MPM.addPass(HWAddressSanitizerPass(
780 {CompileKernel, Recover,
781 CodeGenOpts.OptimizationLevel == 0}));
784 HWASanPass(SanitizerKind::HWAddress,
false);
785 HWASanPass(SanitizerKind::KernelHWAddress,
true);
787 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
789 PB.getVirtualFileSystemPtr()));
793 PB.registerOptimizerEarlyEPCallback(
794 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
795 ThinOrFullLTOPhase Phase) {
796 ModulePassManager NewMPM;
797 SanitizersCallback(NewMPM, Level, Phase);
798 if (!NewMPM.isEmpty()) {
800 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
801 MPM.addPass(std::move(NewMPM));
806 PB.registerOptimizerLastEPCallback(SanitizersCallback);
812 uint64_t AllowRuntimeCheckSkipHotCutoff =
815 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
818 PB.registerOptimizerEarlyEPCallback(
819 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
820 ModulePassManager &MPM, OptimizationLevel Level,
821 ThinOrFullLTOPhase Phase) {
822 LowerAllowCheckPass::Options Opts;
824 if (ScaledCutoffs.has_value())
825 Opts.cutoffs = ScaledCutoffs.value();
826 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
828 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
833void EmitAssemblyHelper::RunOptimizationPipeline(
834 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
835 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
836 std::optional<PGOOptions> PGOOpt;
843 CodeGenOpts.DebugInfoForProfiling,
845 CodeGenOpts.AtomicProfileUpdate);
849 : PGOOptions::NoCSAction;
854 CodeGenOpts.DebugInfoForProfiling);
861 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
865 PGOOptions::NoAction, PGOOptions::NoCSAction,
867 else if (CodeGenOpts.PseudoProbeForProfiling)
869 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
871 CodeGenOpts.DebugInfoForProfiling,
true);
872 else if (CodeGenOpts.DebugInfoForProfiling)
874 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
880 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
883 assert(PGOOpt->Action != PGOOptions::IRInstr &&
884 PGOOpt->Action != PGOOptions::SampleUse &&
885 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
888 PGOOpt->CSAction = PGOOptions::CSIRInstr;
891 "", PGOOptions::NoAction,
893 CodeGenOpts.DebugInfoForProfiling);
896 TM->setPGOOption(PGOOpt);
898 PipelineTuningOptions PTO;
899 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
900 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
901 PTO.LoopFusion = CodeGenOpts.FuseLoops;
904 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
905 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
906 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
907 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
910 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
911 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
913 LoopAnalysisManager LAM;
914 FunctionAnalysisManager FAM;
915 CGSCCAnalysisManager CGAM;
916 ModuleAnalysisManager MAM;
918 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
919 PassInstrumentationCallbacks PIC;
920 PrintPassOptions PrintPassOpts;
921 PrintPassOpts.Indent = DebugPassStructure;
922 PrintPassOpts.SkipAnalyses = DebugPassStructure;
923 StandardInstrumentations SI(
924 TheModule->getContext(),
925 (CodeGenOpts.DebugPassManager || DebugPassStructure),
926 CodeGenOpts.VerifyEach, PrintPassOpts);
927 SI.registerCallbacks(PIC, &MAM);
931 switch (CodeGenOpts.getAssignmentTrackingMode()) {
932 case CodeGenOptions::AssignmentTrackingOpts::Forced:
933 PB.registerPipelineStartEPCallback(
934 [&](ModulePassManager &MPM, OptimizationLevel Level) {
935 MPM.addPass(AssignmentTrackingPass());
938 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
941 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
942 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
943 PB.registerPipelineStartEPCallback(
944 [&](ModulePassManager &MPM, OptimizationLevel Level) {
946 if (Level != OptimizationLevel::O0)
947 MPM.addPass(AssignmentTrackingPass());
951 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
956 DebugifyEachInstrumentation Debugify;
957 DebugInfoPerPass DebugInfoBeforePass;
958 if (CodeGenOpts.EnableDIPreservationVerify) {
959 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
960 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
963 Debugify.setOrigDIVerifyBugsReportFilePath(
965 Debugify.registerCallbacks(PIC, MAM);
967#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
974 if (!F.getSubprogram())
976 for (BasicBlock &BB : F)
977 for (Instruction &I : BB)
978 if (!I.getDebugLoc())
979 I.setDebugLoc(DebugLoc::getCompilerGenerated());
985 auto PassPlugin = PassPlugin::Load(PluginFN);
987 PassPlugin->registerPassBuilderCallbacks(PB);
989 Diags.
Report(diag::err_fe_unable_to_load_plugin)
990 << PluginFN <<
toString(PassPlugin.takeError());
995#define HANDLE_EXTENSION(Ext) \
996 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
997#include "llvm/Support/Extension.def"
1001 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1002 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1003 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1006 PB.registerModuleAnalyses(MAM);
1007 PB.registerCGSCCAnalyses(CGAM);
1008 PB.registerFunctionAnalyses(FAM);
1009 PB.registerLoopAnalyses(LAM);
1010 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1012 ModulePassManager MPM;
1014 if (CodeGenOpts.VerifyModule)
1015 MPM.addPass(VerifierPass());
1017 if (!CodeGenOpts.DisableLLVMPasses) {
1022 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1023 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1025 if (LangOpts.ObjCAutoRefCount) {
1026 PB.registerPipelineStartEPCallback(
1027 [](ModulePassManager &MPM, OptimizationLevel Level) {
1028 if (Level != OptimizationLevel::O0)
1030 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1032 PB.registerScalarOptimizerLateEPCallback(
1033 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1034 if (Level != OptimizationLevel::O0)
1035 FPM.addPass(ObjCARCOptPass());
1045 if (IsThinLTOPostLink)
1046 PB.registerPipelineStartEPCallback(
1047 [](ModulePassManager &MPM, OptimizationLevel Level) {
1048 MPM.addPass(LowerTypeTestsPass(
1051 lowertypetests::DropTestKind::Assume));
1056 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1057 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1058 OptimizationLevel Level) {
1059 BoundsCheckingPass::Options Options;
1062 static_assert(SanitizerKind::SO_LocalBounds <=
1063 std::numeric_limits<
1064 decltype(Options.GuardKind)::value_type>
::max(),
1065 "Update type of llvm.allow.ubsan.check to represent "
1066 "SanitizerKind::SO_LocalBounds.");
1067 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1074 CodeGenOpts.SanitizeMinimalRuntime),
1079 FPM.addPass(BoundsCheckingPass(Options));
1084 if (!IsThinLTOPostLink) {
1089 if (std::optional<GCOVOptions> Options =
1091 PB.registerPipelineStartEPCallback(
1092 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1093 MPM.addPass(GCOVProfilerPass(*Options));
1095 if (std::optional<InstrProfOptions> Options =
1097 PB.registerPipelineStartEPCallback(
1098 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1099 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1105 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1106 OptimizationLevel Level,
1107 ThinOrFullLTOPhase) {
1108 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1109 MPM.addPass(ModuleMemProfilerPass());
1113 if (CodeGenOpts.FatLTO) {
1114 MPM.addPass(PB.buildFatLTODefaultPipeline(
1115 Level, PrepareForThinLTO,
1116 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1117 }
else if (PrepareForThinLTO) {
1118 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1119 }
else if (PrepareForLTO) {
1120 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1122 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1127 if (CodeGenOpts.LinkBitcodePostopt)
1128 MPM.addPass(LinkInModulesPass(BC));
1130 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1131 LangOpts.HIPStdParInterposeAlloc)
1132 MPM.addPass(HipStdParAllocationInterpositionPass());
1140 MPM.addPass(VerifierPass());
1143 CodeGenOpts.FatLTO) {
1144 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1145 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1146 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1147 CodeGenOpts.EnableSplitLTOUnit);
1154 MPM.addPass(ThinLTOBitcodeWriterPass(
1155 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1157 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1163 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1164 if (EmitLTOSummary) {
1165 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1166 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1167 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1168 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1172 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1175 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1180 if (shouldEmitUnifiedLTOModueFlag())
1181 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1188 if (PrintPipelinePasses) {
1189 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1190 auto PassName = PIC.getPassNameForClassName(ClassName);
1191 return PassName.empty() ? ClassName : PassName;
1199 PrettyStackTraceString CrashInfo(
"Optimizer");
1200 llvm::TimeTraceScope TimeScope(
"Optimizer");
1206 MPM.run(*TheModule, MAM);
1212void EmitAssemblyHelper::RunCodegenPipeline(
1213 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1214 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1218 legacy::PassManager CodeGenPasses;
1226 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1232 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1233 DwoOS ? &DwoOS->os() :
nullptr))
1244 if (PrintPipelinePasses) {
1249 PrettyStackTraceString CrashInfo(
"Code generation");
1250 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1253 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1256 CodeGenPasses.run(*TheModule);
1263 std::unique_ptr<raw_pwrite_stream> OS,
1264 BackendConsumer *BC) {
1268 CreateTargetMachine(RequiresCodeGen);
1270 if (RequiresCodeGen && !TM)
1273 TheModule->setDataLayout(TM->createDataLayout());
1276 cl::PrintOptionValues();
1278 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1279 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1280 RunCodegenPipeline(Action, OS, DwoOS);
1290 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1291 std::string SampleProfile, std::string ProfileRemapping,
1296 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1297 ModuleToDefinedGVSummaries;
1298 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1305 FunctionImporter::ImportIDTable ImportIDs;
1306 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1307 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1310 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1311 return std::make_unique<CachedFileStream>(std::move(OS),
1312 CGOpts.ObjectFilenameForDebug);
1315 if (CGOpts.SaveTempsFilePrefix !=
"") {
1316 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1318 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1319 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1324 Conf.CPU = TOpts.CPU;
1326 Conf.MAttrs = TOpts.Features;
1327 Conf.RelocModel = CGOpts.RelocationModel;
1328 std::optional<CodeGenOptLevel> OptLevelOrNone =
1329 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1330 assert(OptLevelOrNone &&
"Invalid optimization level!");
1331 Conf.CGOptLevel = *OptLevelOrNone;
1332 Conf.OptLevel = CGOpts.OptimizationLevel;
1334 Conf.SampleProfile = std::move(SampleProfile);
1335 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1336 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1337 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1340 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1341 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1342 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1345 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1348 if (CGOpts.hasProfileCSIRInstr()) {
1349 Conf.RunCSIRInstr =
true;
1351 }
else if (CGOpts.hasProfileCSIRUse()) {
1352 Conf.RunCSIRInstr =
false;
1353 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1356 Conf.ProfileRemapping = std::move(ProfileRemapping);
1357 Conf.DebugPassManager = CGOpts.DebugPassManager;
1358 Conf.VerifyEach = CGOpts.VerifyEach;
1359 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1360 Conf.RemarksFilename = CGOpts.OptRecordFile;
1361 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1362 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1363 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1364 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1367 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1372 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1373 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1378 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1379 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1390 finalizeLLVMOptimizationRemarks(M->getContext());
1392 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1393 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1394 nullptr, Conf.CodeGenOnly,
1395 nullptr, CGOpts.CmdArgs)) {
1396 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1397 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1403 StringRef TDesc, llvm::Module *M,
1406 std::unique_ptr<raw_pwrite_stream> OS,
1408 llvm::TimeTraceScope TimeScope(
"Backend");
1411 std::unique_ptr<llvm::Module> EmptyModule;
1416 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1417 if (
Error E = llvm::getModuleSummaryIndexForFile(
1420 .moveInto(CombinedIndex)) {
1421 logAllUnhandledErrors(std::move(E), errs(),
1422 "Error loading index file '" +
1430 if (CombinedIndex) {
1431 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1443 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1444 EmptyModule->setTargetTriple(M->getTargetTriple());
1445 M = EmptyModule.get();
1449 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1450 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1455 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1456 if (DLDesc != TDesc) {
1459 "expected target description '%1'");
1460 Diags.
Report(DiagID) << DLDesc << TDesc;
1468 llvm::MemoryBufferRef Buf) {
1471 llvm::embedBitcodeInModule(
1483 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1484 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1485 if (ObjectOrErr.getError()) {
1487 "could not open '%0' for embedding");
1488 Diags.
Report(DiagID) << OffloadObject;
1492 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1493 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 std::optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool initTargetOptions(const CompilerInstance &CI, DiagnosticsEngine &Diags, llvm::TargetOptions &Options)
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::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.
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
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 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.