19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/TargetLibraryInfo.h"
23#include "llvm/Analysis/TargetTransformInfo.h"
24#include "llvm/Bitcode/BitcodeReader.h"
25#include "llvm/Bitcode/BitcodeWriter.h"
26#include "llvm/Bitcode/BitcodeWriterPass.h"
27#include "llvm/CodeGen/TargetSubtargetInfo.h"
28#include "llvm/Config/llvm-config.h"
29#include "llvm/Frontend/Driver/CodeGenOptions.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DebugInfo.h"
32#include "llvm/IR/LLVMRemarkStreamer.h"
33#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/ModuleSummaryIndex.h"
36#include "llvm/IR/PassManager.h"
37#include "llvm/IR/Verifier.h"
38#include "llvm/IRPrinter/IRPrintingPasses.h"
39#include "llvm/LTO/LTOBackend.h"
40#include "llvm/MC/TargetRegistry.h"
41#include "llvm/Object/OffloadBinary.h"
42#include "llvm/Passes/PassBuilder.h"
43#include "llvm/Passes/PassPlugin.h"
44#include "llvm/Passes/StandardInstrumentations.h"
45#include "llvm/ProfileData/InstrProfCorrelator.h"
46#include "llvm/Support/BuryPointer.h"
47#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/PrettyStackTrace.h"
51#include "llvm/Support/Program.h"
52#include "llvm/Support/TimeProfiler.h"
53#include "llvm/Support/Timer.h"
54#include "llvm/Support/ToolOutputFile.h"
55#include "llvm/Support/VirtualFileSystem.h"
56#include "llvm/Support/raw_ostream.h"
57#include "llvm/Target/TargetMachine.h"
58#include "llvm/Target/TargetOptions.h"
59#include "llvm/TargetParser/SubtargetFeature.h"
60#include "llvm/TargetParser/Triple.h"
61#include "llvm/Transforms/HipStdPar/HipStdPar.h"
62#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
63#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
64#include "llvm/Transforms/IPO/LowerTypeTests.h"
65#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
66#include "llvm/Transforms/InstCombine/InstCombine.h"
67#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
68#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
69#include "llvm/Transforms/Instrumentation/AllocToken.h"
70#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
71#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
72#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
73#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
74#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
75#include "llvm/Transforms/Instrumentation/KCFI.h"
76#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
77#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
78#include "llvm/Transforms/Instrumentation/MemProfUse.h"
79#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
80#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
81#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
82#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
83#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
84#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
85#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
86#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
87#include "llvm/Transforms/ObjCARC.h"
88#include "llvm/Transforms/Scalar/EarlyCSE.h"
89#include "llvm/Transforms/Scalar/GVN.h"
90#include "llvm/Transforms/Scalar/JumpThreading.h"
91#include "llvm/Transforms/Utils/Debugify.h"
92#include "llvm/Transforms/Utils/ModuleUtils.h"
99#define HANDLE_EXTENSION(Ext) \
100 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
101#include "llvm/Support/Extension.def"
106 "sanitizer-early-opt-ep", cl::Optional,
107 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
112 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
114 "Function attribute to apply to cold functions as determined by PGO"),
115 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
116 "Default (no attribute)"),
117 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
118 "Mark cold functions with optsize."),
119 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
120 "Mark cold functions with minsize."),
121 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
122 "Mark cold functions with optnone.")));
124LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
134 ? llvm::driver::getDefaultProfileGenName()
136 if (CodeGenOpts.ContinuousProfileSync)
143class EmitAssemblyHelper {
144 CompilerInstance &CI;
145 DiagnosticsEngine &Diags;
146 const CodeGenOptions &CodeGenOpts;
147 const clang::TargetOptions &TargetOpts;
148 const LangOptions &LangOpts;
149 llvm::Module *TheModule;
150 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
152 std::unique_ptr<raw_pwrite_stream> OS;
156 TargetIRAnalysis getTargetIRAnalysis()
const {
158 return TM->getTargetIRAnalysis();
160 return TargetIRAnalysis();
171 void CreateTargetMachine(
bool MustCreateTM);
176 bool AddEmitPasses(legacy::PassManager &CodeGenPasses,
BackendAction Action,
177 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
179 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
181 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
182 llvm::sys::fs::OF_None);
184 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
190 void RunOptimizationPipeline(
191 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
192 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
194 std::unique_ptr<raw_pwrite_stream> &OS,
195 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
202 bool shouldEmitRegularLTOSummary()
const {
203 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
204 TargetTriple.getVendor() != llvm::Triple::Apple;
210 bool shouldEmitUnifiedLTOModueFlag()
const {
211 return CodeGenOpts.UnifiedLTO &&
212 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
216 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
218 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
219 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
220 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
221 TheModule(M), VFS(std::move(VFS)),
222 TargetTriple(TheModule->getTargetTriple()) {}
224 ~EmitAssemblyHelper() {
225 if (CodeGenOpts.DisableFree)
226 BuryPointer(std::move(TM));
229 std::unique_ptr<TargetMachine> TM;
232 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
233 BackendConsumer *BC);
239 AllocTokenOptions Opts;
243 Opts.Extended = CGOpts.SanitizeAllocTokenExtended;
244 Opts.FastABI = CGOpts.SanitizeAllocTokenFastABI;
248static SanitizerCoverageOptions
250 SanitizerCoverageOptions Opts;
252 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
253 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
254 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
255 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
256 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
257 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
258 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
259 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
260 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
261 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
262 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
263 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
264 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
265 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
266 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
267 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
268 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
269 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
273static SanitizerBinaryMetadataOptions
275 SanitizerBinaryMetadataOptions Opts;
276 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
277 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
278 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
287 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
289 switch (
T.getObjectFormat()) {
294 return !CGOpts.DisableIntegratedAS;
296 llvm::report_fatal_error(
"ASan not implemented for GOFF");
298 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
300 case Triple::DXContainer:
302 case Triple::UnknownObjectFormat:
308static std::optional<llvm::CodeModel::Model>
310 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
311 .Case(
"tiny", llvm::CodeModel::Tiny)
312 .Case(
"small", llvm::CodeModel::Small)
313 .Case(
"kernel", llvm::CodeModel::Kernel)
314 .Case(
"medium", llvm::CodeModel::Medium)
315 .Case(
"large", llvm::CodeModel::Large)
316 .Cases({
"default",
""}, ~1u)
318 assert(CodeModel != ~0u &&
"invalid code model!");
319 if (CodeModel == ~1u)
321 return static_cast<llvm::CodeModel::Model
>(CodeModel);
326 return CodeGenFileType::ObjectFile;
328 return CodeGenFileType::Null;
331 return CodeGenFileType::AssemblyFile;
341 StringRef MainFilename) {
343 return std::string{};
345 std::string FlatCmdLine;
346 raw_string_ostream OS(FlatCmdLine);
347 bool PrintedOneArg =
false;
348 if (!StringRef(Args[0]).
contains(
"-cc1")) {
349 llvm::sys::printArg(OS,
"-cc1",
true);
350 PrintedOneArg =
true;
352 for (
unsigned i = 0; i < Args.size(); i++) {
353 StringRef Arg = Args[i];
356 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
360 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
363 if (Arg.starts_with(
"-fmessage-length"))
367 llvm::sys::printArg(OS, Arg,
true);
368 PrintedOneArg =
true;
375 llvm::TargetOptions &Options) {
380 switch (LangOpts.getThreadModel()) {
382 Options.ThreadModel = llvm::ThreadModel::POSIX;
385 Options.ThreadModel = llvm::ThreadModel::Single;
390 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
392 "Invalid Floating Point ABI!");
393 Options.FloatABIType =
394 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
395 .Case(
"soft", llvm::FloatABI::Soft)
396 .Case(
"softfp", llvm::FloatABI::Soft)
397 .Case(
"hard", llvm::FloatABI::Hard)
398 .Default(llvm::FloatABI::Default);
401 switch (LangOpts.getDefaultFPContractMode()) {
405 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
409 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
412 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
416 Options.BinutilsVersion =
417 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
418 Options.UseInitArray = CodeGenOpts.UseInitArray;
419 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
425 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
427 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
429 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
431 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
433 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
434 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
435 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
437 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
439 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
440 .Case(
"all", llvm::BasicBlockSection::All)
441 .StartsWith(
"list=", llvm::BasicBlockSection::List)
442 .Case(
"none", llvm::BasicBlockSection::None)
443 .Default(llvm::BasicBlockSection::None);
445 if (Options.BBSections == llvm::BasicBlockSection::List) {
446 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
450 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
451 << MBOrErr.getError().message();
454 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
457 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
458 Options.FunctionSections = CodeGenOpts.FunctionSections;
459 Options.DataSections = CodeGenOpts.DataSections;
460 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
461 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
462 Options.UniqueBasicBlockSectionNames =
463 CodeGenOpts.UniqueBasicBlockSectionNames;
464 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
465 Options.TLSSize = CodeGenOpts.TLSSize;
466 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
467 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
468 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
469 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
471 Options.EmitAddrsig = CodeGenOpts.Addrsig;
472 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
473 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
474 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
475 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
476 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
477 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
478 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
480 Options.Hotpatch = CodeGenOpts.HotPatch;
481 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
482 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
484 switch (CodeGenOpts.getVecLib()) {
485 case llvm::driver::VectorLibrary::NoLibrary:
486 Options.VecLib = llvm::VectorLibrary::NoLibrary;
488 case llvm::driver::VectorLibrary::Accelerate:
489 Options.VecLib = llvm::VectorLibrary::Accelerate;
491 case llvm::driver::VectorLibrary::Darwin_libsystem_m:
492 Options.VecLib = llvm::VectorLibrary::DarwinLibSystemM;
494 case llvm::driver::VectorLibrary::LIBMVEC:
495 Options.VecLib = llvm::VectorLibrary::LIBMVEC;
497 case llvm::driver::VectorLibrary::MASSV:
498 Options.VecLib = llvm::VectorLibrary::MASSV;
500 case llvm::driver::VectorLibrary::SVML:
501 Options.VecLib = llvm::VectorLibrary::SVML;
503 case llvm::driver::VectorLibrary::SLEEF:
504 Options.VecLib = llvm::VectorLibrary::SLEEFGNUABI;
506 case llvm::driver::VectorLibrary::ArmPL:
507 Options.VecLib = llvm::VectorLibrary::ArmPL;
509 case llvm::driver::VectorLibrary::AMDLIBM:
510 Options.VecLib = llvm::VectorLibrary::AMDLIBM;
514 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
516 Options.SwiftAsyncFramePointer =
517 SwiftAsyncFramePointerMode::DeploymentBased;
521 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
525 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
530 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
531 Options.MCOptions.EmitCompactUnwindNonCanonical =
532 CodeGenOpts.EmitCompactUnwindNonCanonical;
533 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
534 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
535 Options.MCOptions.MCUseDwarfDirectory =
536 CodeGenOpts.NoDwarfDirectoryAsm
537 ? llvm::MCTargetOptions::DisableDwarfDirectory
538 : llvm::MCTargetOptions::EnableDwarfDirectory;
539 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
540 Options.MCOptions.MCIncrementalLinkerCompatible =
541 CodeGenOpts.IncrementalLinkerCompatible;
542 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
543 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
544 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
545 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
546 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
547 Options.MCOptions.Crel = CodeGenOpts.Crel;
548 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
549 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
550 Options.MCOptions.CompressDebugSections =
551 CodeGenOpts.getCompressDebugSections();
552 if (CodeGenOpts.OutputAsmVariant != 3)
553 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
554 Options.MCOptions.ABIName = TargetOpts.
ABI;
555 for (
const auto &Entry : HSOpts.UserEntries)
556 if (!Entry.IsFramework &&
560 Options.MCOptions.IASSearchPaths.push_back(
561 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
562 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
566 Options.MCOptions.PPCUseFullRegisterNames =
567 CodeGenOpts.PPCUseFullRegisterNames;
568 Options.MisExpect = CodeGenOpts.MisExpect;
573static std::optional<GCOVOptions>
584 Options.NoRedZone = CodeGenOpts.DisableRedZone;
587 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
591static std::optional<InstrProfOptions>
596 InstrProfOptions Options;
597 Options.NoRedZone = CodeGenOpts.DisableRedZone;
601 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
606 vfs::FileSystem &VFS) {
608 BackendArgs.push_back(
"clang");
610 BackendArgs.push_back(
"-debug-pass");
611 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
614 BackendArgs.push_back(
"-limit-float-precision");
621 if (BackendArgs.size() == 1)
623 BackendArgs.push_back(
nullptr);
627 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
632void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
635 const llvm::Triple &Triple = TheModule->getTargetTriple();
636 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
639 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
643 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
644 std::string FeaturesStr =
647 std::optional<CodeGenOptLevel> OptLevelOrNone =
648 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
649 assert(OptLevelOrNone &&
"Invalid optimization level!");
650 CodeGenOptLevel OptLevel = *OptLevelOrNone;
652 llvm::TargetOptions Options;
655 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
656 Options, RM, CM, OptLevel));
661bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
663 raw_pwrite_stream &OS,
664 raw_pwrite_stream *DwoOS) {
666 std::unique_ptr<TargetLibraryInfoImpl> TLII(
667 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
668 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
674 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
675 !CodeGenOpts.VerifyModule)) {
676 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
684 switch (Opts.OptimizationLevel) {
686 llvm_unreachable(
"Invalid optimization level!");
689 return OptimizationLevel::O0;
692 return OptimizationLevel::O1;
695 switch (Opts.OptimizeSize) {
697 llvm_unreachable(
"Invalid optimization level for size!");
700 return OptimizationLevel::O2;
703 return OptimizationLevel::Os;
706 return OptimizationLevel::Oz;
710 return OptimizationLevel::O3;
717 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
718 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
719 TargetTriple.isARM() || TargetTriple.isThumb())
723 PB.registerOptimizerLastEPCallback(
724 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
725 if (Level == OptimizationLevel::O0 &&
727 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
732 PB.registerPeepholeEPCallback(
733 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
734 if (Level != OptimizationLevel::O0 &&
736 FPM.addPass(KCFIPass());
743 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
744 ThinOrFullLTOPhase) {
748 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
754 MPM.addPass(SanitizerBinaryMetadataPass(
756 PB.getVirtualFileSystemPtr(),
760 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
762 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
765 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
766 CodeGenOpts.SanitizeMemoryParamRetval);
767 MPM.addPass(MemorySanitizerPass(
options));
768 if (Level != OptimizationLevel::O0) {
773 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
774 FunctionPassManager FPM;
775 FPM.addPass(EarlyCSEPass(
true ));
776 FPM.addPass(InstCombinePass());
777 FPM.addPass(JumpThreadingPass());
778 FPM.addPass(GVNPass());
779 FPM.addPass(InstCombinePass());
780 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
784 MSanPass(SanitizerKind::Memory,
false);
785 MSanPass(SanitizerKind::KernelMemory,
true);
787 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
788 MPM.addPass(ModuleThreadSanitizerPass());
789 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
793 MPM.addPass(TypeSanitizerPass());
795 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
796 MPM.addPass(NumericalStabilitySanitizerPass());
798 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
799 MPM.addPass(RealtimeSanitizerPass());
801 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
804 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
805 llvm::AsanDtorKind DestructorKind =
806 CodeGenOpts.getSanitizeAddressDtor();
807 AddressSanitizerOptions Opts;
808 Opts.CompileKernel = CompileKernel;
810 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
811 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
812 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
816 ASanPass(SanitizerKind::Address,
false);
817 ASanPass(SanitizerKind::KernelAddress,
true);
819 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
822 MPM.addPass(HWAddressSanitizerPass(
823 {CompileKernel, Recover,
824 CodeGenOpts.OptimizationLevel == 0}));
827 HWASanPass(SanitizerKind::HWAddress,
false);
828 HWASanPass(SanitizerKind::KernelHWAddress,
true);
830 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
832 PB.getVirtualFileSystemPtr()));
836 PB.registerOptimizerEarlyEPCallback(
837 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
838 ThinOrFullLTOPhase Phase) {
839 ModulePassManager NewMPM;
840 SanitizersCallback(NewMPM, Level, Phase);
841 if (!NewMPM.isEmpty()) {
843 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
844 MPM.addPass(std::move(NewMPM));
849 PB.registerOptimizerLastEPCallback(SanitizersCallback);
855 uint64_t AllowRuntimeCheckSkipHotCutoff =
858 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
861 PB.registerOptimizerEarlyEPCallback(
862 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
863 ModulePassManager &MPM, OptimizationLevel Level,
864 ThinOrFullLTOPhase Phase) {
865 LowerAllowCheckPass::Options Opts;
867 if (ScaledCutoffs.has_value())
868 Opts.cutoffs = ScaledCutoffs.value();
869 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
871 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
879 PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
880 OptimizationLevel Level,
881 ThinOrFullLTOPhase) {
882 if (Level == OptimizationLevel::O0 &&
883 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
887 MPM.addPass(InferFunctionAttrsPass());
893void EmitAssemblyHelper::RunOptimizationPipeline(
894 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
895 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
896 std::optional<PGOOptions> PGOOpt;
903 CodeGenOpts.DebugInfoForProfiling,
905 CodeGenOpts.AtomicProfileUpdate);
909 : PGOOptions::NoCSAction;
914 CodeGenOpts.DebugInfoForProfiling);
921 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
925 PGOOptions::NoAction, PGOOptions::NoCSAction,
927 else if (CodeGenOpts.PseudoProbeForProfiling)
929 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
931 CodeGenOpts.DebugInfoForProfiling,
true);
932 else if (CodeGenOpts.DebugInfoForProfiling)
934 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
940 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
943 assert(PGOOpt->Action != PGOOptions::IRInstr &&
944 PGOOpt->Action != PGOOptions::SampleUse &&
945 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
948 PGOOpt->CSAction = PGOOptions::CSIRInstr;
951 "", PGOOptions::NoAction,
953 CodeGenOpts.DebugInfoForProfiling);
956 TM->setPGOOption(PGOOpt);
958 PipelineTuningOptions PTO;
959 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
960 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
961 PTO.LoopFusion = CodeGenOpts.FuseLoops;
964 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
965 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
966 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
967 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
970 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
971 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
973 LoopAnalysisManager LAM;
974 FunctionAnalysisManager FAM;
975 CGSCCAnalysisManager CGAM;
976 ModuleAnalysisManager MAM;
978 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
979 PassInstrumentationCallbacks PIC;
980 PrintPassOptions PrintPassOpts;
981 PrintPassOpts.Indent = DebugPassStructure;
982 PrintPassOpts.SkipAnalyses = DebugPassStructure;
983 StandardInstrumentations SI(
984 TheModule->getContext(),
985 (CodeGenOpts.DebugPassManager || DebugPassStructure),
986 CodeGenOpts.VerifyEach, PrintPassOpts);
987 SI.registerCallbacks(PIC, &MAM);
991 switch (CodeGenOpts.getAssignmentTrackingMode()) {
992 case CodeGenOptions::AssignmentTrackingOpts::Forced:
993 PB.registerPipelineStartEPCallback(
994 [&](ModulePassManager &MPM, OptimizationLevel Level) {
995 MPM.addPass(AssignmentTrackingPass());
998 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
1001 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
1002 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
1003 PB.registerPipelineStartEPCallback(
1004 [&](ModulePassManager &MPM, OptimizationLevel Level) {
1006 if (Level != OptimizationLevel::O0)
1007 MPM.addPass(AssignmentTrackingPass());
1011 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
1016 DebugifyEachInstrumentation Debugify;
1017 DebugInfoPerPass DebugInfoBeforePass;
1018 if (CodeGenOpts.EnableDIPreservationVerify) {
1019 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
1020 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
1023 Debugify.setOrigDIVerifyBugsReportFilePath(
1025 Debugify.registerCallbacks(PIC, MAM);
1027#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
1034 if (!F.getSubprogram())
1036 for (BasicBlock &BB : F)
1037 for (Instruction &I : BB)
1038 if (!I.getDebugLoc())
1039 I.setDebugLoc(DebugLoc::getCompilerGenerated());
1045 auto PassPlugin = PassPlugin::Load(PluginFN);
1047 PassPlugin->registerPassBuilderCallbacks(PB);
1049 Diags.
Report(diag::err_fe_unable_to_load_plugin)
1050 << PluginFN <<
toString(PassPlugin.takeError());
1055#define HANDLE_EXTENSION(Ext) \
1056 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1057#include "llvm/Support/Extension.def"
1061 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1062 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1063 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1066 PB.registerModuleAnalyses(MAM);
1067 PB.registerCGSCCAnalyses(CGAM);
1068 PB.registerFunctionAnalyses(FAM);
1069 PB.registerLoopAnalyses(LAM);
1070 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1072 ModulePassManager MPM;
1074 if (CodeGenOpts.VerifyModule)
1075 MPM.addPass(VerifierPass());
1077 if (!CodeGenOpts.DisableLLVMPasses) {
1082 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1083 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1085 if (LangOpts.ObjCAutoRefCount) {
1086 PB.registerPipelineStartEPCallback(
1087 [](ModulePassManager &MPM, OptimizationLevel Level) {
1088 if (Level != OptimizationLevel::O0)
1090 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1092 PB.registerScalarOptimizerLateEPCallback(
1093 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1094 if (Level != OptimizationLevel::O0)
1095 FPM.addPass(ObjCARCOptPass());
1105 if (IsThinLTOPostLink)
1106 PB.registerPipelineStartEPCallback(
1107 [](ModulePassManager &MPM, OptimizationLevel Level) {
1108 MPM.addPass(LowerTypeTestsPass(
1111 lowertypetests::DropTestKind::Assume));
1116 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1117 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1118 OptimizationLevel Level) {
1119 BoundsCheckingPass::Options Options;
1122 static_assert(SanitizerKind::SO_LocalBounds <=
1123 std::numeric_limits<
1124 decltype(Options.GuardKind)::value_type>
::max(),
1125 "Update type of llvm.allow.ubsan.check to represent "
1126 "SanitizerKind::SO_LocalBounds.");
1127 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1134 CodeGenOpts.SanitizeMinimalRuntime),
1138 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1141 FPM.addPass(BoundsCheckingPass(Options));
1146 if (!IsThinLTOPostLink) {
1152 if (std::optional<GCOVOptions> Options =
1154 PB.registerPipelineStartEPCallback(
1155 [
this, Options](ModulePassManager &MPM, OptimizationLevel Level) {
1159 if (std::optional<InstrProfOptions> Options =
1161 PB.registerPipelineStartEPCallback(
1162 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1163 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1169 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1170 OptimizationLevel Level,
1171 ThinOrFullLTOPhase) {
1172 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1173 MPM.addPass(ModuleMemProfilerPass());
1177 if (CodeGenOpts.FatLTO) {
1178 MPM.addPass(PB.buildFatLTODefaultPipeline(
1179 Level, PrepareForThinLTO,
1180 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1181 }
else if (PrepareForThinLTO) {
1182 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1183 }
else if (PrepareForLTO) {
1184 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1186 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1191 if (CodeGenOpts.LinkBitcodePostopt)
1192 MPM.addPass(LinkInModulesPass(BC));
1194 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1195 LangOpts.HIPStdParInterposeAlloc)
1196 MPM.addPass(HipStdParAllocationInterpositionPass());
1204 MPM.addPass(VerifierPass());
1207 CodeGenOpts.FatLTO) {
1208 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1209 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1210 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1211 CodeGenOpts.EnableSplitLTOUnit);
1218 MPM.addPass(ThinLTOBitcodeWriterPass(
1219 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1221 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1227 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1228 if (EmitLTOSummary) {
1229 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1230 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1231 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1232 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1236 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1239 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1244 if (shouldEmitUnifiedLTOModueFlag() &&
1245 !TheModule->getModuleFlag(
"UnifiedLTO"))
1246 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1253 if (PrintPipelinePasses) {
1254 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1255 auto PassName = PIC.getPassNameForClassName(ClassName);
1256 return PassName.empty() ? ClassName : PassName;
1264 PrettyStackTraceString CrashInfo(
"Optimizer");
1265 llvm::TimeTraceScope TimeScope(
"Optimizer");
1271 MPM.run(*TheModule, MAM);
1277void EmitAssemblyHelper::RunCodegenPipeline(
1278 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1279 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1283 legacy::PassManager CodeGenPasses;
1291 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1297 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1298 DwoOS ? &DwoOS->os() :
nullptr))
1309 if (PrintPipelinePasses) {
1314 PrettyStackTraceString CrashInfo(
"Code generation");
1315 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1318 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1321 CodeGenPasses.run(*TheModule);
1328 std::unique_ptr<raw_pwrite_stream> OS,
1329 BackendConsumer *BC) {
1333 CreateTargetMachine(RequiresCodeGen);
1335 if (RequiresCodeGen && !TM)
1338 TheModule->setDataLayout(TM->createDataLayout());
1341 cl::PrintOptionValues();
1343 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1344 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1345 RunCodegenPipeline(Action, OS, DwoOS);
1355 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1356 std::string SampleProfile, std::string ProfileRemapping,
1361 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1362 ModuleToDefinedGVSummaries;
1363 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1370 FunctionImporter::ImportIDTable ImportIDs;
1371 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1372 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1375 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1376 return std::make_unique<CachedFileStream>(std::move(OS),
1377 CGOpts.ObjectFilenameForDebug);
1380 if (CGOpts.SaveTempsFilePrefix !=
"") {
1381 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1383 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1384 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1389 Conf.CPU = TOpts.CPU;
1391 Conf.MAttrs = TOpts.Features;
1392 Conf.RelocModel = CGOpts.RelocationModel;
1393 std::optional<CodeGenOptLevel> OptLevelOrNone =
1394 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1395 assert(OptLevelOrNone &&
"Invalid optimization level!");
1396 Conf.CGOptLevel = *OptLevelOrNone;
1397 Conf.OptLevel = CGOpts.OptimizationLevel;
1399 Conf.SampleProfile = std::move(SampleProfile);
1400 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1401 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1402 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1405 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1406 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1407 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1410 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1413 if (CGOpts.hasProfileCSIRInstr()) {
1414 Conf.RunCSIRInstr =
true;
1416 }
else if (CGOpts.hasProfileCSIRUse()) {
1417 Conf.RunCSIRInstr =
false;
1418 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1421 Conf.ProfileRemapping = std::move(ProfileRemapping);
1422 Conf.DebugPassManager = CGOpts.DebugPassManager;
1423 Conf.VerifyEach = CGOpts.VerifyEach;
1424 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1425 Conf.RemarksFilename = CGOpts.OptRecordFile;
1426 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1427 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1428 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1429 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1432 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1437 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1438 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1443 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1444 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1455 finalizeLLVMOptimizationRemarks(M->getContext());
1457 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1458 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1459 nullptr, Conf.CodeGenOnly,
1460 nullptr, CGOpts.CmdArgs)) {
1461 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1462 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1468 StringRef TDesc, llvm::Module *M,
1471 std::unique_ptr<raw_pwrite_stream> OS,
1473 llvm::TimeTraceScope TimeScope(
"Backend");
1476 std::unique_ptr<llvm::Module> EmptyModule;
1481 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1482 if (
Error E = llvm::getModuleSummaryIndexForFile(
1485 .moveInto(CombinedIndex)) {
1486 logAllUnhandledErrors(std::move(E), errs(),
1487 "Error loading index file '" +
1495 if (CombinedIndex) {
1496 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1508 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1509 EmptyModule->setTargetTriple(M->getTargetTriple());
1510 M = EmptyModule.get();
1514 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1515 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1520 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1521 if (DLDesc != TDesc) {
1524 "expected target description '%1'");
1525 Diags.
Report(DiagID) << DLDesc << TDesc;
1533 llvm::MemoryBufferRef Buf) {
1536 llvm::embedBitcodeInModule(
1548 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1549 VFS.getBufferForFile(OffloadObject);
1550 if (ObjectOrErr.getError()) {
1552 "could not open '%0' for embedding");
1553 Diags.
Report(DiagID) << OffloadObject;
1557 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1558 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 AllocTokenOptions getAllocTokenOptions(const LangOptions &LangOpts, 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 addAllocTokenPass(const Triple &TargetTriple, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts, vfs::FileSystem &VFS)
static std::string getProfileGenName(const CodeGenOptions &CodeGenOpts)
static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts, PassBuilder &PB)
static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts)
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts)
static std::optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
static std::string flattenClangCommandLine(ArrayRef< std::string > Args, StringRef MainFilename)
Defines the Diagnostic-related interfaces.
Defines the clang::LangOptions interface.
This file provides a pass to link in Modules from a provided BackendConsumer.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static bool contains(const std::set< tok::TokenKind > &Terminators, const Token &Tok)
Defines the clang::TargetOptions class.
__DEVICE__ int max(int __a, int __b)
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
SanitizerSet SanitizeMergeHandlers
Set of sanitizer checks that can merge handlers (smaller code size at the expense of debuggability).
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
std::string BinutilsVersion
bool hasDWARFExceptions() const
bool hasProfileIRUse() const
Check if IR level profile use is on.
char CoverageVersion[4]
The version string to put into coverage files.
std::string FloatABI
The ABI to use for passing floating point arguments.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
bool hasProfileCSIRInstr() const
Check if CS IR level profile instrumentation is on.
std::string DebugPass
Enable additional debugging information.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
uint64_t LargeDataThreshold
The code model-specific large data threshold to use (-mlarge-data-threshold).
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::function< void(llvm::PassBuilder &)> > PassBuilderCallbacks
List of pass builder callbacks.
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
std::string CodeModel
The code model to use (-mcmodel).
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::vector< std::string > PassPlugins
List of dynamic shared object files to be loaded as pass plugins.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
std::vector< std::string > SanitizeCoverageAllowlistFiles
Path to allowlist file specifying which objects (files, functions) should exclusively be instrumented...
std::vector< std::string > SanitizeCoverageIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
bool hasSanitizeCoverage() const
std::string MainFileName
The user provided name for the "main file", if non-empty.
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
bool hasProfileCSIRUse() const
Check if CSIR profile use is on.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
std::vector< std::string > SanitizeMetadataIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
std::string ProfileExcludeFiles
Regexes separated by a semi-colon to filter the files to not instrument.
std::string AsSecureLogFile
The name of a file to use with .secure_log_unique directives.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
bool hasSanitizeBinaryMetadata() const
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
bool hasWasmExceptions() const
bool hasSjLjExceptions() const
SanitizerMaskCutoffs SanitizeSkipHotCutoffs
Set of thresholds in a range [0.0, 1.0]: the top hottest code responsible for the given fraction of P...
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
std::optional< double > AllowRuntimeCheckSkipHotCutoff
std::vector< std::string > CommandLineArgs
bool hasSEHExceptions() const
std::string MemoryProfileUsePath
Name of the profile file to use as input for -fmemory-profile-use.
std::vector< std::string > OffloadObjects
List of filenames passed in using the -fembed-offload-object option.
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
std::string ObjectFilenameForDebug
Output filename used in the COFF debug information.
std::string SplitDwarfOutput
Output filename for the split debug info, not used in the skeleton CU.
std::string DIBugsReportFilePath
The file to use for dumping bug report by Debugify for original debug info.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
llvm::TimerGroup & getTimerGroup() const
llvm::Timer & getFrontendTimer() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
HeaderSearchOptions & getHeaderSearchOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
@ Single
Single Threaded Environment.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
SanitizerSet Sanitize
Set of enabled sanitizers.
std::optional< llvm::AllocTokenMode > AllocTokenMode
The allocation token mode.
std::optional< uint64_t > AllocTokenMax
Maximum number of allocation tokens (0 = target SIZE_MAX), nullopt if none set (use target SIZE_MAX).
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
std::optional< std::vector< unsigned > > getAllScaled(unsigned ScalingFactor) const
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string CPU
If given, the name of the target CPU to generate code for.
llvm::EABI EABIVersion
The EABI version to use.
@ Angled
Paths for '#include <>' added by '-I'.
@ System
Like Angled, but marks system directories.
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
llvm::cl::opt< bool > ClSanitizeGuardChecks
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Diagnostic wrappers for TextAPI types for error reporting.
LLVM_ABI cl::opt< InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate
static cl::opt< PGOOptions::ColdFuncOpt > ClPGOColdFuncAttr("pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden, cl::desc("Function attribute to apply to cold functions as determined by PGO"), cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default", "Default (no attribute)"), clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize", "Mark cold functions with optsize."), clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize", "Mark cold functions with minsize."), clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone", "Mark cold functions with optnone.")))
static cl::opt< bool > ClSanitizeOnOptimizerEarlyEP("sanitizer-early-opt-ep", cl::Optional, cl::desc("Insert sanitizers on OptimizerEarlyEP."))
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.