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);
238 AllocTokenOptions Opts;
240 Opts.Extended = CGOpts.SanitizeAllocTokenExtended;
241 Opts.FastABI = CGOpts.SanitizeAllocTokenFastABI;
245static SanitizerCoverageOptions
247 SanitizerCoverageOptions Opts;
249 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
250 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
251 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
252 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
253 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
254 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
255 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
256 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
257 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
258 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
259 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
260 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
261 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
262 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
263 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
264 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
265 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
266 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
270static SanitizerBinaryMetadataOptions
272 SanitizerBinaryMetadataOptions Opts;
273 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
274 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
275 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
284 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
286 switch (
T.getObjectFormat()) {
291 return !CGOpts.DisableIntegratedAS;
293 llvm::report_fatal_error(
"ASan not implemented for GOFF");
295 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
297 case Triple::DXContainer:
299 case Triple::UnknownObjectFormat:
305static std::optional<llvm::CodeModel::Model>
307 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
308 .Case(
"tiny", llvm::CodeModel::Tiny)
309 .Case(
"small", llvm::CodeModel::Small)
310 .Case(
"kernel", llvm::CodeModel::Kernel)
311 .Case(
"medium", llvm::CodeModel::Medium)
312 .Case(
"large", llvm::CodeModel::Large)
313 .Cases(
"default",
"", ~1u)
315 assert(CodeModel != ~0u &&
"invalid code model!");
316 if (CodeModel == ~1u)
318 return static_cast<llvm::CodeModel::Model
>(CodeModel);
323 return CodeGenFileType::ObjectFile;
325 return CodeGenFileType::Null;
328 return CodeGenFileType::AssemblyFile;
338 StringRef MainFilename) {
340 return std::string{};
342 std::string FlatCmdLine;
343 raw_string_ostream OS(FlatCmdLine);
344 bool PrintedOneArg =
false;
345 if (!StringRef(Args[0]).
contains(
"-cc1")) {
346 llvm::sys::printArg(OS,
"-cc1",
true);
347 PrintedOneArg =
true;
349 for (
unsigned i = 0; i < Args.size(); i++) {
350 StringRef Arg = Args[i];
353 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
357 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
360 if (Arg.starts_with(
"-fmessage-length"))
364 llvm::sys::printArg(OS, Arg,
true);
365 PrintedOneArg =
true;
372 llvm::TargetOptions &Options) {
377 switch (LangOpts.getThreadModel()) {
379 Options.ThreadModel = llvm::ThreadModel::POSIX;
382 Options.ThreadModel = llvm::ThreadModel::Single;
387 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
389 "Invalid Floating Point ABI!");
390 Options.FloatABIType =
391 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
392 .Case(
"soft", llvm::FloatABI::Soft)
393 .Case(
"softfp", llvm::FloatABI::Soft)
394 .Case(
"hard", llvm::FloatABI::Hard)
395 .Default(llvm::FloatABI::Default);
398 switch (LangOpts.getDefaultFPContractMode()) {
402 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
406 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
409 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
413 Options.BinutilsVersion =
414 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
415 Options.UseInitArray = CodeGenOpts.UseInitArray;
416 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
422 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
424 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
426 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
428 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
430 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
431 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
432 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
434 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
436 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
437 .Case(
"all", llvm::BasicBlockSection::All)
438 .StartsWith(
"list=", llvm::BasicBlockSection::List)
439 .Case(
"none", llvm::BasicBlockSection::None)
440 .Default(llvm::BasicBlockSection::None);
442 if (Options.BBSections == llvm::BasicBlockSection::List) {
443 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
447 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
448 << MBOrErr.getError().message();
451 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
454 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
455 Options.FunctionSections = CodeGenOpts.FunctionSections;
456 Options.DataSections = CodeGenOpts.DataSections;
457 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
458 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
459 Options.UniqueBasicBlockSectionNames =
460 CodeGenOpts.UniqueBasicBlockSectionNames;
461 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
462 Options.TLSSize = CodeGenOpts.TLSSize;
463 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
464 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
465 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
466 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
468 Options.EmitAddrsig = CodeGenOpts.Addrsig;
469 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
470 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
471 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
472 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
473 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
474 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
475 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
477 Options.Hotpatch = CodeGenOpts.HotPatch;
478 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
479 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
481 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
483 Options.SwiftAsyncFramePointer =
484 SwiftAsyncFramePointerMode::DeploymentBased;
488 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
492 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
497 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
498 Options.MCOptions.EmitCompactUnwindNonCanonical =
499 CodeGenOpts.EmitCompactUnwindNonCanonical;
500 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
501 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
502 Options.MCOptions.MCUseDwarfDirectory =
503 CodeGenOpts.NoDwarfDirectoryAsm
504 ? llvm::MCTargetOptions::DisableDwarfDirectory
505 : llvm::MCTargetOptions::EnableDwarfDirectory;
506 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
507 Options.MCOptions.MCIncrementalLinkerCompatible =
508 CodeGenOpts.IncrementalLinkerCompatible;
509 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
510 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
511 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
512 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
513 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
514 Options.MCOptions.Crel = CodeGenOpts.Crel;
515 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
516 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
517 Options.MCOptions.CompressDebugSections =
518 CodeGenOpts.getCompressDebugSections();
519 if (CodeGenOpts.OutputAsmVariant != 3)
520 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
521 Options.MCOptions.ABIName = TargetOpts.
ABI;
522 for (
const auto &Entry : HSOpts.UserEntries)
523 if (!Entry.IsFramework &&
527 Options.MCOptions.IASSearchPaths.push_back(
528 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
529 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
533 Options.MCOptions.PPCUseFullRegisterNames =
534 CodeGenOpts.PPCUseFullRegisterNames;
535 Options.MisExpect = CodeGenOpts.MisExpect;
540static std::optional<GCOVOptions>
551 Options.NoRedZone = CodeGenOpts.DisableRedZone;
554 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
558static std::optional<InstrProfOptions>
563 InstrProfOptions Options;
564 Options.NoRedZone = CodeGenOpts.DisableRedZone;
568 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
573 vfs::FileSystem &VFS) {
575 BackendArgs.push_back(
"clang");
577 BackendArgs.push_back(
"-debug-pass");
578 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
581 BackendArgs.push_back(
"-limit-float-precision");
587 if (BackendArgs.size() == 1)
589 BackendArgs.push_back(
nullptr);
593 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
598void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
601 const llvm::Triple &Triple = TheModule->getTargetTriple();
602 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
605 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
609 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
610 std::string FeaturesStr =
613 std::optional<CodeGenOptLevel> OptLevelOrNone =
614 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
615 assert(OptLevelOrNone &&
"Invalid optimization level!");
616 CodeGenOptLevel OptLevel = *OptLevelOrNone;
618 llvm::TargetOptions Options;
621 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
622 Options, RM, CM, OptLevel));
627bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
629 raw_pwrite_stream &OS,
630 raw_pwrite_stream *DwoOS) {
632 std::unique_ptr<TargetLibraryInfoImpl> TLII(
633 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
634 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
640 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
641 !CodeGenOpts.VerifyModule)) {
642 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
650 switch (Opts.OptimizationLevel) {
652 llvm_unreachable(
"Invalid optimization level!");
655 return OptimizationLevel::O0;
658 return OptimizationLevel::O1;
661 switch (Opts.OptimizeSize) {
663 llvm_unreachable(
"Invalid optimization level for size!");
666 return OptimizationLevel::O2;
669 return OptimizationLevel::Os;
672 return OptimizationLevel::Oz;
676 return OptimizationLevel::O3;
683 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
684 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
688 PB.registerOptimizerLastEPCallback(
689 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
690 if (Level == OptimizationLevel::O0 &&
692 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
697 PB.registerPeepholeEPCallback(
698 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
699 if (Level != OptimizationLevel::O0 &&
701 FPM.addPass(KCFIPass());
708 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
709 ThinOrFullLTOPhase) {
712 MPM.addPass(SanitizerCoveragePass(
718 MPM.addPass(SanitizerBinaryMetadataPass(
723 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
725 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
728 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
729 CodeGenOpts.SanitizeMemoryParamRetval);
730 MPM.addPass(MemorySanitizerPass(options));
731 if (Level != OptimizationLevel::O0) {
736 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
737 FunctionPassManager FPM;
738 FPM.addPass(EarlyCSEPass(
true ));
739 FPM.addPass(InstCombinePass());
740 FPM.addPass(JumpThreadingPass());
741 FPM.addPass(GVNPass());
742 FPM.addPass(InstCombinePass());
743 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
747 MSanPass(SanitizerKind::Memory,
false);
748 MSanPass(SanitizerKind::KernelMemory,
true);
750 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
751 MPM.addPass(ModuleThreadSanitizerPass());
752 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
756 MPM.addPass(TypeSanitizerPass());
758 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
759 MPM.addPass(NumericalStabilitySanitizerPass());
761 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
762 MPM.addPass(RealtimeSanitizerPass());
764 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
767 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
768 llvm::AsanDtorKind DestructorKind =
769 CodeGenOpts.getSanitizeAddressDtor();
770 AddressSanitizerOptions Opts;
771 Opts.CompileKernel = CompileKernel;
773 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
774 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
775 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
779 ASanPass(SanitizerKind::Address,
false);
780 ASanPass(SanitizerKind::KernelAddress,
true);
782 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
785 MPM.addPass(HWAddressSanitizerPass(
786 {CompileKernel, Recover,
787 CodeGenOpts.OptimizationLevel == 0}));
790 HWASanPass(SanitizerKind::HWAddress,
false);
791 HWASanPass(SanitizerKind::KernelHWAddress,
true);
793 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
795 PB.getVirtualFileSystemPtr()));
798 if (LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
799 if (Level == OptimizationLevel::O0) {
803 MPM.addPass(InferFunctionAttrsPass());
809 PB.registerOptimizerEarlyEPCallback(
810 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
811 ThinOrFullLTOPhase Phase) {
812 ModulePassManager NewMPM;
813 SanitizersCallback(NewMPM, Level, Phase);
814 if (!NewMPM.isEmpty()) {
816 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
817 MPM.addPass(std::move(NewMPM));
822 PB.registerOptimizerLastEPCallback(SanitizersCallback);
828 uint64_t AllowRuntimeCheckSkipHotCutoff =
831 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
834 PB.registerOptimizerEarlyEPCallback(
835 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
836 ModulePassManager &MPM, OptimizationLevel Level,
837 ThinOrFullLTOPhase Phase) {
838 LowerAllowCheckPass::Options Opts;
840 if (ScaledCutoffs.has_value())
841 Opts.cutoffs = ScaledCutoffs.value();
842 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
844 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
849void EmitAssemblyHelper::RunOptimizationPipeline(
850 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
851 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
852 std::optional<PGOOptions> PGOOpt;
859 CodeGenOpts.DebugInfoForProfiling,
861 CodeGenOpts.AtomicProfileUpdate);
865 : PGOOptions::NoCSAction;
870 CodeGenOpts.DebugInfoForProfiling);
877 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
881 PGOOptions::NoAction, PGOOptions::NoCSAction,
883 else if (CodeGenOpts.PseudoProbeForProfiling)
885 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
887 CodeGenOpts.DebugInfoForProfiling,
true);
888 else if (CodeGenOpts.DebugInfoForProfiling)
890 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
896 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
899 assert(PGOOpt->Action != PGOOptions::IRInstr &&
900 PGOOpt->Action != PGOOptions::SampleUse &&
901 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
904 PGOOpt->CSAction = PGOOptions::CSIRInstr;
907 "", PGOOptions::NoAction,
909 CodeGenOpts.DebugInfoForProfiling);
912 TM->setPGOOption(PGOOpt);
914 PipelineTuningOptions PTO;
915 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
916 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
917 PTO.LoopFusion = CodeGenOpts.FuseLoops;
920 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
921 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
922 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
923 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
926 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
927 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
929 LoopAnalysisManager LAM;
930 FunctionAnalysisManager FAM;
931 CGSCCAnalysisManager CGAM;
932 ModuleAnalysisManager MAM;
934 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
935 PassInstrumentationCallbacks PIC;
936 PrintPassOptions PrintPassOpts;
937 PrintPassOpts.Indent = DebugPassStructure;
938 PrintPassOpts.SkipAnalyses = DebugPassStructure;
939 StandardInstrumentations SI(
940 TheModule->getContext(),
941 (CodeGenOpts.DebugPassManager || DebugPassStructure),
942 CodeGenOpts.VerifyEach, PrintPassOpts);
943 SI.registerCallbacks(PIC, &MAM);
947 switch (CodeGenOpts.getAssignmentTrackingMode()) {
948 case CodeGenOptions::AssignmentTrackingOpts::Forced:
949 PB.registerPipelineStartEPCallback(
950 [&](ModulePassManager &MPM, OptimizationLevel Level) {
951 MPM.addPass(AssignmentTrackingPass());
954 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
957 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
958 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
959 PB.registerPipelineStartEPCallback(
960 [&](ModulePassManager &MPM, OptimizationLevel Level) {
962 if (Level != OptimizationLevel::O0)
963 MPM.addPass(AssignmentTrackingPass());
967 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
972 DebugifyEachInstrumentation Debugify;
973 DebugInfoPerPass DebugInfoBeforePass;
974 if (CodeGenOpts.EnableDIPreservationVerify) {
975 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
976 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
979 Debugify.setOrigDIVerifyBugsReportFilePath(
981 Debugify.registerCallbacks(PIC, MAM);
983#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
990 if (!F.getSubprogram())
992 for (BasicBlock &BB : F)
993 for (Instruction &I : BB)
994 if (!I.getDebugLoc())
995 I.setDebugLoc(DebugLoc::getCompilerGenerated());
1001 auto PassPlugin = PassPlugin::Load(PluginFN);
1003 PassPlugin->registerPassBuilderCallbacks(PB);
1005 Diags.
Report(diag::err_fe_unable_to_load_plugin)
1006 << PluginFN <<
toString(PassPlugin.takeError());
1011#define HANDLE_EXTENSION(Ext) \
1012 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1013#include "llvm/Support/Extension.def"
1017 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1018 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1019 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1022 PB.registerModuleAnalyses(MAM);
1023 PB.registerCGSCCAnalyses(CGAM);
1024 PB.registerFunctionAnalyses(FAM);
1025 PB.registerLoopAnalyses(LAM);
1026 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1028 ModulePassManager MPM;
1030 if (CodeGenOpts.VerifyModule)
1031 MPM.addPass(VerifierPass());
1033 if (!CodeGenOpts.DisableLLVMPasses) {
1038 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1039 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1041 if (LangOpts.ObjCAutoRefCount) {
1042 PB.registerPipelineStartEPCallback(
1043 [](ModulePassManager &MPM, OptimizationLevel Level) {
1044 if (Level != OptimizationLevel::O0)
1046 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1048 PB.registerScalarOptimizerLateEPCallback(
1049 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1050 if (Level != OptimizationLevel::O0)
1051 FPM.addPass(ObjCARCOptPass());
1061 if (IsThinLTOPostLink)
1062 PB.registerPipelineStartEPCallback(
1063 [](ModulePassManager &MPM, OptimizationLevel Level) {
1064 MPM.addPass(LowerTypeTestsPass(
1067 lowertypetests::DropTestKind::Assume));
1072 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1073 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1074 OptimizationLevel Level) {
1075 BoundsCheckingPass::Options Options;
1078 static_assert(SanitizerKind::SO_LocalBounds <=
1079 std::numeric_limits<
1080 decltype(Options.GuardKind)::value_type>
::max(),
1081 "Update type of llvm.allow.ubsan.check to represent "
1082 "SanitizerKind::SO_LocalBounds.");
1083 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1090 CodeGenOpts.SanitizeMinimalRuntime),
1095 FPM.addPass(BoundsCheckingPass(Options));
1100 if (!IsThinLTOPostLink) {
1105 if (std::optional<GCOVOptions> Options =
1107 PB.registerPipelineStartEPCallback(
1108 [
this, Options](ModulePassManager &MPM, OptimizationLevel Level) {
1112 if (std::optional<InstrProfOptions> Options =
1114 PB.registerPipelineStartEPCallback(
1115 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1116 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1122 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1123 OptimizationLevel Level,
1124 ThinOrFullLTOPhase) {
1125 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1126 MPM.addPass(ModuleMemProfilerPass());
1130 if (CodeGenOpts.FatLTO) {
1131 MPM.addPass(PB.buildFatLTODefaultPipeline(
1132 Level, PrepareForThinLTO,
1133 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1134 }
else if (PrepareForThinLTO) {
1135 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1136 }
else if (PrepareForLTO) {
1137 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1139 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1144 if (CodeGenOpts.LinkBitcodePostopt)
1145 MPM.addPass(LinkInModulesPass(BC));
1147 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1148 LangOpts.HIPStdParInterposeAlloc)
1149 MPM.addPass(HipStdParAllocationInterpositionPass());
1157 MPM.addPass(VerifierPass());
1160 CodeGenOpts.FatLTO) {
1161 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1162 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1163 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1164 CodeGenOpts.EnableSplitLTOUnit);
1171 MPM.addPass(ThinLTOBitcodeWriterPass(
1172 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1174 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1180 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1181 if (EmitLTOSummary) {
1182 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1183 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1184 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1185 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1189 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1192 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1197 if (shouldEmitUnifiedLTOModueFlag() &&
1198 !TheModule->getModuleFlag(
"UnifiedLTO"))
1199 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1206 if (PrintPipelinePasses) {
1207 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1208 auto PassName = PIC.getPassNameForClassName(ClassName);
1209 return PassName.empty() ? ClassName : PassName;
1217 PrettyStackTraceString CrashInfo(
"Optimizer");
1218 llvm::TimeTraceScope TimeScope(
"Optimizer");
1224 MPM.run(*TheModule, MAM);
1230void EmitAssemblyHelper::RunCodegenPipeline(
1231 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1232 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1236 legacy::PassManager CodeGenPasses;
1244 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1250 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1251 DwoOS ? &DwoOS->os() :
nullptr))
1262 if (PrintPipelinePasses) {
1267 PrettyStackTraceString CrashInfo(
"Code generation");
1268 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1271 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1274 CodeGenPasses.run(*TheModule);
1281 std::unique_ptr<raw_pwrite_stream> OS,
1282 BackendConsumer *BC) {
1286 CreateTargetMachine(RequiresCodeGen);
1288 if (RequiresCodeGen && !TM)
1291 TheModule->setDataLayout(TM->createDataLayout());
1294 cl::PrintOptionValues();
1296 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1297 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1298 RunCodegenPipeline(Action, OS, DwoOS);
1308 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1309 std::string SampleProfile, std::string ProfileRemapping,
1314 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1315 ModuleToDefinedGVSummaries;
1316 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1323 FunctionImporter::ImportIDTable ImportIDs;
1324 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1325 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1328 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1329 return std::make_unique<CachedFileStream>(std::move(OS),
1330 CGOpts.ObjectFilenameForDebug);
1333 if (CGOpts.SaveTempsFilePrefix !=
"") {
1334 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1336 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1337 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1342 Conf.CPU = TOpts.CPU;
1344 Conf.MAttrs = TOpts.Features;
1345 Conf.RelocModel = CGOpts.RelocationModel;
1346 std::optional<CodeGenOptLevel> OptLevelOrNone =
1347 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1348 assert(OptLevelOrNone &&
"Invalid optimization level!");
1349 Conf.CGOptLevel = *OptLevelOrNone;
1350 Conf.OptLevel = CGOpts.OptimizationLevel;
1352 Conf.SampleProfile = std::move(SampleProfile);
1353 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1354 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1355 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1358 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1359 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1360 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1363 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1366 if (CGOpts.hasProfileCSIRInstr()) {
1367 Conf.RunCSIRInstr =
true;
1369 }
else if (CGOpts.hasProfileCSIRUse()) {
1370 Conf.RunCSIRInstr =
false;
1371 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1374 Conf.ProfileRemapping = std::move(ProfileRemapping);
1375 Conf.DebugPassManager = CGOpts.DebugPassManager;
1376 Conf.VerifyEach = CGOpts.VerifyEach;
1377 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1378 Conf.RemarksFilename = CGOpts.OptRecordFile;
1379 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1380 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1381 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1382 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1385 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1390 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1391 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1396 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1397 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1408 finalizeLLVMOptimizationRemarks(M->getContext());
1410 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1411 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1412 nullptr, Conf.CodeGenOnly,
1413 nullptr, CGOpts.CmdArgs)) {
1414 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1415 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1421 StringRef TDesc, llvm::Module *M,
1424 std::unique_ptr<raw_pwrite_stream> OS,
1426 llvm::TimeTraceScope TimeScope(
"Backend");
1429 std::unique_ptr<llvm::Module> EmptyModule;
1434 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1435 if (
Error E = llvm::getModuleSummaryIndexForFile(
1438 .moveInto(CombinedIndex)) {
1439 logAllUnhandledErrors(std::move(E), errs(),
1440 "Error loading index file '" +
1448 if (CombinedIndex) {
1449 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1461 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1462 EmptyModule->setTargetTriple(M->getTargetTriple());
1463 M = EmptyModule.get();
1467 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1468 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1473 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1474 if (DLDesc != TDesc) {
1477 "expected target description '%1'");
1478 Diags.
Report(DiagID) << DLDesc << TDesc;
1486 llvm::MemoryBufferRef Buf) {
1489 llvm::embedBitcodeInModule(
1501 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1502 VFS.getBufferForFile(OffloadObject);
1503 if (ObjectOrErr.getError()) {
1505 "could not open '%0' for embedding");
1506 Diags.
Report(DiagID) << OffloadObject;
1510 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1511 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 AllocTokenOptions getAllocTokenOptions(const CodeGenOptions &CGOpts)
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::optional< uint64_t > AllocTokenMax
Maximum number of allocation tokens (0 = no max), nullopt if none set (use pass default).
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.