19#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/Analysis/GlobalsModRef.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/Frontend/Driver/CodeGenOptions.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DebugInfo.h"
32#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/ModuleSummaryIndex.h"
35#include "llvm/IR/PassManager.h"
36#include "llvm/IR/Verifier.h"
37#include "llvm/IRPrinter/IRPrintingPasses.h"
38#include "llvm/LTO/LTOBackend.h"
39#include "llvm/MC/TargetRegistry.h"
40#include "llvm/Object/OffloadBinary.h"
41#include "llvm/Passes/PassBuilder.h"
42#include "llvm/Passes/PassPlugin.h"
43#include "llvm/Passes/StandardInstrumentations.h"
44#include "llvm/ProfileData/InstrProfCorrelator.h"
45#include "llvm/Support/BuryPointer.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/PrettyStackTrace.h"
49#include "llvm/Support/Program.h"
50#include "llvm/Support/TimeProfiler.h"
51#include "llvm/Support/Timer.h"
52#include "llvm/Support/ToolOutputFile.h"
53#include "llvm/Support/VirtualFileSystem.h"
54#include "llvm/Support/raw_ostream.h"
55#include "llvm/Target/TargetMachine.h"
56#include "llvm/Target/TargetOptions.h"
57#include "llvm/TargetParser/SubtargetFeature.h"
58#include "llvm/TargetParser/Triple.h"
59#include "llvm/Transforms/HipStdPar/HipStdPar.h"
60#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
61#include "llvm/Transforms/IPO/LowerTypeTests.h"
62#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
63#include "llvm/Transforms/InstCombine/InstCombine.h"
64#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
65#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
66#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
67#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
68#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
69#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
70#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
71#include "llvm/Transforms/Instrumentation/KCFI.h"
72#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
73#include "llvm/Transforms/Instrumentation/MemProfiler.h"
74#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
75#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
76#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
77#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
78#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
79#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
80#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
81#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
82#include "llvm/Transforms/ObjCARC.h"
83#include "llvm/Transforms/Scalar/EarlyCSE.h"
84#include "llvm/Transforms/Scalar/GVN.h"
85#include "llvm/Transforms/Scalar/JumpThreading.h"
86#include "llvm/Transforms/Utils/Debugify.h"
87#include "llvm/Transforms/Utils/ModuleUtils.h"
94#define HANDLE_EXTENSION(Ext) \
95 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
96#include "llvm/Support/Extension.def"
103 "sanitizer-early-opt-ep", cl::Optional,
104 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
109 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
111 "Function attribute to apply to cold functions as determined by PGO"),
112 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
113 "Default (no attribute)"),
114 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
115 "Mark cold functions with optsize."),
116 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
117 "Mark cold functions with minsize."),
118 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
119 "Mark cold functions with optnone.")));
130std::string getDefaultProfileGenName() {
132 ?
"default_%m.proflite"
133 :
"default_%m.profraw";
136class EmitAssemblyHelper {
142 llvm::Module *TheModule;
145 std::unique_ptr<raw_pwrite_stream> OS;
149 TargetIRAnalysis getTargetIRAnalysis()
const {
151 return TM->getTargetIRAnalysis();
153 return TargetIRAnalysis();
164 void CreateTargetMachine(
bool MustCreateTM);
169 bool AddEmitPasses(legacy::PassManager &CodeGenPasses,
BackendAction Action,
170 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
172 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef
Path) {
174 auto F = std::make_unique<llvm::ToolOutputFile>(
Path, EC,
175 llvm::sys::fs::OF_None);
177 Diags.
Report(diag::err_fe_unable_to_open_output) <<
Path << EC.message();
183 void RunOptimizationPipeline(
184 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
185 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS,
BackendConsumer *BC);
187 std::unique_ptr<raw_pwrite_stream> &OS,
188 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
195 bool shouldEmitRegularLTOSummary()
const {
196 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
197 TargetTriple.getVendor() != llvm::Triple::Apple;
203 bool shouldEmitUnifiedLTOModueFlag()
const {
204 return CodeGenOpts.UnifiedLTO &&
205 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
212 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
213 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
215 TargetTriple(TheModule->getTargetTriple()) {}
217 ~EmitAssemblyHelper() {
218 if (CodeGenOpts.DisableFree)
219 BuryPointer(std::move(TM));
222 std::unique_ptr<TargetMachine> TM;
225 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
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;
356 llvm::TargetOptions &Options) {
361 switch (LangOpts.getThreadModel()) {
362 case LangOptions::ThreadModelKind::POSIX:
363 Options.ThreadModel = llvm::ThreadModel::POSIX;
365 case LangOptions::ThreadModelKind::Single:
366 Options.ThreadModel = llvm::ThreadModel::Single;
371 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
373 "Invalid Floating Point ABI!");
374 Options.FloatABIType =
375 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
376 .Case(
"soft", llvm::FloatABI::Soft)
377 .Case(
"softfp", llvm::FloatABI::Soft)
378 .Case(
"hard", llvm::FloatABI::Hard)
379 .Default(llvm::FloatABI::Default);
382 switch (LangOpts.getDefaultFPContractMode()) {
383 case LangOptions::FPM_Off:
386 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
388 case LangOptions::FPM_On:
389 case LangOptions::FPM_FastHonorPragmas:
390 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
392 case LangOptions::FPM_Fast:
393 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
397 Options.BinutilsVersion =
398 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
399 Options.UseInitArray = CodeGenOpts.UseInitArray;
400 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
406 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
408 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
410 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
412 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
414 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
415 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
416 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
417 Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
418 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
419 (LangOpts.getDefaultFPContractMode() ==
420 LangOptions::FPModeKind::FPM_Fast ||
421 LangOpts.getDefaultFPContractMode() ==
422 LangOptions::FPModeKind::FPM_FastHonorPragmas);
423 Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
425 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
427 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
428 .Case(
"all", llvm::BasicBlockSection::All)
429 .StartsWith(
"list=", llvm::BasicBlockSection::List)
430 .Case(
"none", llvm::BasicBlockSection::None)
431 .Default(llvm::BasicBlockSection::None);
433 if (Options.BBSections == llvm::BasicBlockSection::List) {
434 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
435 MemoryBuffer::getFile(CodeGenOpts.
BBSections.substr(5));
437 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
438 << MBOrErr.getError().message();
441 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
444 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
445 Options.FunctionSections = CodeGenOpts.FunctionSections;
446 Options.DataSections = CodeGenOpts.DataSections;
447 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
448 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
449 Options.UniqueBasicBlockSectionNames =
450 CodeGenOpts.UniqueBasicBlockSectionNames;
451 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
452 Options.TLSSize = CodeGenOpts.TLSSize;
453 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
454 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
455 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
456 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
458 Options.EmitAddrsig = CodeGenOpts.Addrsig;
459 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
460 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
461 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
462 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
463 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
464 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
466 Options.Hotpatch = CodeGenOpts.HotPatch;
467 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
468 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
470 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
471 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
472 Options.SwiftAsyncFramePointer =
473 SwiftAsyncFramePointerMode::DeploymentBased;
476 case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
477 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
480 case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
481 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
486 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
487 Options.MCOptions.EmitCompactUnwindNonCanonical =
488 CodeGenOpts.EmitCompactUnwindNonCanonical;
489 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
490 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
491 Options.MCOptions.MCUseDwarfDirectory =
492 CodeGenOpts.NoDwarfDirectoryAsm
493 ? llvm::MCTargetOptions::DisableDwarfDirectory
494 : llvm::MCTargetOptions::EnableDwarfDirectory;
495 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
496 Options.MCOptions.MCIncrementalLinkerCompatible =
497 CodeGenOpts.IncrementalLinkerCompatible;
498 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
499 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
500 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
501 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
502 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
503 Options.MCOptions.Crel = CodeGenOpts.Crel;
504 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
505 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
506 Options.MCOptions.CompressDebugSections =
507 CodeGenOpts.getCompressDebugSections();
508 if (CodeGenOpts.OutputAsmVariant != 3)
509 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
510 Options.MCOptions.ABIName = TargetOpts.
ABI;
511 for (
const auto &Entry : HSOpts.UserEntries)
512 if (!Entry.IsFramework &&
513 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
514 Entry.Group == frontend::IncludeDirGroup::Angled ||
515 Entry.Group == frontend::IncludeDirGroup::System))
516 Options.MCOptions.IASSearchPaths.push_back(
517 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
518 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
522 Options.MCOptions.PPCUseFullRegisterNames =
523 CodeGenOpts.PPCUseFullRegisterNames;
524 Options.MisExpect = CodeGenOpts.MisExpect;
529static std::optional<GCOVOptions>
540 Options.NoRedZone = CodeGenOpts.DisableRedZone;
543 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
547static std::optional<InstrProfOptions>
552 InstrProfOptions Options;
553 Options.NoRedZone = CodeGenOpts.DisableRedZone;
555 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
561 BackendArgs.push_back(
"clang");
563 BackendArgs.push_back(
"-debug-pass");
564 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
567 BackendArgs.push_back(
"-limit-float-precision");
573 if (BackendArgs.size() == 1)
575 BackendArgs.push_back(
nullptr);
579 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
583void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
586 std::string Triple = TheModule->getTargetTriple();
587 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
590 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
594 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
595 std::string FeaturesStr =
598 std::optional<CodeGenOptLevel> OptLevelOrNone =
599 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
600 assert(OptLevelOrNone &&
"Invalid optimization level!");
601 CodeGenOptLevel OptLevel = *OptLevelOrNone;
603 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(TypeSanitizerPass());
742 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
743 MPM.addPass(NumericalStabilitySanitizerPass());
745 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
746 MPM.addPass(RealtimeSanitizerPass());
748 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
751 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
752 llvm::AsanDtorKind DestructorKind =
753 CodeGenOpts.getSanitizeAddressDtor();
754 AddressSanitizerOptions Opts;
755 Opts.CompileKernel = CompileKernel;
757 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
758 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
759 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
763 ASanPass(SanitizerKind::Address,
false);
764 ASanPass(SanitizerKind::KernelAddress,
true);
766 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
769 MPM.addPass(HWAddressSanitizerPass(
770 {CompileKernel, Recover,
771 CodeGenOpts.OptimizationLevel == 0}));
774 HWASanPass(SanitizerKind::HWAddress,
false);
775 HWASanPass(SanitizerKind::KernelHWAddress,
true);
777 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
782 PB.registerOptimizerEarlyEPCallback(
783 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
784 ThinOrFullLTOPhase Phase) {
785 ModulePassManager NewMPM;
786 SanitizersCallback(NewMPM, Level, Phase);
787 if (!NewMPM.isEmpty()) {
789 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
790 MPM.addPass(std::move(NewMPM));
795 PB.registerOptimizerLastEPCallback(SanitizersCallback);
803 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value()) {
805 PB.registerOptimizerEarlyEPCallback(
806 [ScaledCutoffs](ModulePassManager &MPM, OptimizationLevel Level,
807 ThinOrFullLTOPhase Phase) {
808 LowerAllowCheckPass::Options Opts;
810 if (ScaledCutoffs.has_value())
811 Opts.cutoffs = ScaledCutoffs.value();
813 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
818void EmitAssemblyHelper::RunOptimizationPipeline(
819 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
820 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS,
BackendConsumer *BC) {
821 std::optional<PGOOptions> PGOOpt;
830 CodeGenOpts.DebugInfoForProfiling,
831 false, CodeGenOpts.AtomicProfileUpdate);
835 : PGOOptions::NoCSAction;
840 CodeGenOpts.DebugInfoForProfiling);
847 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
851 PGOOptions::NoAction, PGOOptions::NoCSAction,
853 else if (CodeGenOpts.PseudoProbeForProfiling)
856 PGOOptions(
"",
"",
"",
"",
nullptr,
857 PGOOptions::NoAction, PGOOptions::NoCSAction,
859 else if (CodeGenOpts.DebugInfoForProfiling)
861 PGOOpt = PGOOptions(
"",
"",
"",
"",
nullptr,
862 PGOOptions::NoAction, PGOOptions::NoCSAction,
868 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
871 assert(PGOOpt->Action != PGOOptions::IRInstr &&
872 PGOOpt->Action != PGOOptions::SampleUse &&
873 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
876 ? getDefaultProfileGenName()
877 : CodeGenOpts.InstrProfileOutput;
878 PGOOpt->CSAction = PGOOptions::CSIRInstr;
880 PGOOpt = PGOOptions(
"",
882 ? getDefaultProfileGenName()
885 PGOOptions::NoAction, PGOOptions::CSIRInstr,
889 TM->setPGOOption(PGOOpt);
891 PipelineTuningOptions PTO;
892 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
895 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
896 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
897 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
898 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
901 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
902 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
904 LoopAnalysisManager LAM;
905 FunctionAnalysisManager FAM;
906 CGSCCAnalysisManager CGAM;
907 ModuleAnalysisManager MAM;
909 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
910 PassInstrumentationCallbacks PIC;
911 PrintPassOptions PrintPassOpts;
912 PrintPassOpts.Indent = DebugPassStructure;
913 PrintPassOpts.SkipAnalyses = DebugPassStructure;
914 StandardInstrumentations SI(
915 TheModule->getContext(),
916 (CodeGenOpts.DebugPassManager || DebugPassStructure),
917 CodeGenOpts.VerifyEach, PrintPassOpts);
918 SI.registerCallbacks(PIC, &MAM);
919 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
922 switch (CodeGenOpts.getAssignmentTrackingMode()) {
923 case CodeGenOptions::AssignmentTrackingOpts::Forced:
924 PB.registerPipelineStartEPCallback(
925 [&](ModulePassManager &MPM, OptimizationLevel Level) {
926 MPM.addPass(AssignmentTrackingPass());
929 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
932 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
933 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
934 PB.registerPipelineStartEPCallback(
935 [&](ModulePassManager &MPM, OptimizationLevel Level) {
937 if (Level != OptimizationLevel::O0)
938 MPM.addPass(AssignmentTrackingPass());
942 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
947 DebugifyEachInstrumentation Debugify;
948 DebugInfoPerPass DebugInfoBeforePass;
949 if (CodeGenOpts.EnableDIPreservationVerify) {
950 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
951 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
954 Debugify.setOrigDIVerifyBugsReportFilePath(
956 Debugify.registerCallbacks(PIC, MAM);
960 auto PassPlugin = PassPlugin::Load(PluginFN);
962 PassPlugin->registerPassBuilderCallbacks(PB);
964 Diags.
Report(diag::err_fe_unable_to_load_plugin)
965 << PluginFN <<
toString(PassPlugin.takeError());
970#define HANDLE_EXTENSION(Ext) \
971 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
972#include "llvm/Support/Extension.def"
976 std::unique_ptr<TargetLibraryInfoImpl> TLII(
977 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
978 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
981 PB.registerModuleAnalyses(MAM);
982 PB.registerCGSCCAnalyses(CGAM);
983 PB.registerFunctionAnalyses(FAM);
984 PB.registerLoopAnalyses(LAM);
985 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
987 ModulePassManager MPM;
989 if (CodeGenOpts.VerifyModule)
990 MPM.addPass(VerifierPass());
992 if (!CodeGenOpts.DisableLLVMPasses) {
997 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
998 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1000 if (LangOpts.ObjCAutoRefCount) {
1001 PB.registerPipelineStartEPCallback(
1002 [](ModulePassManager &MPM, OptimizationLevel Level) {
1003 if (Level != OptimizationLevel::O0)
1005 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1007 PB.registerPipelineEarlySimplificationEPCallback(
1008 [](ModulePassManager &MPM, OptimizationLevel Level,
1009 ThinOrFullLTOPhase) {
1010 if (Level != OptimizationLevel::O0)
1011 MPM.addPass(ObjCARCAPElimPass());
1013 PB.registerScalarOptimizerLateEPCallback(
1014 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1015 if (Level != OptimizationLevel::O0)
1016 FPM.addPass(ObjCARCOptPass());
1026 if (IsThinLTOPostLink)
1027 PB.registerPipelineStartEPCallback(
1028 [](ModulePassManager &MPM, OptimizationLevel Level) {
1029 MPM.addPass(LowerTypeTestsPass(
1032 lowertypetests::DropTestKind::Assume));
1037 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1038 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1039 OptimizationLevel Level) {
1040 BoundsCheckingPass::Options Options;
1043 static_assert(SanitizerKind::SO_LocalBounds <=
1044 std::numeric_limits<
1045 decltype(Options.GuardKind)::value_type>::max(),
1046 "Update type of llvm.allow.ubsan.check to represent "
1047 "SanitizerKind::SO_LocalBounds.");
1048 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1055 CodeGenOpts.SanitizeMinimalRuntime),
1057 CodeGenOpts.SanitizeRecover.has(SanitizerKind::LocalBounds),
1060 FPM.addPass(BoundsCheckingPass(Options));
1065 if (!IsThinLTOPostLink) {
1070 if (std::optional<GCOVOptions> Options =
1072 PB.registerPipelineStartEPCallback(
1073 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1074 MPM.addPass(GCOVProfilerPass(*Options));
1076 if (std::optional<InstrProfOptions> Options =
1078 PB.registerPipelineStartEPCallback(
1079 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1080 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1086 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1087 OptimizationLevel Level,
1088 ThinOrFullLTOPhase) {
1089 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1090 MPM.addPass(ModuleMemProfilerPass());
1094 if (CodeGenOpts.FatLTO) {
1095 MPM.addPass(PB.buildFatLTODefaultPipeline(
1096 Level, PrepareForThinLTO,
1097 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1098 }
else if (PrepareForThinLTO) {
1099 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1100 }
else if (PrepareForLTO) {
1101 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1103 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1108 if (CodeGenOpts.LinkBitcodePostopt)
1117 MPM.addPass(VerifierPass());
1120 CodeGenOpts.FatLTO) {
1121 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1122 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1123 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1124 CodeGenOpts.EnableSplitLTOUnit);
1131 MPM.addPass(ThinLTOBitcodeWriterPass(
1132 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1134 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1140 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1141 if (EmitLTOSummary) {
1142 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1143 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1144 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1145 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1149 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1152 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1157 if (shouldEmitUnifiedLTOModueFlag())
1158 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1166 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1167 auto PassName = PIC.getPassNameForClassName(ClassName);
1168 return PassName.empty() ? ClassName : PassName;
1174 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1175 LangOpts.HIPStdParInterposeAlloc)
1176 MPM.addPass(HipStdParAllocationInterpositionPass());
1180 PrettyStackTraceString CrashInfo(
"Optimizer");
1181 llvm::TimeTraceScope TimeScope(
"Optimizer");
1187 MPM.run(*TheModule, MAM);
1193void EmitAssemblyHelper::RunCodegenPipeline(
1194 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1195 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1199 legacy::PassManager CodeGenPasses;
1207 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1213 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1214 DwoOS ? &DwoOS->os() :
nullptr))
1230 PrettyStackTraceString CrashInfo(
"Code generation");
1231 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1234 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1237 CodeGenPasses.run(*TheModule);
1244 std::unique_ptr<raw_pwrite_stream> OS,
1249 CreateTargetMachine(RequiresCodeGen);
1251 if (RequiresCodeGen && !TM)
1254 TheModule->setDataLayout(TM->createDataLayout());
1257 cl::PrintOptionValues();
1259 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1260 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1261 RunCodegenPipeline(Action, OS, DwoOS);
1271 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1272 std::string SampleProfile, std::string ProfileRemapping,
1277 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1278 ModuleToDefinedGVSummaries;
1279 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1286 FunctionImporter::ImportIDTable ImportIDs;
1287 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1288 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1291 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1292 return std::make_unique<CachedFileStream>(std::move(OS),
1293 CGOpts.ObjectFilenameForDebug);
1296 if (CGOpts.SaveTempsFilePrefix !=
"") {
1297 if (Error
E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1299 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1300 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1305 Conf.CPU = TOpts.CPU;
1307 Conf.MAttrs = TOpts.Features;
1308 Conf.RelocModel = CGOpts.RelocationModel;
1309 std::optional<CodeGenOptLevel> OptLevelOrNone =
1310 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1311 assert(OptLevelOrNone &&
"Invalid optimization level!");
1312 Conf.CGOptLevel = *OptLevelOrNone;
1313 Conf.OptLevel = CGOpts.OptimizationLevel;
1315 Conf.SampleProfile = std::move(SampleProfile);
1316 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1319 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1320 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1321 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1324 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1327 if (CGOpts.hasProfileCSIRInstr()) {
1328 Conf.RunCSIRInstr =
true;
1329 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1330 }
else if (CGOpts.hasProfileCSIRUse()) {
1331 Conf.RunCSIRInstr =
false;
1332 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1335 Conf.ProfileRemapping = std::move(ProfileRemapping);
1336 Conf.DebugPassManager = CGOpts.DebugPassManager;
1337 Conf.VerifyEach = CGOpts.VerifyEach;
1338 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1339 Conf.RemarksFilename = CGOpts.OptRecordFile;
1340 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1341 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1342 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1343 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1346 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1351 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1352 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1357 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1358 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1367 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1368 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1369 nullptr, Conf.CodeGenOnly,
1370 nullptr, CGOpts.CmdArgs)) {
1371 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1372 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1378 StringRef TDesc, llvm::Module *M,
1381 std::unique_ptr<raw_pwrite_stream> OS,
1383 llvm::TimeTraceScope TimeScope(
"Backend");
1386 std::unique_ptr<llvm::Module> EmptyModule;
1391 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1392 if (Error
E = llvm::getModuleSummaryIndexForFile(
1395 .moveInto(CombinedIndex)) {
1396 logAllUnhandledErrors(std::move(
E), errs(),
1397 "Error loading index file '" +
1405 if (CombinedIndex) {
1406 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1418 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1419 EmptyModule->setTargetTriple(M->getTargetTriple());
1420 M = EmptyModule.get();
1424 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1425 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1430 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1431 if (DLDesc != TDesc) {
1434 "expected target description '%1'");
1435 Diags.
Report(DiagID) << DLDesc << TDesc;
1443 llvm::MemoryBufferRef Buf) {
1446 llvm::embedBitcodeInModule(
1458 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1459 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1460 if (ObjectOrErr.getError()) {
1462 "could not open '%0' for embedding");
1463 Diags.
Report(DiagID) << OffloadObject;
1467 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1468 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 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 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 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::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.
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::vector< std::string > CommandLineArgs
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
TargetOptions & getTargetOpts()
HeaderSearchOptions & getHeaderSearchOpts()
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.
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.
std::optional< std::vector< unsigned > > getAllScaled(unsigned ScalingFactor) const
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...
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)
llvm::cl::opt< bool > ClSanitizeGuardChecks
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
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.