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/Frontend/Driver/CodeGenOptions.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DebugInfo.h"
31#include "llvm/IR/LegacyPassManager.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/ModuleSummaryIndex.h"
34#include "llvm/IR/PassManager.h"
35#include "llvm/IR/Verifier.h"
36#include "llvm/IRPrinter/IRPrintingPasses.h"
37#include "llvm/LTO/LTOBackend.h"
38#include "llvm/MC/TargetRegistry.h"
39#include "llvm/Object/OffloadBinary.h"
40#include "llvm/Passes/PassBuilder.h"
41#include "llvm/Passes/PassPlugin.h"
42#include "llvm/Passes/StandardInstrumentations.h"
43#include "llvm/ProfileData/InstrProfCorrelator.h"
44#include "llvm/Support/BuryPointer.h"
45#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/MemoryBuffer.h"
47#include "llvm/Support/PrettyStackTrace.h"
48#include "llvm/Support/Program.h"
49#include "llvm/Support/TimeProfiler.h"
50#include "llvm/Support/Timer.h"
51#include "llvm/Support/ToolOutputFile.h"
52#include "llvm/Support/VirtualFileSystem.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Target/TargetMachine.h"
55#include "llvm/Target/TargetOptions.h"
56#include "llvm/TargetParser/SubtargetFeature.h"
57#include "llvm/TargetParser/Triple.h"
58#include "llvm/Transforms/HipStdPar/HipStdPar.h"
59#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
60#include "llvm/Transforms/IPO/LowerTypeTests.h"
61#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
62#include "llvm/Transforms/InstCombine/InstCombine.h"
63#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
64#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
65#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
66#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
67#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
68#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
69#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
70#include "llvm/Transforms/Instrumentation/KCFI.h"
71#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
72#include "llvm/Transforms/Instrumentation/MemProfiler.h"
73#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
74#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
75#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
76#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
77#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
78#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
79#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
80#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
81#include "llvm/Transforms/ObjCARC.h"
82#include "llvm/Transforms/Scalar/EarlyCSE.h"
83#include "llvm/Transforms/Scalar/GVN.h"
84#include "llvm/Transforms/Scalar/JumpThreading.h"
85#include "llvm/Transforms/Utils/Debugify.h"
86#include "llvm/Transforms/Utils/ModuleUtils.h"
92#define HANDLE_EXTENSION(Ext) \
93 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
94#include "llvm/Support/Extension.def"
101 "sanitizer-early-opt-ep", cl::Optional,
102 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
107 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
109 "Function attribute to apply to cold functions as determined by PGO"),
110 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
111 "Default (no attribute)"),
112 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
113 "Mark cold functions with optsize."),
114 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
115 "Mark cold functions with minsize."),
116 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
117 "Mark cold functions with optnone.")));
125std::string getDefaultProfileGenName() {
127 ?
"default_%m.proflite"
128 :
"default_%m.profraw";
131class EmitAssemblyHelper {
137 llvm::Module *TheModule;
140 Timer CodeGenerationTime;
142 std::unique_ptr<raw_pwrite_stream> OS;
146 TargetIRAnalysis getTargetIRAnalysis()
const {
148 return TM->getTargetIRAnalysis();
150 return TargetIRAnalysis();
161 void CreateTargetMachine(
bool MustCreateTM);
166 bool AddEmitPasses(legacy::PassManager &CodeGenPasses,
BackendAction Action,
167 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
169 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef
Path) {
171 auto F = std::make_unique<llvm::ToolOutputFile>(
Path, EC,
172 llvm::sys::fs::OF_None);
174 Diags.
Report(diag::err_fe_unable_to_open_output) <<
Path << EC.message();
180 void RunOptimizationPipeline(
181 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
182 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS,
BackendConsumer *BC);
184 std::unique_ptr<raw_pwrite_stream> &OS,
185 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
192 bool shouldEmitRegularLTOSummary()
const {
193 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
194 TargetTriple.getVendor() != llvm::Triple::Apple;
200 bool shouldEmitUnifiedLTOModueFlag()
const {
201 return CodeGenOpts.UnifiedLTO &&
202 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
212 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
213 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
VFS(
std::move(
VFS)),
214 CodeGenerationTime(
"codegen",
"Code Generation Time"),
215 TargetTriple(TheModule->getTargetTriple()) {}
217 ~EmitAssemblyHelper() {
218 if (CodeGenOpts.DisableFree)
219 BuryPointer(std::move(TM));
222 std::unique_ptr<TargetMachine> TM;
230static SanitizerCoverageOptions
232 SanitizerCoverageOptions Opts;
234 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
235 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
236 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
237 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
238 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
239 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
240 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
241 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
242 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
243 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
244 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
245 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
246 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
247 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
248 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
249 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
250 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
254static SanitizerBinaryMetadataOptions
256 SanitizerBinaryMetadataOptions Opts;
257 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
258 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
259 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
268 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
270 switch (
T.getObjectFormat()) {
275 return !CGOpts.DisableIntegratedAS;
277 llvm::report_fatal_error(
"ASan not implemented for GOFF");
279 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
281 case Triple::DXContainer:
283 case Triple::UnknownObjectFormat:
289static std::optional<llvm::CodeModel::Model>
291 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
292 .Case(
"tiny", llvm::CodeModel::Tiny)
293 .Case(
"small", llvm::CodeModel::Small)
294 .Case(
"kernel", llvm::CodeModel::Kernel)
295 .Case(
"medium", llvm::CodeModel::Medium)
296 .Case(
"large", llvm::CodeModel::Large)
297 .Case(
"default", ~1u)
299 assert(CodeModel != ~0u &&
"invalid code model!");
300 if (CodeModel == ~1u)
302 return static_cast<llvm::CodeModel::Model
>(CodeModel);
307 return CodeGenFileType::ObjectFile;
309 return CodeGenFileType::Null;
312 return CodeGenFileType::AssemblyFile;
322 StringRef MainFilename) {
324 return std::string{};
326 std::string FlatCmdLine;
327 raw_string_ostream OS(FlatCmdLine);
328 bool PrintedOneArg =
false;
329 if (!StringRef(Args[0]).
contains(
"-cc1")) {
330 llvm::sys::printArg(OS,
"-cc1",
true);
331 PrintedOneArg =
true;
333 for (
unsigned i = 0; i < Args.size(); i++) {
334 StringRef Arg = Args[i];
337 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
341 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
344 if (Arg.starts_with(
"-fmessage-length"))
348 llvm::sys::printArg(OS, Arg,
true);
349 PrintedOneArg =
true;
355 llvm::TargetOptions &Options,
360 switch (LangOpts.getThreadModel()) {
361 case LangOptions::ThreadModelKind::POSIX:
362 Options.ThreadModel = llvm::ThreadModel::POSIX;
364 case LangOptions::ThreadModelKind::Single:
365 Options.ThreadModel = llvm::ThreadModel::Single;
370 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
372 "Invalid Floating Point ABI!");
373 Options.FloatABIType =
374 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
375 .Case(
"soft", llvm::FloatABI::Soft)
376 .Case(
"softfp", llvm::FloatABI::Soft)
377 .Case(
"hard", llvm::FloatABI::Hard)
378 .Default(llvm::FloatABI::Default);
381 switch (LangOpts.getDefaultFPContractMode()) {
382 case LangOptions::FPM_Off:
385 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
387 case LangOptions::FPM_On:
388 case LangOptions::FPM_FastHonorPragmas:
389 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
391 case LangOptions::FPM_Fast:
392 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
396 Options.BinutilsVersion =
397 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
398 Options.UseInitArray = CodeGenOpts.UseInitArray;
399 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
405 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
407 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
409 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
411 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
413 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
414 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
415 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
416 Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
417 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
418 (LangOpts.getDefaultFPContractMode() ==
419 LangOptions::FPModeKind::FPM_Fast ||
420 LangOpts.getDefaultFPContractMode() ==
421 LangOptions::FPModeKind::FPM_FastHonorPragmas);
422 Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
424 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
426 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
427 .Case(
"all", llvm::BasicBlockSection::All)
428 .StartsWith(
"list=", llvm::BasicBlockSection::List)
429 .Case(
"none", llvm::BasicBlockSection::None)
430 .Default(llvm::BasicBlockSection::None);
432 if (Options.BBSections == llvm::BasicBlockSection::List) {
433 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
434 MemoryBuffer::getFile(CodeGenOpts.
BBSections.substr(5));
436 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
437 << MBOrErr.getError().message();
440 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
443 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
444 Options.FunctionSections = CodeGenOpts.FunctionSections;
445 Options.DataSections = CodeGenOpts.DataSections;
446 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
447 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
448 Options.UniqueBasicBlockSectionNames =
449 CodeGenOpts.UniqueBasicBlockSectionNames;
450 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
451 Options.TLSSize = CodeGenOpts.TLSSize;
452 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
453 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
454 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
455 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
457 Options.EmitAddrsig = CodeGenOpts.Addrsig;
458 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
459 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
460 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
461 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
462 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
463 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
465 Options.Hotpatch = CodeGenOpts.HotPatch;
466 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
467 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
469 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
470 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
471 Options.SwiftAsyncFramePointer =
472 SwiftAsyncFramePointerMode::DeploymentBased;
475 case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
476 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
479 case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
480 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
485 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
486 Options.MCOptions.EmitCompactUnwindNonCanonical =
487 CodeGenOpts.EmitCompactUnwindNonCanonical;
488 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
489 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
490 Options.MCOptions.MCUseDwarfDirectory =
491 CodeGenOpts.NoDwarfDirectoryAsm
492 ? llvm::MCTargetOptions::DisableDwarfDirectory
493 : llvm::MCTargetOptions::EnableDwarfDirectory;
494 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
495 Options.MCOptions.MCIncrementalLinkerCompatible =
496 CodeGenOpts.IncrementalLinkerCompatible;
497 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
498 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
499 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
500 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
501 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
502 Options.MCOptions.Crel = CodeGenOpts.Crel;
503 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
504 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
505 Options.MCOptions.CompressDebugSections =
506 CodeGenOpts.getCompressDebugSections();
507 if (CodeGenOpts.OutputAsmVariant != 3)
508 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
509 Options.MCOptions.ABIName = TargetOpts.
ABI;
511 if (!Entry.IsFramework &&
512 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
513 Entry.Group == frontend::IncludeDirGroup::Angled ||
514 Entry.Group == frontend::IncludeDirGroup::System))
515 Options.MCOptions.IASSearchPaths.push_back(
516 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.
Sysroot + Entry.Path);
517 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
521 Options.MCOptions.PPCUseFullRegisterNames =
522 CodeGenOpts.PPCUseFullRegisterNames;
523 Options.MisExpect = CodeGenOpts.MisExpect;
528static std::optional<GCOVOptions>
539 Options.NoRedZone = CodeGenOpts.DisableRedZone;
542 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
546static std::optional<InstrProfOptions>
551 InstrProfOptions Options;
552 Options.NoRedZone = CodeGenOpts.DisableRedZone;
554 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
560 BackendArgs.push_back(
"clang");
562 BackendArgs.push_back(
"-debug-pass");
563 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
566 BackendArgs.push_back(
"-limit-float-precision");
572 if (BackendArgs.size() == 1)
574 BackendArgs.push_back(
nullptr);
578 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
582void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
585 std::string Triple = TheModule->getTargetTriple();
586 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
589 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
593 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
594 std::string FeaturesStr =
597 std::optional<CodeGenOptLevel> OptLevelOrNone =
598 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
599 assert(OptLevelOrNone &&
"Invalid optimization level!");
600 CodeGenOptLevel OptLevel = *OptLevelOrNone;
602 llvm::TargetOptions Options;
606 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
607 Options, RM, CM, OptLevel));
611bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
613 raw_pwrite_stream &OS,
614 raw_pwrite_stream *DwoOS) {
616 std::unique_ptr<TargetLibraryInfoImpl> TLII(
617 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
618 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
624 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
625 !CodeGenOpts.VerifyModule)) {
626 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
634 switch (Opts.OptimizationLevel) {
636 llvm_unreachable(
"Invalid optimization level!");
639 return OptimizationLevel::O0;
642 return OptimizationLevel::O1;
645 switch (Opts.OptimizeSize) {
647 llvm_unreachable(
"Invalid optimization level for size!");
650 return OptimizationLevel::O2;
653 return OptimizationLevel::Os;
656 return OptimizationLevel::Oz;
660 return OptimizationLevel::O3;
667 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
668 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
672 PB.registerOptimizerLastEPCallback(
673 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
674 if (Level == OptimizationLevel::O0 &&
676 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
681 PB.registerPeepholeEPCallback(
682 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
683 if (Level != OptimizationLevel::O0 &&
685 FPM.addPass(KCFIPass());
692 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
693 ThinOrFullLTOPhase) {
696 MPM.addPass(SanitizerCoveragePass(
702 MPM.addPass(SanitizerBinaryMetadataPass(
707 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
709 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
712 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
713 CodeGenOpts.SanitizeMemoryParamRetval);
714 MPM.addPass(MemorySanitizerPass(options));
715 if (Level != OptimizationLevel::O0) {
720 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
721 FunctionPassManager FPM;
722 FPM.addPass(EarlyCSEPass(
true ));
723 FPM.addPass(InstCombinePass());
724 FPM.addPass(JumpThreadingPass());
725 FPM.addPass(GVNPass());
726 FPM.addPass(InstCombinePass());
727 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
731 MSanPass(SanitizerKind::Memory,
false);
732 MSanPass(SanitizerKind::KernelMemory,
true);
734 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
735 MPM.addPass(ModuleThreadSanitizerPass());
736 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
740 MPM.addPass(ModuleTypeSanitizerPass());
741 MPM.addPass(createModuleToFunctionPassAdaptor(TypeSanitizerPass()));
744 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
745 MPM.addPass(NumericalStabilitySanitizerPass());
747 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
748 MPM.addPass(RealtimeSanitizerPass());
750 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
753 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
754 llvm::AsanDtorKind DestructorKind =
755 CodeGenOpts.getSanitizeAddressDtor();
756 AddressSanitizerOptions Opts;
757 Opts.CompileKernel = CompileKernel;
759 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
760 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
761 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
765 ASanPass(SanitizerKind::Address,
false);
766 ASanPass(SanitizerKind::KernelAddress,
true);
768 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
771 MPM.addPass(HWAddressSanitizerPass(
772 {CompileKernel, Recover,
773 CodeGenOpts.OptimizationLevel == 0}));
776 HWASanPass(SanitizerKind::HWAddress,
false);
777 HWASanPass(SanitizerKind::KernelHWAddress,
true);
779 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
784 PB.registerOptimizerEarlyEPCallback(
785 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
786 ThinOrFullLTOPhase Phase) {
787 ModulePassManager NewMPM;
788 SanitizersCallback(NewMPM, Level, Phase);
789 if (!NewMPM.isEmpty()) {
791 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
792 MPM.addPass(std::move(NewMPM));
797 PB.registerOptimizerLastEPCallback(SanitizersCallback);
800 if (LowerAllowCheckPass::IsRequested()) {
802 PB.registerOptimizerEarlyEPCallback([](ModulePassManager &MPM,
803 OptimizationLevel Level,
804 ThinOrFullLTOPhase Phase) {
805 MPM.addPass(createModuleToFunctionPassAdaptor(LowerAllowCheckPass()));
810void EmitAssemblyHelper::RunOptimizationPipeline(
811 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
812 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS,
BackendConsumer *BC) {
813 std::optional<PGOOptions> PGOOpt;
822 CodeGenOpts.DebugInfoForProfiling,
823 false, CodeGenOpts.AtomicProfileUpdate);
827 : PGOOptions::NoCSAction;
832 CodeGenOpts.DebugInfoForProfiling);
839 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
843 PGOOptions::NoAction, PGOOptions::NoCSAction,
845 else if (CodeGenOpts.PseudoProbeForProfiling)
848 PGOOptions(
"",
"",
"",
"",
nullptr,
849 PGOOptions::NoAction, PGOOptions::NoCSAction,
851 else if (CodeGenOpts.DebugInfoForProfiling)
853 PGOOpt = PGOOptions(
"",
"",
"",
"",
nullptr,
854 PGOOptions::NoAction, PGOOptions::NoCSAction,
860 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
863 assert(PGOOpt->Action != PGOOptions::IRInstr &&
864 PGOOpt->Action != PGOOptions::SampleUse &&
865 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
868 ? getDefaultProfileGenName()
869 : CodeGenOpts.InstrProfileOutput;
870 PGOOpt->CSAction = PGOOptions::CSIRInstr;
872 PGOOpt = PGOOptions(
"",
874 ? getDefaultProfileGenName()
877 PGOOptions::NoAction, PGOOptions::CSIRInstr,
881 TM->setPGOOption(PGOOpt);
883 PipelineTuningOptions PTO;
884 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
887 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
888 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
889 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
890 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
893 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
894 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
896 LoopAnalysisManager LAM;
897 FunctionAnalysisManager FAM;
898 CGSCCAnalysisManager CGAM;
899 ModuleAnalysisManager MAM;
901 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
902 PassInstrumentationCallbacks PIC;
903 PrintPassOptions PrintPassOpts;
904 PrintPassOpts.Indent = DebugPassStructure;
905 PrintPassOpts.SkipAnalyses = DebugPassStructure;
906 StandardInstrumentations SI(
907 TheModule->getContext(),
908 (CodeGenOpts.DebugPassManager || DebugPassStructure),
909 CodeGenOpts.VerifyEach, PrintPassOpts);
910 SI.registerCallbacks(PIC, &MAM);
911 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
914 switch (CodeGenOpts.getAssignmentTrackingMode()) {
915 case CodeGenOptions::AssignmentTrackingOpts::Forced:
916 PB.registerPipelineStartEPCallback(
917 [&](ModulePassManager &MPM, OptimizationLevel Level) {
918 MPM.addPass(AssignmentTrackingPass());
921 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
924 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
925 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
926 PB.registerPipelineStartEPCallback(
927 [&](ModulePassManager &MPM, OptimizationLevel Level) {
929 if (Level != OptimizationLevel::O0)
930 MPM.addPass(AssignmentTrackingPass());
934 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
939 DebugifyEachInstrumentation Debugify;
940 DebugInfoPerPass DebugInfoBeforePass;
941 if (CodeGenOpts.EnableDIPreservationVerify) {
942 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
943 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
946 Debugify.setOrigDIVerifyBugsReportFilePath(
948 Debugify.registerCallbacks(PIC, MAM);
952 auto PassPlugin = PassPlugin::Load(PluginFN);
954 PassPlugin->registerPassBuilderCallbacks(PB);
956 Diags.
Report(diag::err_fe_unable_to_load_plugin)
957 << PluginFN <<
toString(PassPlugin.takeError());
962#define HANDLE_EXTENSION(Ext) \
963 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
964#include "llvm/Support/Extension.def"
968 std::unique_ptr<TargetLibraryInfoImpl> TLII(
969 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
970 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
973 PB.registerModuleAnalyses(MAM);
974 PB.registerCGSCCAnalyses(CGAM);
975 PB.registerFunctionAnalyses(FAM);
976 PB.registerLoopAnalyses(LAM);
977 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
979 ModulePassManager MPM;
981 if (CodeGenOpts.VerifyModule)
982 MPM.addPass(VerifierPass());
984 if (!CodeGenOpts.DisableLLVMPasses) {
989 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
990 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
992 if (LangOpts.ObjCAutoRefCount) {
993 PB.registerPipelineStartEPCallback(
994 [](ModulePassManager &MPM, OptimizationLevel Level) {
995 if (Level != OptimizationLevel::O0)
997 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
999 PB.registerPipelineEarlySimplificationEPCallback(
1000 [](ModulePassManager &MPM, OptimizationLevel Level,
1001 ThinOrFullLTOPhase) {
1002 if (Level != OptimizationLevel::O0)
1003 MPM.addPass(ObjCARCAPElimPass());
1005 PB.registerScalarOptimizerLateEPCallback(
1006 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1007 if (Level != OptimizationLevel::O0)
1008 FPM.addPass(ObjCARCOptPass());
1018 if (IsThinLTOPostLink)
1019 PB.registerPipelineStartEPCallback(
1020 [](ModulePassManager &MPM, OptimizationLevel Level) {
1021 MPM.addPass(LowerTypeTestsPass(
1024 lowertypetests::DropTestKind::Assume));
1029 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1030 PB.registerScalarOptimizerLateEPCallback(
1031 [
this](FunctionPassManager &FPM, OptimizationLevel Level) {
1032 BoundsCheckingPass::ReportingMode Mode;
1034 SanitizerKind::LocalBounds);
1037 Mode = BoundsCheckingPass::ReportingMode::Trap;
1038 }
else if (CodeGenOpts.SanitizeMinimalRuntime) {
1039 Mode = CodeGenOpts.SanitizeRecover.has(SanitizerKind::LocalBounds)
1040 ? BoundsCheckingPass::ReportingMode::MinRuntime
1041 : BoundsCheckingPass::ReportingMode::MinRuntimeAbort;
1043 Mode = CodeGenOpts.SanitizeRecover.has(SanitizerKind::LocalBounds)
1044 ? BoundsCheckingPass::ReportingMode::FullRuntime
1045 : BoundsCheckingPass::ReportingMode::FullRuntimeAbort;
1047 BoundsCheckingPass::BoundsCheckingOptions Options(Mode, Merge);
1048 FPM.addPass(BoundsCheckingPass(Options));
1053 if (!IsThinLTOPostLink) {
1058 if (std::optional<GCOVOptions> Options =
1060 PB.registerPipelineStartEPCallback(
1061 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1062 MPM.addPass(GCOVProfilerPass(*Options));
1064 if (std::optional<InstrProfOptions> Options =
1066 PB.registerPipelineStartEPCallback(
1067 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1068 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1074 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1075 OptimizationLevel Level,
1076 ThinOrFullLTOPhase) {
1077 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1078 MPM.addPass(ModuleMemProfilerPass());
1082 if (CodeGenOpts.FatLTO) {
1083 MPM.addPass(PB.buildFatLTODefaultPipeline(
1084 Level, PrepareForThinLTO,
1085 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1086 }
else if (PrepareForThinLTO) {
1087 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1088 }
else if (PrepareForLTO) {
1089 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1091 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1096 if (CodeGenOpts.LinkBitcodePostopt)
1105 MPM.addPass(VerifierPass());
1108 CodeGenOpts.FatLTO) {
1109 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1110 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1111 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1112 CodeGenOpts.EnableSplitLTOUnit);
1119 MPM.addPass(ThinLTOBitcodeWriterPass(
1120 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1122 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1128 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1129 if (EmitLTOSummary) {
1130 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1131 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1132 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1133 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1137 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1140 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1145 if (shouldEmitUnifiedLTOModueFlag())
1146 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1154 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1155 auto PassName = PIC.getPassNameForClassName(ClassName);
1156 return PassName.empty() ? ClassName : PassName;
1162 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1163 LangOpts.HIPStdParInterposeAlloc)
1164 MPM.addPass(HipStdParAllocationInterpositionPass());
1168 PrettyStackTraceString CrashInfo(
"Optimizer");
1169 llvm::TimeTraceScope TimeScope(
"Optimizer");
1170 MPM.run(*TheModule, MAM);
1174void EmitAssemblyHelper::RunCodegenPipeline(
1175 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1176 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1180 legacy::PassManager CodeGenPasses;
1188 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1194 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1195 DwoOS ? &DwoOS->os() :
nullptr))
1211 PrettyStackTraceString CrashInfo(
"Code generation");
1212 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1213 CodeGenPasses.run(*TheModule);
1218 std::unique_ptr<raw_pwrite_stream> OS,
1220 TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime :
nullptr);
1224 CreateTargetMachine(RequiresCodeGen);
1226 if (RequiresCodeGen && !TM)
1229 TheModule->setDataLayout(TM->createDataLayout());
1232 cl::PrintOptionValues();
1234 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1235 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1236 RunCodegenPipeline(Action, OS, DwoOS);
1248 const LangOptions &LOpts, std::unique_ptr<raw_pwrite_stream> OS,
1249 std::string SampleProfile, std::string ProfileRemapping,
1251 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1252 ModuleToDefinedGVSummaries;
1253 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1260 FunctionImporter::ImportIDTable ImportIDs;
1261 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1262 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1265 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1266 return std::make_unique<CachedFileStream>(std::move(OS),
1273 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1274 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1279 Conf.CPU = TOpts.
CPU;
1283 std::optional<CodeGenOptLevel> OptLevelOrNone =
1284 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1285 assert(OptLevelOrNone &&
"Invalid optimization level!");
1286 Conf.CGOptLevel = *OptLevelOrNone;
1287 Conf.OptLevel = CGOpts.OptimizationLevel;
1289 Conf.SampleProfile = std::move(SampleProfile);
1290 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1293 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1294 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1295 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1298 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1302 Conf.RunCSIRInstr =
true;
1305 Conf.RunCSIRInstr =
false;
1309 Conf.ProfileRemapping = std::move(ProfileRemapping);
1310 Conf.DebugPassManager = CGOpts.DebugPassManager;
1311 Conf.VerifyEach = CGOpts.VerifyEach;
1312 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1320 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1325 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1326 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1331 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1332 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1341 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1342 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1343 nullptr, Conf.CodeGenOnly,
1345 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1346 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1354 const LangOptions &LOpts, StringRef TDesc, llvm::Module *M,
1358 llvm::TimeTraceScope TimeScope(
"Backend");
1360 std::unique_ptr<llvm::Module> EmptyModule;
1365 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1366 if (Error
E = llvm::getModuleSummaryIndexForFile(
1369 .moveInto(CombinedIndex)) {
1370 logAllUnhandledErrors(std::move(
E), errs(),
1371 "Error loading index file '" +
1379 if (CombinedIndex) {
1380 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1392 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1393 EmptyModule->setTargetTriple(M->getTargetTriple());
1394 M = EmptyModule.get();
1398 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M, VFS);
1399 AsmHelper.EmitAssembly(Action, std::move(OS), BC);
1404 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1405 if (DLDesc != TDesc) {
1408 "expected target description '%1'");
1409 Diags.
Report(DiagID) << DLDesc << TDesc;
1417 llvm::MemoryBufferRef Buf) {
1420 llvm::embedBitcodeInModule(
1432 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1433 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1434 if (ObjectOrErr.getError()) {
1436 "could not open '%0' for embedding");
1437 Diags.
Report(DiagID) << OffloadObject;
1441 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1442 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 SanitizerBinaryMetadataOptions getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts)
static std::optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool initTargetOptions(DiagnosticsEngine &Diags, llvm::TargetOptions &Options, const CodeGenOptions &CodeGenOpts, const clang::TargetOptions &TargetOpts, const LangOptions &LangOpts, const HeaderSearchOptions &HSOpts)
static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts, PassBuilder &PB)
static void runThinLTOBackend(DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, llvm::Module *M, const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts, const LangOptions &LOpts, std::unique_ptr< raw_pwrite_stream > OS, std::string SampleProfile, std::string ProfileRemapping, BackendAction Action)
static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts)
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts)
static std::optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
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.
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 OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
std::string BinutilsVersion
bool hasProfileIRUse() const
Check if IR level profile use is on.
char CoverageVersion[4]
The version string to put into coverage files.
std::string FloatABI
The ABI to use for passing floating point arguments.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
bool hasProfileCSIRInstr() const
Check if CS IR level profile instrumentation is on.
std::string DebugPass
Enable additional debugging information.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
uint64_t LargeDataThreshold
The code model-specific large data threshold to use (-mlarge-data-threshold).
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::function< void(llvm::PassBuilder &)> > PassBuilderCallbacks
List of pass builder callbacks.
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
std::string CodeModel
The code model to use (-mcmodel).
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::vector< std::string > PassPlugins
List of dynamic shared object files to be loaded as pass plugins.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::vector< std::string > SanitizeCoverageAllowlistFiles
Path to allowlist file specifying which objects (files, functions) should exclusively be instrumented...
std::string SaveTempsFilePrefix
Prefix to use for -save-temps output.
std::vector< std::string > SanitizeCoverageIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
bool hasSanitizeCoverage() const
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.
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
std::vector< std::string > CommandLineArgs
std::string MemoryProfileUsePath
Name of the profile file to use as input for -fmemory-profile-use.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
std::vector< std::string > OffloadObjects
List of filenames passed in using the -fembed-offload-object option.
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
std::string ObjectFilenameForDebug
Output filename used in the COFF debug information.
std::string SplitDwarfOutput
Output filename for the split debug info, not used in the skeleton CU.
std::string DIBugsReportFilePath
The file to use for dumping bug report by Debugify for original debug info.
Concrete class used by the front-end to report problems and issues.
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.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool hasWasmExceptions() const
bool hasSjLjExceptions() const
SanitizerSet Sanitize
Set of enabled sanitizers.
bool hasDWARFExceptions() const
bool hasSEHExceptions() const
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
Options for controlling the target.
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.
Create and return a pass that links in Moduels from a provided BackendConsumer to a given primary Mod...
@ EmitAssembly
Emit a .s file.
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ 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)
const FunctionProtoType * T
Diagnostic wrappers for TextAPI types for error reporting.
cl::opt< bool > PrintPipelinePasses
cl::opt< InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate
static cl::opt< PGOOptions::ColdFuncOpt > ClPGOColdFuncAttr("pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden, cl::desc("Function attribute to apply to cold functions as determined by PGO"), cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default", "Default (no attribute)"), clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize", "Mark cold functions with optsize."), clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize", "Mark cold functions with minsize."), clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone", "Mark cold functions with optnone.")))
static cl::opt< bool > ClSanitizeOnOptimizerEarlyEP("sanitizer-early-opt-ep", cl::Optional, cl::desc("Insert sanitizers on OptimizerEarlyEP."))
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.