19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/RuntimeLibcallInfo.h"
23#include "llvm/Analysis/TargetLibraryInfo.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/Bitcode/BitcodeReader.h"
26#include "llvm/Bitcode/BitcodeWriter.h"
27#include "llvm/Bitcode/BitcodeWriterPass.h"
28#include "llvm/CodeGen/TargetSubtargetInfo.h"
29#include "llvm/Config/llvm-config.h"
30#include "llvm/Frontend/Driver/CodeGenOptions.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DebugInfo.h"
33#include "llvm/IR/LLVMRemarkStreamer.h"
34#include "llvm/IR/LegacyPassManager.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/ModuleSummaryIndex.h"
37#include "llvm/IR/PassManager.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/IRPrinter/IRPrintingPasses.h"
40#include "llvm/LTO/LTOBackend.h"
41#include "llvm/MC/TargetRegistry.h"
42#include "llvm/Object/OffloadBinary.h"
43#include "llvm/Passes/PassBuilder.h"
44#include "llvm/Passes/StandardInstrumentations.h"
45#include "llvm/Plugins/PassPlugin.h"
46#include "llvm/ProfileData/InstrProfCorrelator.h"
47#include "llvm/Support/BuryPointer.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/IOSandbox.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/PrettyStackTrace.h"
53#include "llvm/Support/Program.h"
54#include "llvm/Support/TimeProfiler.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/ToolOutputFile.h"
57#include "llvm/Support/VirtualFileSystem.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/Target/TargetMachine.h"
60#include "llvm/Target/TargetOptions.h"
61#include "llvm/TargetParser/SubtargetFeature.h"
62#include "llvm/TargetParser/Triple.h"
63#include "llvm/Transforms/HipStdPar/HipStdPar.h"
64#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
65#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
66#include "llvm/Transforms/IPO/LowerTypeTests.h"
67#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
68#include "llvm/Transforms/InstCombine/InstCombine.h"
69#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
70#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
71#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
72#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
73#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
74#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
75#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
76#include "llvm/Transforms/Instrumentation/KCFI.h"
77#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
78#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
79#include "llvm/Transforms/Instrumentation/MemProfUse.h"
80#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
81#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
82#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
83#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
84#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
85#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
86#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
87#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
88#include "llvm/Transforms/ObjCARC.h"
89#include "llvm/Transforms/Scalar/EarlyCSE.h"
90#include "llvm/Transforms/Scalar/GVN.h"
91#include "llvm/Transforms/Scalar/JumpThreading.h"
92#include "llvm/Transforms/Utils/Debugify.h"
93#include "llvm/Transforms/Utils/ModuleUtils.h"
100#define HANDLE_EXTENSION(Ext) \
101 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
102#include "llvm/Support/Extension.def"
107 "sanitizer-early-opt-ep", cl::Optional,
108 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
113 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
115 "Function attribute to apply to cold functions as determined by PGO"),
116 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
117 "Default (no attribute)"),
118 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
119 "Mark cold functions with optsize."),
120 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
121 "Mark cold functions with minsize."),
122 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
123 "Mark cold functions with optnone.")));
125LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
135 ? llvm::driver::getDefaultProfileGenName()
137 if (CodeGenOpts.ContinuousProfileSync)
144class EmitAssemblyHelper {
145 CompilerInstance &CI;
146 DiagnosticsEngine &Diags;
147 const CodeGenOptions &CodeGenOpts;
148 const clang::TargetOptions &TargetOpts;
149 const LangOptions &LangOpts;
150 llvm::Module *TheModule;
151 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
153 std::unique_ptr<raw_pwrite_stream> OS;
157 TargetIRAnalysis getTargetIRAnalysis()
const {
159 return TM->getTargetIRAnalysis();
161 return TargetIRAnalysis();
172 void CreateTargetMachine(
bool MustCreateTM);
174 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
176 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
177 llvm::sys::fs::OF_None);
179 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
185 void RunOptimizationPipeline(
186 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
187 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
189 std::unique_ptr<raw_pwrite_stream> &OS,
190 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
197 bool shouldEmitRegularLTOSummary()
const {
198 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
199 TargetTriple.getVendor() != llvm::Triple::Apple;
205 bool shouldEmitUnifiedLTOModueFlag()
const {
206 return CodeGenOpts.UnifiedLTO &&
207 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
211 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
213 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
214 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
215 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
216 TheModule(M), VFS(std::move(VFS)),
217 TargetTriple(TheModule->getTargetTriple()) {}
219 ~EmitAssemblyHelper() {
220 if (CodeGenOpts.DisableFree)
221 BuryPointer(std::move(TM));
224 std::unique_ptr<TargetMachine> TM;
227 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
228 BackendConsumer *BC);
232static SanitizerCoverageOptions
234 SanitizerCoverageOptions Opts;
236 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
237 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
238 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
239 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
240 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
241 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
242 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
243 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
244 Opts.TracePCEntryExit = CGOpts.SanitizeCoverageTracePCEntryExit;
245 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
246 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
247 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
248 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
249 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
250 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
251 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
252 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
253 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
254 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
258static SanitizerBinaryMetadataOptions
260 SanitizerBinaryMetadataOptions Opts;
261 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
262 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
263 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
272 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
274 switch (T.getObjectFormat()) {
279 return !CGOpts.DisableIntegratedAS;
281 llvm::report_fatal_error(
"ASan not implemented for GOFF");
283 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
285 case Triple::DXContainer:
287 case Triple::UnknownObjectFormat:
293static std::optional<llvm::CodeModel::Model>
295 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
296 .Case(
"tiny", llvm::CodeModel::Tiny)
297 .Case(
"small", llvm::CodeModel::Small)
298 .Case(
"kernel", llvm::CodeModel::Kernel)
299 .Case(
"medium", llvm::CodeModel::Medium)
300 .Case(
"large", llvm::CodeModel::Large)
301 .Cases({
"default",
""}, ~1u)
303 assert(CodeModel != ~0u &&
"invalid code model!");
304 if (CodeModel == ~1u)
306 return static_cast<llvm::CodeModel::Model
>(CodeModel);
311 return CodeGenFileType::ObjectFile;
313 return CodeGenFileType::Null;
316 return CodeGenFileType::AssemblyFile;
326 StringRef MainFilename,
329 return std::string{};
331 std::string FlatCmdLine;
332 raw_string_ostream OS(FlatCmdLine);
333 bool PrintedOneArg =
false;
334 if (!StringRef(Args[0]).
contains(
"-cc1")) {
335 llvm::sys::printArg(OS,
"-cc1",
true);
336 PrintedOneArg =
true;
338 for (
unsigned i = 0; i < Args.size(); i++) {
339 StringRef Arg = Args[i];
342 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
346 if (Arg.starts_with(
"-object-file-name"))
354 if (Arg == MainFilename || llvm::is_contained(InputFiles, Arg))
357 if (Arg.starts_with(
"-fmessage-length"))
361 llvm::sys::printArg(OS, Arg,
true);
362 PrintedOneArg =
true;
369 llvm::TargetOptions &Options) {
374 switch (LangOpts.getThreadModel()) {
376 Options.ThreadModel = llvm::ThreadModel::POSIX;
379 Options.ThreadModel = llvm::ThreadModel::Single;
384 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
386 "Invalid Floating Point ABI!");
387 Options.FloatABIType =
388 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
389 .Case(
"soft", llvm::FloatABI::Soft)
390 .Case(
"softfp", llvm::FloatABI::Soft)
391 .Case(
"hard", llvm::FloatABI::Hard)
392 .Default(llvm::FloatABI::Default);
395 switch (LangOpts.getDefaultFPContractMode()) {
399 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
403 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
406 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
410 Options.BinutilsVersion =
411 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
412 Options.UseInitArray = CodeGenOpts.UseInitArray;
413 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
419 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
421 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
423 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
425 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
427 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
429 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
431 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
432 .Case(
"all", llvm::BasicBlockSection::All)
433 .StartsWith(
"list=", llvm::BasicBlockSection::List)
434 .Case(
"none", llvm::BasicBlockSection::None)
435 .Default(llvm::BasicBlockSection::None);
437 if (Options.BBSections == llvm::BasicBlockSection::List) {
438 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
442 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
443 << MBOrErr.getError().message();
446 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
449 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
450 Options.EnableStaticDataPartitioning =
451 CodeGenOpts.PartitionStaticDataSections;
452 Options.FunctionSections = CodeGenOpts.FunctionSections;
453 Options.DataSections = CodeGenOpts.DataSections;
454 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
455 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
456 Options.UniqueBasicBlockSectionNames =
457 CodeGenOpts.UniqueBasicBlockSectionNames;
458 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
459 Options.TLSSize = CodeGenOpts.TLSSize;
460 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
461 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
462 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
463 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
465 Options.EmitAddrsig = CodeGenOpts.Addrsig;
466 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
467 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
468 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
469 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
470 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
471 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
472 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
474 Options.Hotpatch = CodeGenOpts.HotPatch;
475 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
476 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
478 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
480 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
482 Options.SwiftAsyncFramePointer =
483 SwiftAsyncFramePointerMode::DeploymentBased;
487 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
491 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
496 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
497 Options.MCOptions.EmitCompactUnwindNonCanonical =
498 CodeGenOpts.EmitCompactUnwindNonCanonical;
499 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
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.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
516 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
517 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
518 Options.MCOptions.CompressDebugSections =
519 CodeGenOpts.getCompressDebugSections();
520 if (CodeGenOpts.OutputAsmVariant != 3)
521 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
522 Options.MCOptions.ABIName = TargetOpts.
ABI;
523 for (
const auto &Entry : HSOpts.UserEntries)
524 if (!Entry.IsFramework &&
528 Options.MCOptions.IASSearchPaths.push_back(
529 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
530 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
537 InputFiles.push_back(Input.getFile());
541 Options.MCOptions.PPCUseFullRegisterNames =
542 CodeGenOpts.PPCUseFullRegisterNames;
543 Options.MisExpect = CodeGenOpts.MisExpect;
548static std::optional<GCOVOptions>
559 Options.NoRedZone = CodeGenOpts.DisableRedZone;
562 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
566static std::optional<InstrProfOptions>
571 InstrProfOptions Options;
572 Options.NoRedZone = CodeGenOpts.DisableRedZone;
576 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
581 vfs::FileSystem &VFS) {
583 BackendArgs.push_back(
"clang");
585 BackendArgs.push_back(
"-debug-pass");
586 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
589 BackendArgs.push_back(
"-limit-float-precision");
596 if (BackendArgs.size() == 1)
598 BackendArgs.push_back(
nullptr);
602 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
607void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
610 const llvm::Triple &Triple = TheModule->getTargetTriple();
611 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
614 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
618 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
619 std::string FeaturesStr =
622 std::optional<CodeGenOptLevel> OptLevelOrNone =
623 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
624 assert(OptLevelOrNone &&
"Invalid optimization level!");
625 CodeGenOptLevel OptLevel = *OptLevelOrNone;
627 llvm::TargetOptions Options;
630 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
631 Options, RM, CM, OptLevel));
637 switch (Opts.OptimizationLevel) {
639 llvm_unreachable(
"Invalid optimization level!");
642 return OptimizationLevel::O0;
645 return OptimizationLevel::O1;
648 return OptimizationLevel::O2;
651 return OptimizationLevel::O3;
658 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
659 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
660 TargetTriple.isARM() || TargetTriple.isThumb())
664 PB.registerOptimizerLastEPCallback(
665 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
666 if (Level == OptimizationLevel::O0 &&
668 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
673 PB.registerPeepholeEPCallback(
674 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
675 if (Level != OptimizationLevel::O0 &&
677 FPM.addPass(KCFIPass());
684 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
685 ThinOrFullLTOPhase) {
689 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
695 MPM.addPass(SanitizerBinaryMetadataPass(
697 PB.getVirtualFileSystemPtr(),
701 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
703 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
706 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
707 CodeGenOpts.SanitizeMemoryParamRetval);
708 MPM.addPass(MemorySanitizerPass(
options));
709 if (Level != OptimizationLevel::O0) {
714 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
715 FunctionPassManager FPM;
716 FPM.addPass(EarlyCSEPass(
true ));
717 FPM.addPass(InstCombinePass());
718 FPM.addPass(JumpThreadingPass());
719 FPM.addPass(GVNPass());
720 FPM.addPass(InstCombinePass());
721 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
725 MSanPass(SanitizerKind::Memory,
false);
726 MSanPass(SanitizerKind::KernelMemory,
true);
728 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
729 MPM.addPass(ModuleThreadSanitizerPass());
730 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
734 MPM.addPass(TypeSanitizerPass());
736 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
737 MPM.addPass(NumericalStabilitySanitizerPass());
739 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
740 MPM.addPass(RealtimeSanitizerPass());
742 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
745 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
746 llvm::AsanDtorKind DestructorKind =
747 CodeGenOpts.getSanitizeAddressDtor();
748 AddressSanitizerOptions Opts;
749 Opts.CompileKernel = CompileKernel;
751 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
752 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
753 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
757 ASanPass(SanitizerKind::Address,
false);
758 ASanPass(SanitizerKind::KernelAddress,
true);
760 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
763 MPM.addPass(HWAddressSanitizerPass(
764 {CompileKernel, Recover,
765 CodeGenOpts.OptimizationLevel == 0}));
768 HWASanPass(SanitizerKind::HWAddress,
false);
769 HWASanPass(SanitizerKind::KernelHWAddress,
true);
771 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
773 PB.getVirtualFileSystemPtr()));
777 PB.registerOptimizerEarlyEPCallback(
778 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
779 ThinOrFullLTOPhase Phase) {
780 ModulePassManager NewMPM;
781 SanitizersCallback(NewMPM, Level, Phase);
782 if (!NewMPM.isEmpty()) {
784 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
785 MPM.addPass(std::move(NewMPM));
790 PB.registerOptimizerLastEPCallback(SanitizersCallback);
799 uint64_t AllowRuntimeCheckSkipHotCutoff =
804 SanitizerKind::Address | SanitizerKind::KernelAddress |
805 SanitizerKind::Thread | SanitizerKind::Memory |
806 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
807 SanitizerKind::KernelHWAddress);
810 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
812 LowerAllowSanitize) {
814 PB.registerOptimizerEarlyEPCallback(
815 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
816 ModulePassManager &MPM, OptimizationLevel Level,
817 ThinOrFullLTOPhase Phase) {
818 LowerAllowCheckPass::Options Opts;
820 if (ScaledCutoffs.has_value())
821 Opts.cutoffs = ScaledCutoffs.value();
822 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
824 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
829void EmitAssemblyHelper::RunOptimizationPipeline(
830 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
831 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
832 std::optional<PGOOptions> PGOOpt;
839 CodeGenOpts.DebugInfoForProfiling,
841 CodeGenOpts.AtomicProfileUpdate);
845 : PGOOptions::NoCSAction;
850 CodeGenOpts.DebugInfoForProfiling);
857 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
861 PGOOptions::NoAction, PGOOptions::NoCSAction,
863 else if (CodeGenOpts.PseudoProbeForProfiling)
865 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
867 CodeGenOpts.DebugInfoForProfiling,
true);
868 else if (CodeGenOpts.DebugInfoForProfiling)
870 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
876 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
879 assert(PGOOpt->Action != PGOOptions::IRInstr &&
880 PGOOpt->Action != PGOOptions::SampleUse &&
881 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
884 PGOOpt->CSAction = PGOOptions::CSIRInstr;
887 "", PGOOptions::NoAction,
889 CodeGenOpts.DebugInfoForProfiling);
892 TM->setPGOOption(PGOOpt);
894 PipelineTuningOptions PTO;
895 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
896 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
897 PTO.LoopFusion = CodeGenOpts.FuseLoops;
900 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
901 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
902 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
903 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
906 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
907 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
908 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
910 LoopAnalysisManager LAM;
911 FunctionAnalysisManager FAM;
912 CGSCCAnalysisManager CGAM;
913 ModuleAnalysisManager MAM;
915 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
916 PassInstrumentationCallbacks PIC;
917 PrintPassOptions PrintPassOpts;
918 PrintPassOpts.Indent = DebugPassStructure;
919 PrintPassOpts.SkipAnalyses = DebugPassStructure;
920 StandardInstrumentations SI(
921 TheModule->getContext(),
922 (CodeGenOpts.DebugPassManager || DebugPassStructure),
923 CodeGenOpts.VerifyEach, PrintPassOpts);
924 SI.registerCallbacks(PIC, &MAM);
928 switch (CodeGenOpts.getAssignmentTrackingMode()) {
929 case CodeGenOptions::AssignmentTrackingOpts::Forced:
930 PB.registerPipelineStartEPCallback(
931 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
932 MPM.addPass(AssignmentTrackingPass());
935 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
938 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
939 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
940 PB.registerPipelineStartEPCallback(
941 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
943 if (
Level != OptimizationLevel::O0)
944 MPM.addPass(AssignmentTrackingPass());
948 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
953 DebugifyEachInstrumentation Debugify;
954 DebugInfoPerPass DebugInfoBeforePass;
955 if (CodeGenOpts.EnableDIPreservationVerify) {
956 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
957 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
960 Debugify.setOrigDIVerifyBugsReportFilePath(
962 Debugify.registerCallbacks(PIC, MAM);
964#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
971 if (!F.getSubprogram())
973 for (BasicBlock &BB : F)
974 for (Instruction &I : BB)
975 if (!I.getDebugLoc())
976 I.setDebugLoc(DebugLoc::getCompilerGenerated());
981 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
982 Plugin->registerPassBuilderCallbacks(PB);
985#define HANDLE_EXTENSION(Ext) \
986 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
987#include "llvm/Support/Extension.def"
991 std::unique_ptr<TargetLibraryInfoImpl> TLII(
992 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
993 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
996 PB.registerModuleAnalyses(MAM);
997 PB.registerCGSCCAnalyses(CGAM);
998 PB.registerFunctionAnalyses(FAM);
999 PB.registerLoopAnalyses(LAM);
1000 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1002 ModulePassManager MPM;
1004 if (CodeGenOpts.VerifyModule)
1005 MPM.addPass(VerifierPass());
1007 if (!CodeGenOpts.DisableLLVMPasses) {
1012 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1013 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1015 if (LangOpts.ObjCAutoRefCount) {
1016 PB.registerPipelineStartEPCallback(
1017 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1018 if (
Level != OptimizationLevel::O0)
1020 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1022 PB.registerScalarOptimizerLateEPCallback(
1023 [](FunctionPassManager &FPM, OptimizationLevel
Level) {
1024 if (
Level != OptimizationLevel::O0)
1025 FPM.addPass(ObjCARCOptPass());
1035 if (IsThinLTOPostLink)
1036 PB.registerPipelineStartEPCallback(
1037 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1038 MPM.addPass(DropTypeTestsPass());
1043 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1044 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1045 OptimizationLevel
Level) {
1046 BoundsCheckingPass::Options Options;
1049 static_assert(SanitizerKind::SO_LocalBounds <=
1050 std::numeric_limits<
1051 decltype(Options.GuardKind)::value_type>
::max(),
1052 "Update type of llvm.allow.ubsan.check to represent "
1053 "SanitizerKind::SO_LocalBounds.");
1054 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1061 CodeGenOpts.SanitizeMinimalRuntime),
1065 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1068 FPM.addPass(BoundsCheckingPass(Options));
1071 if (!IsThinLTOPostLink) {
1077 PB.registerPipelineStartEPCallback(
1078 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
1079 if (
Level == OptimizationLevel::O0 &&
1080 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1086 MPM.addPass(InferFunctionAttrsPass());
1091 if (std::optional<GCOVOptions> Options =
1093 PB.registerPipelineStartEPCallback(
1094 [
this, Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1098 if (std::optional<InstrProfOptions> Options =
1100 PB.registerPipelineStartEPCallback(
1101 [Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1102 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1108 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1109 OptimizationLevel
Level,
1110 ThinOrFullLTOPhase) {
1111 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1112 MPM.addPass(ModuleMemProfilerPass());
1116 if (CodeGenOpts.FatLTO) {
1117 MPM.addPass(PB.buildFatLTODefaultPipeline(
1118 Level, PrepareForThinLTO,
1119 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1120 }
else if (PrepareForThinLTO) {
1121 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(
Level));
1122 }
else if (PrepareForLTO) {
1123 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(
Level));
1125 MPM.addPass(PB.buildPerModuleDefaultPipeline(
Level));
1130 if (CodeGenOpts.LinkBitcodePostopt)
1131 MPM.addPass(LinkInModulesPass(BC));
1133 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1134 LangOpts.HIPStdParInterposeAlloc)
1135 MPM.addPass(HipStdParAllocationInterpositionPass());
1143 MPM.addPass(VerifierPass());
1146 CodeGenOpts.FatLTO) {
1147 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1148 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1149 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1150 CodeGenOpts.EnableSplitLTOUnit);
1157 MPM.addPass(ThinLTOBitcodeWriterPass(
1158 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1160 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1166 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1167 if (EmitLTOSummary) {
1168 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1169 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1170 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1171 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1175 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1178 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1183 if (shouldEmitUnifiedLTOModueFlag() &&
1184 !TheModule->getModuleFlag(
"UnifiedLTO"))
1185 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1192 if (PrintPipelinePasses) {
1193 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1194 auto PassName = PIC.getPassNameForClassName(ClassName);
1195 return PassName.empty() ? ClassName : PassName;
1203 PrettyStackTraceString CrashInfo(
"Optimizer");
1204 llvm::TimeTraceScope TimeScope(
"Optimizer");
1210 MPM.run(*TheModule, MAM);
1216void EmitAssemblyHelper::RunCodegenPipeline(
1217 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1218 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1228 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1229 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1236 legacy::PassManager CodeGenPasses;
1239 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1241 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1242 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1243 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
1245 const llvm::TargetOptions &Options = TM->Options;
1246 CodeGenPasses.add(
new RuntimeLibraryInfoWrapper(
1247 TargetTriple, Options.ExceptionModel, Options.FloatABIType,
1248 Options.EABIVersion, Options.MCOptions.ABIName, Options.VecLib));
1256 if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
1257 DwoOS ? &DwoOS->os() :
nullptr, CGFT,
1258 !CodeGenOpts.VerifyModule)) {
1259 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1266 if (PrintPipelinePasses) {
1271 PrettyStackTraceString CrashInfo(
"Code generation");
1272 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1275 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1278 CodeGenPasses.run(*TheModule);
1285 std::unique_ptr<raw_pwrite_stream> OS,
1286 BackendConsumer *BC) {
1290 CreateTargetMachine(RequiresCodeGen);
1292 if (RequiresCodeGen && !TM)
1295 TheModule->setDataLayout(TM->createDataLayout());
1298 cl::PrintOptionValues();
1300 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1301 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1302 RunCodegenPipeline(Action, OS, DwoOS);
1312 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1313 std::string SampleProfile, std::string ProfileRemapping,
1318 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1319 ModuleToDefinedGVSummaries;
1320 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1327 FunctionImporter::ImportIDTable ImportIDs;
1328 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1329 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1332 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1333 return std::make_unique<CachedFileStream>(std::move(OS),
1334 CGOpts.ObjectFilenameForDebug);
1337 if (CGOpts.SaveTempsFilePrefix !=
"") {
1338 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1340 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1341 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1346 Conf.CPU = TOpts.CPU;
1348 Conf.MAttrs = TOpts.Features;
1349 Conf.RelocModel = CGOpts.RelocationModel;
1350 std::optional<CodeGenOptLevel> OptLevelOrNone =
1351 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1352 assert(OptLevelOrNone &&
"Invalid optimization level!");
1353 Conf.CGOptLevel = *OptLevelOrNone;
1354 Conf.OptLevel = CGOpts.OptimizationLevel;
1356 Conf.SampleProfile = std::move(SampleProfile);
1357 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1358 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1359 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1362 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1363 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1364 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1367 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1370 if (CGOpts.hasProfileCSIRInstr()) {
1371 Conf.RunCSIRInstr =
true;
1373 }
else if (CGOpts.hasProfileCSIRUse()) {
1374 Conf.RunCSIRInstr =
false;
1375 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1378 Conf.ProfileRemapping = std::move(ProfileRemapping);
1379 Conf.DebugPassManager = CGOpts.DebugPassManager;
1380 Conf.VerifyEach = CGOpts.VerifyEach;
1381 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1382 Conf.RemarksFilename = CGOpts.OptRecordFile;
1383 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1384 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1385 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1386 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1388 Conf.LoadedPassPlugins.push_back(Plugin.get());
1391 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1396 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1397 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1402 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1403 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1416 finalizeLLVMOptimizationRemarks(M->getContext());
1417 if (
Error E = thinBackend(
1418 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1419 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1420 nullptr, Conf.CodeGenOnly, {},
1421 nullptr, CGOpts.CmdArgs)) {
1422 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1423 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1429 StringRef TDesc, llvm::Module *M,
1432 std::unique_ptr<raw_pwrite_stream> OS,
1434 llvm::TimeTraceScope TimeScope(
"Backend");
1437 std::unique_ptr<llvm::Module> EmptyModule;
1440 auto BypassSandbox = sys::sandbox::scopedDisable();
1444 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1445 if (
Error E = llvm::getModuleSummaryIndexForFile(
1448 .moveInto(CombinedIndex)) {
1449 logAllUnhandledErrors(std::move(E), errs(),
1450 "Error loading index file '" +
1458 if (CombinedIndex) {
1459 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1471 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1472 EmptyModule->setTargetTriple(M->getTargetTriple());
1473 M = EmptyModule.get();
1477 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1478 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1483 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1484 if (DLDesc != TDesc) {
1485 Diags.
Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1493 llvm::MemoryBufferRef Buf) {
1496 llvm::embedBitcodeInModule(
1508 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1509 VFS.getBufferForFile(OffloadObject);
1510 if (ObjectOrErr.getError()) {
1511 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1515 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1516 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::string flattenClangCommandLine(ArrayRef< std::string > Args, StringRef MainFilename, ArrayRef< StringRef > InputFiles)
static std::optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
void addLowerAllowCheckPass(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
Defines the Diagnostic-related interfaces.
Defines the clang::LangOptions interface.
This file provides a pass to link in Modules from a provided BackendConsumer.
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 StackUsageFile
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
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.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
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()
FrontendOptions & getFrontendOpts()
HeaderSearchOptions & getHeaderSearchOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
llvm::ArrayRef< std::unique_ptr< llvm::PassPlugin > > getPassPlugins() const
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.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
@ 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.
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.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.