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 =
443 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
444 << MBOrErr.getError().message();
447 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
450 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
451 Options.FunctionSections = CodeGenOpts.FunctionSections;
452 Options.DataSections = CodeGenOpts.DataSections;
453 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
454 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
455 Options.UniqueBasicBlockSectionNames =
456 CodeGenOpts.UniqueBasicBlockSectionNames;
457 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
458 Options.TLSSize = CodeGenOpts.TLSSize;
459 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
460 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
461 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
462 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
464 Options.EmitAddrsig = CodeGenOpts.Addrsig;
465 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
466 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
467 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
468 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
469 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
470 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
472 Options.Hotpatch = CodeGenOpts.HotPatch;
473 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
474 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
476 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
478 Options.SwiftAsyncFramePointer =
479 SwiftAsyncFramePointerMode::DeploymentBased;
483 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
487 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
492 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
493 Options.MCOptions.EmitCompactUnwindNonCanonical =
494 CodeGenOpts.EmitCompactUnwindNonCanonical;
495 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
496 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
497 Options.MCOptions.MCUseDwarfDirectory =
498 CodeGenOpts.NoDwarfDirectoryAsm
499 ? llvm::MCTargetOptions::DisableDwarfDirectory
500 : llvm::MCTargetOptions::EnableDwarfDirectory;
501 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
502 Options.MCOptions.MCIncrementalLinkerCompatible =
503 CodeGenOpts.IncrementalLinkerCompatible;
504 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
505 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
506 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
507 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
508 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
509 Options.MCOptions.Crel = CodeGenOpts.Crel;
510 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
511 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
512 Options.MCOptions.CompressDebugSections =
513 CodeGenOpts.getCompressDebugSections();
514 if (CodeGenOpts.OutputAsmVariant != 3)
515 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
516 Options.MCOptions.ABIName = TargetOpts.
ABI;
517 for (
const auto &Entry : HSOpts.UserEntries)
518 if (!Entry.IsFramework &&
522 Options.MCOptions.IASSearchPaths.push_back(
523 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
524 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
528 Options.MCOptions.PPCUseFullRegisterNames =
529 CodeGenOpts.PPCUseFullRegisterNames;
530 Options.MisExpect = CodeGenOpts.MisExpect;
535static std::optional<GCOVOptions>
546 Options.NoRedZone = CodeGenOpts.DisableRedZone;
549 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
553static std::optional<InstrProfOptions>
558 InstrProfOptions Options;
559 Options.NoRedZone = CodeGenOpts.DisableRedZone;
563 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
568 vfs::FileSystem &VFS) {
570 BackendArgs.push_back(
"clang");
572 BackendArgs.push_back(
"-debug-pass");
573 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
576 BackendArgs.push_back(
"-limit-float-precision");
582 if (BackendArgs.size() == 1)
584 BackendArgs.push_back(
nullptr);
588 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
593void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
596 const llvm::Triple &Triple = TheModule->getTargetTriple();
597 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
600 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
604 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
605 std::string FeaturesStr =
608 std::optional<CodeGenOptLevel> OptLevelOrNone =
609 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
610 assert(OptLevelOrNone &&
"Invalid optimization level!");
611 CodeGenOptLevel OptLevel = *OptLevelOrNone;
613 llvm::TargetOptions Options;
616 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
617 Options, RM, CM, OptLevel));
622bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
624 raw_pwrite_stream &OS,
625 raw_pwrite_stream *DwoOS) {
627 std::unique_ptr<TargetLibraryInfoImpl> TLII(
628 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
629 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
635 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
636 !CodeGenOpts.VerifyModule)) {
637 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
645 switch (Opts.OptimizationLevel) {
647 llvm_unreachable(
"Invalid optimization level!");
650 return OptimizationLevel::O0;
653 return OptimizationLevel::O1;
656 switch (Opts.OptimizeSize) {
658 llvm_unreachable(
"Invalid optimization level for size!");
661 return OptimizationLevel::O2;
664 return OptimizationLevel::Os;
667 return OptimizationLevel::Oz;
671 return OptimizationLevel::O3;
678 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
679 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
683 PB.registerOptimizerLastEPCallback(
684 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
685 if (Level == OptimizationLevel::O0 &&
687 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
692 PB.registerPeepholeEPCallback(
693 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
694 if (Level != OptimizationLevel::O0 &&
696 FPM.addPass(KCFIPass());
703 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
704 ThinOrFullLTOPhase) {
707 MPM.addPass(SanitizerCoveragePass(
713 MPM.addPass(SanitizerBinaryMetadataPass(
718 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
720 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
723 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
724 CodeGenOpts.SanitizeMemoryParamRetval);
725 MPM.addPass(MemorySanitizerPass(options));
726 if (Level != OptimizationLevel::O0) {
731 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
732 FunctionPassManager FPM;
733 FPM.addPass(EarlyCSEPass(
true ));
734 FPM.addPass(InstCombinePass());
735 FPM.addPass(JumpThreadingPass());
736 FPM.addPass(GVNPass());
737 FPM.addPass(InstCombinePass());
738 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
742 MSanPass(SanitizerKind::Memory,
false);
743 MSanPass(SanitizerKind::KernelMemory,
true);
745 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
746 MPM.addPass(ModuleThreadSanitizerPass());
747 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
751 MPM.addPass(TypeSanitizerPass());
753 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
754 MPM.addPass(NumericalStabilitySanitizerPass());
756 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
757 MPM.addPass(RealtimeSanitizerPass());
759 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
762 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
763 llvm::AsanDtorKind DestructorKind =
764 CodeGenOpts.getSanitizeAddressDtor();
765 AddressSanitizerOptions Opts;
766 Opts.CompileKernel = CompileKernel;
768 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
769 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
770 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
774 ASanPass(SanitizerKind::Address,
false);
775 ASanPass(SanitizerKind::KernelAddress,
true);
777 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
780 MPM.addPass(HWAddressSanitizerPass(
781 {CompileKernel, Recover,
782 CodeGenOpts.OptimizationLevel == 0}));
785 HWASanPass(SanitizerKind::HWAddress,
false);
786 HWASanPass(SanitizerKind::KernelHWAddress,
true);
788 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
790 PB.getVirtualFileSystemPtr()));
794 PB.registerOptimizerEarlyEPCallback(
795 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
796 ThinOrFullLTOPhase Phase) {
797 ModulePassManager NewMPM;
798 SanitizersCallback(NewMPM, Level, Phase);
799 if (!NewMPM.isEmpty()) {
801 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
802 MPM.addPass(std::move(NewMPM));
807 PB.registerOptimizerLastEPCallback(SanitizersCallback);
813 uint64_t AllowRuntimeCheckSkipHotCutoff =
816 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
819 PB.registerOptimizerEarlyEPCallback(
820 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
821 ModulePassManager &MPM, OptimizationLevel Level,
822 ThinOrFullLTOPhase Phase) {
823 LowerAllowCheckPass::Options Opts;
825 if (ScaledCutoffs.has_value())
826 Opts.cutoffs = ScaledCutoffs.value();
827 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
829 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
834void EmitAssemblyHelper::RunOptimizationPipeline(
835 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
836 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
837 std::optional<PGOOptions> PGOOpt;
844 CodeGenOpts.DebugInfoForProfiling,
846 CodeGenOpts.AtomicProfileUpdate);
850 : PGOOptions::NoCSAction;
855 CodeGenOpts.DebugInfoForProfiling);
862 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
866 PGOOptions::NoAction, PGOOptions::NoCSAction,
868 else if (CodeGenOpts.PseudoProbeForProfiling)
870 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
872 CodeGenOpts.DebugInfoForProfiling,
true);
873 else if (CodeGenOpts.DebugInfoForProfiling)
875 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
881 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
884 assert(PGOOpt->Action != PGOOptions::IRInstr &&
885 PGOOpt->Action != PGOOptions::SampleUse &&
886 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
889 PGOOpt->CSAction = PGOOptions::CSIRInstr;
892 "", PGOOptions::NoAction,
894 CodeGenOpts.DebugInfoForProfiling);
897 TM->setPGOOption(PGOOpt);
899 PipelineTuningOptions PTO;
900 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
901 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
902 PTO.LoopFusion = CodeGenOpts.FuseLoops;
905 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
906 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
907 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
908 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
911 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
912 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
914 LoopAnalysisManager LAM;
915 FunctionAnalysisManager FAM;
916 CGSCCAnalysisManager CGAM;
917 ModuleAnalysisManager MAM;
919 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
920 PassInstrumentationCallbacks PIC;
921 PrintPassOptions PrintPassOpts;
922 PrintPassOpts.Indent = DebugPassStructure;
923 PrintPassOpts.SkipAnalyses = DebugPassStructure;
924 StandardInstrumentations SI(
925 TheModule->getContext(),
926 (CodeGenOpts.DebugPassManager || DebugPassStructure),
927 CodeGenOpts.VerifyEach, PrintPassOpts);
928 SI.registerCallbacks(PIC, &MAM);
932 switch (CodeGenOpts.getAssignmentTrackingMode()) {
933 case CodeGenOptions::AssignmentTrackingOpts::Forced:
934 PB.registerPipelineStartEPCallback(
935 [&](ModulePassManager &MPM, OptimizationLevel Level) {
936 MPM.addPass(AssignmentTrackingPass());
939 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
942 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
943 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
944 PB.registerPipelineStartEPCallback(
945 [&](ModulePassManager &MPM, OptimizationLevel Level) {
947 if (Level != OptimizationLevel::O0)
948 MPM.addPass(AssignmentTrackingPass());
952 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
957 DebugifyEachInstrumentation Debugify;
958 DebugInfoPerPass DebugInfoBeforePass;
959 if (CodeGenOpts.EnableDIPreservationVerify) {
960 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
961 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
964 Debugify.setOrigDIVerifyBugsReportFilePath(
966 Debugify.registerCallbacks(PIC, MAM);
968#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
975 if (!F.getSubprogram())
977 for (BasicBlock &BB : F)
978 for (Instruction &I : BB)
979 if (!I.getDebugLoc())
980 I.setDebugLoc(DebugLoc::getCompilerGenerated());
986 auto PassPlugin = PassPlugin::Load(PluginFN);
988 PassPlugin->registerPassBuilderCallbacks(PB);
990 Diags.
Report(diag::err_fe_unable_to_load_plugin)
991 << PluginFN <<
toString(PassPlugin.takeError());
996#define HANDLE_EXTENSION(Ext) \
997 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
998#include "llvm/Support/Extension.def"
1002 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1003 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1004 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1007 PB.registerModuleAnalyses(MAM);
1008 PB.registerCGSCCAnalyses(CGAM);
1009 PB.registerFunctionAnalyses(FAM);
1010 PB.registerLoopAnalyses(LAM);
1011 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1013 ModulePassManager MPM;
1015 if (CodeGenOpts.VerifyModule)
1016 MPM.addPass(VerifierPass());
1018 if (!CodeGenOpts.DisableLLVMPasses) {
1023 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1024 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1026 if (LangOpts.ObjCAutoRefCount) {
1027 PB.registerPipelineStartEPCallback(
1028 [](ModulePassManager &MPM, OptimizationLevel Level) {
1029 if (Level != OptimizationLevel::O0)
1031 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1033 PB.registerScalarOptimizerLateEPCallback(
1034 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1035 if (Level != OptimizationLevel::O0)
1036 FPM.addPass(ObjCARCOptPass());
1046 if (IsThinLTOPostLink)
1047 PB.registerPipelineStartEPCallback(
1048 [](ModulePassManager &MPM, OptimizationLevel Level) {
1049 MPM.addPass(LowerTypeTestsPass(
1052 lowertypetests::DropTestKind::Assume));
1057 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1058 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1059 OptimizationLevel Level) {
1060 BoundsCheckingPass::Options Options;
1063 static_assert(SanitizerKind::SO_LocalBounds <=
1064 std::numeric_limits<
1065 decltype(Options.GuardKind)::value_type>
::max(),
1066 "Update type of llvm.allow.ubsan.check to represent "
1067 "SanitizerKind::SO_LocalBounds.");
1068 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1075 CodeGenOpts.SanitizeMinimalRuntime),
1080 FPM.addPass(BoundsCheckingPass(Options));
1085 if (!IsThinLTOPostLink) {
1090 if (std::optional<GCOVOptions> Options =
1092 PB.registerPipelineStartEPCallback(
1093 [
this, Options](ModulePassManager &MPM, OptimizationLevel Level) {
1097 if (std::optional<InstrProfOptions> Options =
1099 PB.registerPipelineStartEPCallback(
1100 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1101 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1107 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1108 OptimizationLevel Level,
1109 ThinOrFullLTOPhase) {
1110 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1111 MPM.addPass(ModuleMemProfilerPass());
1115 if (CodeGenOpts.FatLTO) {
1116 MPM.addPass(PB.buildFatLTODefaultPipeline(
1117 Level, PrepareForThinLTO,
1118 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1119 }
else if (PrepareForThinLTO) {
1120 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1121 }
else if (PrepareForLTO) {
1122 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1124 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1129 if (CodeGenOpts.LinkBitcodePostopt)
1130 MPM.addPass(LinkInModulesPass(BC));
1132 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1133 LangOpts.HIPStdParInterposeAlloc)
1134 MPM.addPass(HipStdParAllocationInterpositionPass());
1142 MPM.addPass(VerifierPass());
1145 CodeGenOpts.FatLTO) {
1146 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1147 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1148 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1149 CodeGenOpts.EnableSplitLTOUnit);
1156 MPM.addPass(ThinLTOBitcodeWriterPass(
1157 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1159 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1165 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1166 if (EmitLTOSummary) {
1167 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1168 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1169 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1170 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1174 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1177 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1182 if (shouldEmitUnifiedLTOModueFlag())
1183 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1190 if (PrintPipelinePasses) {
1191 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1192 auto PassName = PIC.getPassNameForClassName(ClassName);
1193 return PassName.empty() ? ClassName : PassName;
1201 PrettyStackTraceString CrashInfo(
"Optimizer");
1202 llvm::TimeTraceScope TimeScope(
"Optimizer");
1208 MPM.run(*TheModule, MAM);
1214void EmitAssemblyHelper::RunCodegenPipeline(
1215 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1216 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1220 legacy::PassManager CodeGenPasses;
1228 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1234 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1235 DwoOS ? &DwoOS->os() :
nullptr))
1246 if (PrintPipelinePasses) {
1251 PrettyStackTraceString CrashInfo(
"Code generation");
1252 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1255 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1258 CodeGenPasses.run(*TheModule);
1265 std::unique_ptr<raw_pwrite_stream> OS,
1266 BackendConsumer *BC) {
1270 CreateTargetMachine(RequiresCodeGen);
1272 if (RequiresCodeGen && !TM)
1275 TheModule->setDataLayout(TM->createDataLayout());
1278 cl::PrintOptionValues();
1280 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1281 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1282 RunCodegenPipeline(Action, OS, DwoOS);
1292 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1293 std::string SampleProfile, std::string ProfileRemapping,
1298 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1299 ModuleToDefinedGVSummaries;
1300 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1307 FunctionImporter::ImportIDTable ImportIDs;
1308 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1309 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1312 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1313 return std::make_unique<CachedFileStream>(std::move(OS),
1314 CGOpts.ObjectFilenameForDebug);
1317 if (CGOpts.SaveTempsFilePrefix !=
"") {
1318 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1320 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1321 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1326 Conf.CPU = TOpts.CPU;
1328 Conf.MAttrs = TOpts.Features;
1329 Conf.RelocModel = CGOpts.RelocationModel;
1330 std::optional<CodeGenOptLevel> OptLevelOrNone =
1331 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1332 assert(OptLevelOrNone &&
"Invalid optimization level!");
1333 Conf.CGOptLevel = *OptLevelOrNone;
1334 Conf.OptLevel = CGOpts.OptimizationLevel;
1336 Conf.SampleProfile = std::move(SampleProfile);
1337 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1338 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1339 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1342 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1343 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1344 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1347 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1350 if (CGOpts.hasProfileCSIRInstr()) {
1351 Conf.RunCSIRInstr =
true;
1353 }
else if (CGOpts.hasProfileCSIRUse()) {
1354 Conf.RunCSIRInstr =
false;
1355 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1358 Conf.ProfileRemapping = std::move(ProfileRemapping);
1359 Conf.DebugPassManager = CGOpts.DebugPassManager;
1360 Conf.VerifyEach = CGOpts.VerifyEach;
1361 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1362 Conf.RemarksFilename = CGOpts.OptRecordFile;
1363 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1364 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1365 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1366 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1369 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1374 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1375 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1380 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1381 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1392 finalizeLLVMOptimizationRemarks(M->getContext());
1394 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1395 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1396 nullptr, Conf.CodeGenOnly,
1397 nullptr, CGOpts.CmdArgs)) {
1398 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1399 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1405 StringRef TDesc, llvm::Module *M,
1408 std::unique_ptr<raw_pwrite_stream> OS,
1410 llvm::TimeTraceScope TimeScope(
"Backend");
1413 std::unique_ptr<llvm::Module> EmptyModule;
1418 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1419 if (
Error E = llvm::getModuleSummaryIndexForFile(
1422 .moveInto(CombinedIndex)) {
1423 logAllUnhandledErrors(std::move(E), errs(),
1424 "Error loading index file '" +
1432 if (CombinedIndex) {
1433 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1445 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1446 EmptyModule->setTargetTriple(M->getTargetTriple());
1447 M = EmptyModule.get();
1451 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1452 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1457 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1458 if (DLDesc != TDesc) {
1461 "expected target description '%1'");
1462 Diags.
Report(DiagID) << DLDesc << TDesc;
1470 llvm::MemoryBufferRef Buf) {
1473 llvm::embedBitcodeInModule(
1485 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1486 VFS.getBufferForFile(OffloadObject);
1487 if (ObjectOrErr.getError()) {
1489 "could not open '%0' for embedding");
1490 Diags.
Report(DiagID) << OffloadObject;
1494 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1495 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.
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.