Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NFC][CodeGen] Change CodeGenOpt::Level/CodeGenFileType into enum classes #66295

Merged
merged 4 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions clang/lib/CodeGen/BackendUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -314,12 +314,12 @@ getCodeModel(const CodeGenOptions &CodeGenOpts) {

static CodeGenFileType getCodeGenFileType(BackendAction Action) {
if (Action == Backend_EmitObj)
return CGFT_ObjectFile;
return CodeGenFileType::ObjectFile;
else if (Action == Backend_EmitMCNull)
return CGFT_Null;
return CodeGenFileType::Null;
else {
assert(Action == Backend_EmitAssembly && "Invalid action!");
return CGFT_AssemblyFile;
return CodeGenFileType::AssemblyFile;
}
}

Expand Down
12 changes: 6 additions & 6 deletions clang/lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -661,27 +661,27 @@ static bool FixupInvocation(CompilerInvocation &Invocation,

static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
DiagnosticsEngine &Diags) {
unsigned DefaultOpt = llvm::CodeGenOpt::None;
unsigned DefaultOpt = 0;
if ((IK.getLanguage() == Language::OpenCL ||
IK.getLanguage() == Language::OpenCLCXX) &&
!Args.hasArg(OPT_cl_opt_disable))
DefaultOpt = llvm::CodeGenOpt::Default;
DefaultOpt = 2;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not keen on having these as magic numbers. Surely you can
static_cast<unsigned>(CodeGenOptLevel::Default) or whatever.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Otherwise the the default is effectively defined twice in two different places.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

llvm::CodeGenOpt is for LLVM's codegen pipeline, but here it's getting overloaded to be used in clang's IR codegen. These are two different concepts where the defaults happen to have the same value.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not that different; CodeGenOpt::getLevel() just uses a static_cast to implement the inverse mapping. This direction of the conversion should be consistent IMO.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do eventually map the opt level here to a CodeGenOpt via CodeGenOpt::getLevel(), but we also use the opt level here for a bunch of other things in the clang codegen process. So whatever the "default" llvm codegen pipeline opt level is shouldn't be tied to a clang frontend opt level default.

Maybe I'm not understanding your comment.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually it looks to me like clang only cares about 0/not-0, and the specific non-zero number is irrelevant. So, internally clang codegen would be better off with a simple Optimize bool. (It looks like LangOpts does it this way already.) CodeGenOpts probably does need to track the actual user-specified level to pass down to LLVM, but it doesn't need it for its own purposes.


if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
if (A->getOption().matches(options::OPT_O0))
return llvm::CodeGenOpt::None;
return 0;

if (A->getOption().matches(options::OPT_Ofast))
return llvm::CodeGenOpt::Aggressive;
return 3;

assert(A->getOption().matches(options::OPT_O));

StringRef S(A->getValue());
if (S == "s" || S == "z")
return llvm::CodeGenOpt::Default;
return 2;

if (S == "g")
return llvm::CodeGenOpt::Less;
return 1;

return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
}
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Interpreter/DeviceOffload.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ llvm::Expected<llvm::StringRef> IncrementalCUDADeviceParser::GeneratePTX() {

llvm::legacy::PassManager PM;
if (TargetMachine->addPassesToEmitFile(PM, dest, nullptr,
llvm::CGFT_AssemblyFile)) {
llvm::CodeGenFileType::AssemblyFile)) {
return llvm::make_error<llvm::StringError>(
"NVPTX backend cannot produce PTX code.",
llvm::inconvertibleErrorCode());
Expand Down
15 changes: 8 additions & 7 deletions clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ typedef void (*LLVMFunc)(int*, int*, int*, int);
static CodeGenOpt::Level
getOptLevel(const std::vector<const char *> &ExtraArgs) {
// Find the optimization level from the command line args
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
CodeGenOpt::Level OLvl = CodeGenOpt::Level::Default;
for (auto &A : ExtraArgs) {
if (A[0] == '-' && A[1] == 'O') {
if (auto Level = CodeGenOpt::parseLevel(A[2])) {
Expand All @@ -76,16 +76,16 @@ static void RunOptimizationPasses(raw_ostream &OS, Module &M,
CodeGenOpt::Level OptLevel) {
llvm::OptimizationLevel OL;
switch (OptLevel) {
case CodeGenOpt::None:
case CodeGenOpt::Level::None:
OL = OptimizationLevel::O0;
break;
case CodeGenOpt::Less:
case CodeGenOpt::Level::Less:
OL = OptimizationLevel::O1;
break;
case CodeGenOpt::Default:
case CodeGenOpt::Level::Default:
OL = OptimizationLevel::O2;
break;
case CodeGenOpt::Aggressive:
case CodeGenOpt::Level::Aggressive:
OL = OptimizationLevel::O3;
break;
}
Expand Down Expand Up @@ -205,7 +205,8 @@ static void CreateAndRunJITFunc(const std::string &IR, CodeGenOpt::Level OLvl) {
#endif

// Figure out if we are running the optimized func or the unoptimized func
RunFuncOnInputs(f, (OLvl == CodeGenOpt::None) ? UnoptArrays : OptArrays);
RunFuncOnInputs(f,
(OLvl == CodeGenOpt::Level::None) ? UnoptArrays : OptArrays);

EE->runStaticConstructorsDestructors(true);
}
Expand All @@ -225,7 +226,7 @@ void clang_fuzzer::HandleLLVM(const std::string &IR,
std::string OptIR = OptLLVM(IR, OLvl);

CreateAndRunJITFunc(OptIR, OLvl);
CreateAndRunJITFunc(IR, CodeGenOpt::None);
CreateAndRunJITFunc(IR, CodeGenOpt::Level::None);

if (memcmp(OptArrays, UnoptArrays, kTotalSize))
ErrorAndExit("!!!BUG!!!");
Expand Down
8 changes: 5 additions & 3 deletions clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -569,8 +569,9 @@ std::unique_ptr<lto::LTO> createLTO(
};
}
Conf.PostOptModuleHook = Hook;
Conf.CGFileType =
(Triple.isNVPTX() || SaveTemps) ? CGFT_AssemblyFile : CGFT_ObjectFile;
Conf.CGFileType = (Triple.isNVPTX() || SaveTemps)
? CodeGenFileType::AssemblyFile
: CodeGenFileType::ObjectFile;

// TODO: Handle remark files
Conf.HasWholeProgramVisibility = Args.hasArg(OPT_whole_program);
Expand Down Expand Up @@ -840,7 +841,8 @@ Expected<StringRef> compileModule(Module &M) {
legacy::PassManager CodeGenPasses;
TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr, CGFT_ObjectFile))
if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr,
CodeGenFileType::ObjectFile))
return createStringError(inconvertibleErrorCode(),
"Failed to execute host backend");
CodeGenPasses.run(M);
Expand Down
4 changes: 2 additions & 2 deletions flang/lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,12 @@ static bool parseShowColorsArgs(const llvm::opt::ArgList &args,
/// Extracts the optimisation level from \a args.
static unsigned getOptimizationLevel(llvm::opt::ArgList &args,
clang::DiagnosticsEngine &diags) {
unsigned defaultOpt = llvm::CodeGenOpt::None;
unsigned defaultOpt = llvm::CodeGenOpt::Level::None;

if (llvm::opt::Arg *a =
args.getLastArg(clang::driver::options::OPT_O_Group)) {
if (a->getOption().matches(clang::driver::options::OPT_O0))
return llvm::CodeGenOpt::None;
return llvm::CodeGenOpt::Level::None;

assert(a->getOption().matches(clang::driver::options::OPT_O));

Expand Down
7 changes: 4 additions & 3 deletions flang/lib/Frontend/FrontendActions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -847,9 +847,10 @@ static void generateMachineCodeOrAssemblyImpl(clang::DiagnosticsEngine &diags,
assert(tlii && "Failed to create TargetLibraryInfo");
codeGenPasses.add(new llvm::TargetLibraryInfoWrapperPass(*tlii));

llvm::CodeGenFileType cgft = (act == BackendActionTy::Backend_EmitAssembly)
? llvm::CodeGenFileType::CGFT_AssemblyFile
: llvm::CodeGenFileType::CGFT_ObjectFile;
llvm::CodeGenFileType cgft =
(act == BackendActionTy::Backend_EmitAssembly)
? llvm::CodeGenFileType::CodeGenFileType::AssemblyFile
: llvm::CodeGenFileType::CodeGenFileType::ObjectFile;
if (tm.addPassesToEmitFile(codeGenPasses, os, nullptr, cgft)) {
unsigned diagID =
diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
Expand Down
2 changes: 1 addition & 1 deletion lld/ELF/LTO.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ static lto::Config createConfig() {
}

if (config->ltoEmitAsm) {
c.CGFileType = CGFT_AssemblyFile;
c.CGFileType = CodeGenFileType::AssemblyFile;
c.Options.MCOptions.AsmVerbose = true;
}

Expand Down
2 changes: 1 addition & 1 deletion lld/MachO/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
#include <vector>

namespace llvm::CodeGenOpt {
enum Level : int;
enum class Level : int;
} // namespace llvm::CodeGenOpt

namespace lld {
Expand Down
2 changes: 1 addition & 1 deletion lld/wasm/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
#include <optional>

namespace llvm::CodeGenOpt {
enum Level : int;
enum class Level : int;
} // namespace llvm::CodeGenOpt

namespace lld::wasm {
Expand Down
2 changes: 1 addition & 1 deletion lldb/source/Expression/IRExecutionUnit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ void IRExecutionUnit::GetRunnableInfo(Status &error, lldb::addr_t &func_addr,
.setRelocationModel(triple.isOSBinFormatMachO() ? llvm::Reloc::PIC_
: llvm::Reloc::Static)
.setMCJITMemoryManager(std::make_unique<MemoryManager>(*this))
.setOptLevel(llvm::CodeGenOpt::Less);
.setOptLevel(llvm::CodeGenOpt::Level::Less);

llvm::StringRef mArch;
llvm::StringRef mCPU;
Expand Down
2 changes: 1 addition & 1 deletion llvm/docs/OptBisect.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ skipped while still allowing correct code generation call a function to
check the opt-bisect limit before performing optimizations. Passes which
either must be run or do not modify the IR do not perform this check and are
therefore never skipped. Generally, this means analysis passes, passes
that are run at CodeGenOpt::None and passes which are required for register
that are run at CodeGenOpt::Level::None and passes which are required for register
allocation.

The -opt-bisect-limit option can be used with any tool, including front ends
Expand Down
2 changes: 1 addition & 1 deletion llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl08.rst
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ pass:
.. code-block:: c++

legacy::PassManager pass;
auto FileType = CGFT_ObjectFile;
auto FileType = CodeGenFileType::ObjectFile;

if (TargetMachine->addPassesToEmitFile(pass, dest, nullptr, FileType)) {
errs() << "TargetMachine can't emit a file of this type";
Expand Down
2 changes: 1 addition & 1 deletion llvm/examples/Kaleidoscope/Chapter8/toy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1258,7 +1258,7 @@ int main() {
}

legacy::PassManager pass;
auto FileType = CGFT_ObjectFile;
auto FileType = CodeGenFileType::ObjectFile;

if (TheTargetMachine->addPassesToEmitFile(pass, dest, nullptr, FileType)) {
errs() << "TheTargetMachine can't emit a file of this type";
Expand Down
33 changes: 18 additions & 15 deletions llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ template <typename DerivedT> class CodeGenPassBuilder {
TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;

if (!Opt.OptimizeRegAlloc)
Opt.OptimizeRegAlloc = getOptLevel() != CodeGenOpt::None;
Opt.OptimizeRegAlloc = getOptLevel() != CodeGenOpt::Level::None;
}

Error buildPipeline(ModulePassManager &MPM, MachineFunctionPassManager &MFPM,
Expand Down Expand Up @@ -597,15 +597,15 @@ void CodeGenPassBuilder<Derived>::addIRPasses(AddIRPass &addPass) const {
addPass(VerifierPass());

// Run loop strength reduction before anything else.
if (getOptLevel() != CodeGenOpt::None && !Opt.DisableLSR) {
if (getOptLevel() != CodeGenOpt::Level::None && !Opt.DisableLSR) {
addPass(createFunctionToLoopPassAdaptor(
LoopStrengthReducePass(), /*UseMemorySSA*/ true, Opt.DebugPM));
// FIXME: use -stop-after so we could remove PrintLSR
if (Opt.PrintLSR)
addPass(PrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
}

if (getOptLevel() != CodeGenOpt::None) {
if (getOptLevel() != CodeGenOpt::Level::None) {
// The MergeICmpsPass tries to create memcmp calls by grouping sequences of
// loads and compares. ExpandMemCmpPass then tries to expand those calls
// into optimally-sized loads and compares. The transforms are enabled by a
Expand All @@ -625,15 +625,16 @@ void CodeGenPassBuilder<Derived>::addIRPasses(AddIRPass &addPass) const {
addPass(UnreachableBlockElimPass());

// Prepare expensive constants for SelectionDAG.
if (getOptLevel() != CodeGenOpt::None && !Opt.DisableConstantHoisting)
if (getOptLevel() != CodeGenOpt::Level::None && !Opt.DisableConstantHoisting)
addPass(ConstantHoistingPass());

// Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
// operands with calls to the corresponding functions in a vector library.
if (getOptLevel() != CodeGenOpt::None)
if (getOptLevel() != CodeGenOpt::Level::None)
addPass(ReplaceWithVeclib());

if (getOptLevel() != CodeGenOpt::None && !Opt.DisablePartialLibcallInlining)
if (getOptLevel() != CodeGenOpt::Level::None &&
!Opt.DisablePartialLibcallInlining)
addPass(PartiallyInlineLibCallsPass());

// Instrument function entry and exit, e.g. with calls to mcount().
Expand All @@ -648,7 +649,7 @@ void CodeGenPassBuilder<Derived>::addIRPasses(AddIRPass &addPass) const {
addPass(ExpandReductionsPass());

// Convert conditional moves to conditional jumps when profitable.
if (getOptLevel() != CodeGenOpt::None && !Opt.DisableSelectOptimize)
if (getOptLevel() != CodeGenOpt::Level::None && !Opt.DisableSelectOptimize)
addPass(SelectOptimizePass());
}

Expand Down Expand Up @@ -702,7 +703,7 @@ void CodeGenPassBuilder<Derived>::addPassesToHandleExceptions(
/// before exception handling preparation passes.
template <typename Derived>
void CodeGenPassBuilder<Derived>::addCodeGenPrepare(AddIRPass &addPass) const {
if (getOptLevel() != CodeGenOpt::None && !Opt.DisableCGP)
if (getOptLevel() != CodeGenOpt::Level::None && !Opt.DisableCGP)
addPass(CodeGenPreparePass());
// TODO: Default ctor'd RewriteSymbolPass is no-op.
// addPass(RewriteSymbolPass());
Expand Down Expand Up @@ -748,7 +749,8 @@ Error CodeGenPassBuilder<Derived>::addCoreISelPasses(
(!Opt.EnableGlobalISelOption ||
*Opt.EnableGlobalISelOption == false)))
Selector = SelectorType::GlobalISel;
else if (TM.getOptLevel() == CodeGenOpt::None && TM.getO0WantsFastISel())
else if (TM.getOptLevel() == CodeGenOpt::Level::None &&
TM.getO0WantsFastISel())
Selector = SelectorType::FastISel;
else
Selector = SelectorType::SelectionDAG;
Expand Down Expand Up @@ -826,7 +828,7 @@ template <typename Derived>
Error CodeGenPassBuilder<Derived>::addMachinePasses(
AddMachinePass &addPass) const {
// Add passes that optimize machine instructions in SSA form.
if (getOptLevel() != CodeGenOpt::None) {
if (getOptLevel() != CodeGenOpt::Level::None) {
derived().addMachineSSAOptimization(addPass);
} else {
// If the target requests it, assign local variables to stack slots relative
Expand Down Expand Up @@ -855,15 +857,15 @@ Error CodeGenPassBuilder<Derived>::addMachinePasses(
addPass(RemoveRedundantDebugValuesPass());

// Insert prolog/epilog code. Eliminate abstract frame index references...
if (getOptLevel() != CodeGenOpt::None) {
if (getOptLevel() != CodeGenOpt::Level::None) {
addPass(PostRAMachineSinkingPass());
addPass(ShrinkWrapPass());
}

addPass(PrologEpilogInserterPass());

/// Add passes that optimize machine instructions after register allocation.
if (getOptLevel() != CodeGenOpt::None)
if (getOptLevel() != CodeGenOpt::Level::None)
derived().addMachineLateOptimization(addPass);

// Expand pseudo instructions before second scheduling pass.
Expand All @@ -878,7 +880,7 @@ Error CodeGenPassBuilder<Derived>::addMachinePasses(
// Second pass scheduler.
// Let Target optionally insert this pass by itself at some other
// point.
if (getOptLevel() != CodeGenOpt::None &&
if (getOptLevel() != CodeGenOpt::Level::None &&
!TM.targetSchedulesPostRAScheduling()) {
if (Opt.MISchedPostRA)
addPass(PostMachineSchedulerPass());
Expand All @@ -890,7 +892,7 @@ Error CodeGenPassBuilder<Derived>::addMachinePasses(
derived().addGCPasses(addPass);

// Basic block placement.
if (getOptLevel() != CodeGenOpt::None)
if (getOptLevel() != CodeGenOpt::Level::None)
derived().addBlockPlacement(addPass);

// Insert before XRay Instrumentation.
Expand All @@ -912,7 +914,8 @@ Error CodeGenPassBuilder<Derived>::addMachinePasses(
addPass(LiveDebugValuesPass());
addPass(MachineSanitizerBinaryMetadata());

if (TM.Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
if (TM.Options.EnableMachineOutliner &&
getOptLevel() != CodeGenOpt::Level::None &&
Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
bool RunOnAllFunctions =
(Opt.EnableMachineOutliner == RunOutliner::AlwaysOutline);
Expand Down
2 changes: 1 addition & 1 deletion llvm/include/llvm/CodeGen/GlobalISel/IRTranslator.h
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,7 @@ class IRTranslator : public MachineFunctionPass {
BranchProbability Prob = BranchProbability::getUnknown());

public:
IRTranslator(CodeGenOpt::Level OptLevel = CodeGenOpt::None);
IRTranslator(CodeGenOpt::Level OptLevel = CodeGenOpt::Level::None);

StringRef getPassName() const override { return "IRTranslator"; }

Expand Down
2 changes: 1 addition & 1 deletion llvm/include/llvm/CodeGen/GlobalISel/InstructionSelect.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class InstructionSelect : public MachineFunctionPass {
BlockFrequencyInfo *BFI = nullptr;
ProfileSummaryInfo *PSI = nullptr;

CodeGenOpt::Level OptLevel = CodeGenOpt::None;
CodeGenOpt::Level OptLevel = CodeGenOpt::Level::None;
};
} // End namespace llvm.

Expand Down
22 changes: 12 additions & 10 deletions llvm/include/llvm/CodeGen/LinkAllCodegenComponents.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,18 @@ namespace {
(void) llvm::createGreedyRegisterAllocator();
(void) llvm::createDefaultPBQPRegisterAllocator();

(void) llvm::createBURRListDAGScheduler(nullptr,
llvm::CodeGenOpt::Default);
(void) llvm::createSourceListDAGScheduler(nullptr,
llvm::CodeGenOpt::Default);
(void) llvm::createHybridListDAGScheduler(nullptr,
llvm::CodeGenOpt::Default);
(void) llvm::createFastDAGScheduler(nullptr, llvm::CodeGenOpt::Default);
(void) llvm::createDefaultScheduler(nullptr, llvm::CodeGenOpt::Default);
(void) llvm::createVLIWDAGScheduler(nullptr, llvm::CodeGenOpt::Default);

(void)llvm::createBURRListDAGScheduler(nullptr,
llvm::CodeGenOpt::Level::Default);
(void)llvm::createSourceListDAGScheduler(
nullptr, llvm::CodeGenOpt::Level::Default);
(void)llvm::createHybridListDAGScheduler(
nullptr, llvm::CodeGenOpt::Level::Default);
(void)llvm::createFastDAGScheduler(nullptr,
llvm::CodeGenOpt::Level::Default);
(void)llvm::createDefaultScheduler(nullptr,
llvm::CodeGenOpt::Level::Default);
(void)llvm::createVLIWDAGScheduler(nullptr,
llvm::CodeGenOpt::Level::Default);
}
} ForceCodegenLinking; // Force link by creating a global definition.
}
Expand Down
Loading