[lldb] [clang] [llvm] [flang] [clang] Split out DebugOptions.def into its own top-level options group. (PR #75530)

Juergen Ributzka via cfe-commits cfe-commits at lists.llvm.org
Tue Jan 23 15:48:19 PST 2024


https://github.com/ributzka updated https://github.com/llvm/llvm-project/pull/75530

>From 60e7508e9f9887658121d4dc3472225aa72cd737 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka <juergen at ributzka.de>
Date: Wed, 6 Dec 2023 10:20:21 -0800
Subject: [PATCH 1/8] [clang] Split out DebugOptions.def into its own top-level
 options group.

This change moves all debug options out of the CodeGenOptions and creates a
dedicated top-level DebugOptions data struture. All uses of the debug options
are updated to reference the new location. No functional changes are intented
with this change.
---
 clang/include/clang/Basic/CodeGenOptions.def  |   3 -
 clang/include/clang/Basic/CodeGenOptions.h    |  51 +---
 clang/include/clang/Basic/DebugOptions.def    |  15 +-
 clang/include/clang/Basic/DebugOptions.h      | 111 +++++++++
 clang/include/clang/Basic/TargetInfo.h        |   2 -
 clang/include/clang/CodeGen/BackendUtil.h     |   6 +-
 clang/include/clang/CodeGen/ModuleBuilder.h   |   3 +-
 clang/include/clang/Driver/Options.td         |  68 +++---
 clang/include/clang/Driver/ToolChain.h        |   6 +-
 .../include/clang/Frontend/CompilerInstance.h |  15 +-
 .../clang/Frontend/CompilerInvocation.h       |  41 +++-
 clang/lib/Basic/CMakeLists.txt                |   1 +
 clang/lib/Basic/CodeGenOptions.cpp            |  37 +--
 clang/lib/Basic/DebugOptions.cpp              |  40 ++++
 clang/lib/CodeGen/BackendConsumer.h           |  13 +-
 clang/lib/CodeGen/BackendUtil.cpp             | 103 ++++----
 clang/lib/CodeGen/CGBlocks.cpp                |   5 +-
 clang/lib/CodeGen/CGDebugInfo.cpp             | 220 +++++++++---------
 clang/lib/CodeGen/CGDebugInfo.h               |   4 +-
 clang/lib/CodeGen/CGDecl.cpp                  |   7 +-
 clang/lib/CodeGen/CGHLSLRuntime.cpp           |   5 +-
 clang/lib/CodeGen/CGOpenMPRuntime.cpp         |  22 +-
 clang/lib/CodeGen/CGStmt.cpp                  |   5 +-
 clang/lib/CodeGen/CGStmtOpenMP.cpp            |   7 +-
 clang/lib/CodeGen/CGVTables.cpp               |  28 +--
 clang/lib/CodeGen/CodeGenAction.cpp           | 109 +++++----
 clang/lib/CodeGen/CodeGenFunction.cpp         |   5 +-
 clang/lib/CodeGen/CodeGenModule.cpp           |  31 +--
 clang/lib/CodeGen/CodeGenModule.h             |   6 +-
 clang/lib/CodeGen/ModuleBuilder.cpp           |  18 +-
 .../ObjectFilePCHContainerOperations.cpp      |  29 +--
 clang/lib/Driver/ToolChains/Clang.cpp         |  70 +++---
 clang/lib/Driver/ToolChains/CommonArgs.cpp    |  26 +--
 clang/lib/Driver/ToolChains/CommonArgs.h      |   5 +-
 clang/lib/Driver/ToolChains/Cuda.cpp          |   6 +-
 clang/lib/Driver/ToolChains/Cuda.h            |   2 +-
 clang/lib/Driver/ToolChains/Flang.cpp         |   6 +-
 clang/lib/Driver/ToolChains/HIPSPV.cpp        |   4 +-
 clang/lib/Driver/ToolChains/HIPSPV.h          |   2 +-
 clang/lib/Driver/ToolChains/MSVC.h            |   7 +-
 clang/lib/Frontend/CompilerInstance.cpp       |  20 +-
 clang/lib/Frontend/CompilerInvocation.cpp     | 202 +++++++++-------
 .../lib/Frontend/Rewrite/FrontendActions.cpp  |   4 +-
 .../DependencyScanning/ModuleDepCollector.cpp |   4 +-
 .../clang-import-test/clang-import-test.cpp   |   4 +-
 clang/unittests/CodeGen/TestCompiler.h        |   3 +-
 .../unittests/Frontend/CodeGenActionTest.cpp  |   2 +-
 .../Frontend/CompilerInvocationTest.cpp       |  18 +-
 .../Clang/ClangExpressionParser.cpp           |   2 +-
 llvm/include/llvm/Frontend/Debug/Options.h    |   4 +-
 50 files changed, 769 insertions(+), 638 deletions(-)
 create mode 100644 clang/include/clang/Basic/DebugOptions.h
 create mode 100644 clang/lib/Basic/DebugOptions.cpp

diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def
index 2f2e45d5cf63dfa..1ed51c13ccda126 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -441,9 +441,6 @@ ENUM_CODEGENOPT(ZeroCallUsedRegs, llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind,
 /// non-deleting destructors. (No effect on Microsoft ABI.)
 CODEGENOPT(CtorDtorReturnThis, 1, 0)
 
-/// FIXME: Make DebugOptions its own top-level .def file.
-#include "DebugOptions.def"
-
 #undef CODEGENOPT
 #undef ENUM_CODEGENOPT
 #undef VALUE_CODEGENOPT
diff --git a/clang/include/clang/Basic/CodeGenOptions.h b/clang/include/clang/Basic/CodeGenOptions.h
index 3f8fe385fef3dff..fb615a3563d860f 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -15,15 +15,11 @@
 
 #include "clang/Basic/Sanitizers.h"
 #include "clang/Basic/XRayInstr.h"
-#include "llvm/ADT/FloatingPointMode.h"
-#include "llvm/Frontend/Debug/Options.h"
 #include "llvm/Frontend/Driver/CodeGenOptions.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
-#include <map>
-#include <memory>
 #include <string>
 #include <vector>
 
@@ -98,12 +94,6 @@ class CodeGenOptions : public CodeGenOptionsBase {
     IAD_Intel,
   };
 
-  enum DebugSrcHashKind {
-    DSH_MD5,
-    DSH_SHA1,
-    DSH_SHA256,
-  };
-
   // This field stores one of the allowed values for the option
   // -fbasic-block-sections=.  The allowed values with this option are:
   // {"labels", "all", "list=<file>", "none"}.
@@ -158,12 +148,6 @@ class CodeGenOptions : public CodeGenOptionsBase {
     Never,    // No loop is assumed to be finite.
   };
 
-  enum AssignmentTrackingOpts {
-    Disabled,
-    Enabled,
-    Forced,
-  };
-
   /// The code model to use (-mcmodel).
   std::string CodeModel;
 
@@ -191,22 +175,13 @@ class CodeGenOptions : public CodeGenOptionsBase {
   /// Enable additional debugging information.
   std::string DebugPass;
 
-  /// The string to embed in debug information as the current working directory.
-  std::string DebugCompilationDir;
-
   /// The string to embed in coverage mapping as the current working directory.
   std::string CoverageCompilationDir;
 
-  /// The string to embed in the debug information for the compile unit, if
-  /// non-empty.
-  std::string DwarfDebugFlags;
-
   /// The string containing the commandline for the llvm.commandline metadata,
   /// if non-empty.
   std::string RecordCommandLine;
 
-  llvm::SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap;
-
   /// Prefix replacement map for source-based code coverage to remap source
   /// file paths in coverage mapping.
   llvm::SmallVector<std::pair<std::string, std::string>, 0> CoveragePrefixMap;
@@ -214,10 +189,6 @@ class CodeGenOptions : public CodeGenOptionsBase {
   /// The ABI to use for passing floating point arguments.
   std::string FloatABI;
 
-  /// The file to use for dumping bug report by `Debugify` for original
-  /// debug info.
-  std::string DIBugsReportFilePath;
-
   /// The floating-point denormal mode to use.
   llvm::DenormalMode FPDenormalMode = llvm::DenormalMode::getIEEE();
 
@@ -248,16 +219,6 @@ class CodeGenOptions : public CodeGenOptionsBase {
   /// file, for example with -save-temps.
   std::string MainFileName;
 
-  /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
-  /// attribute in the skeleton CU.
-  std::string SplitDwarfFile;
-
-  /// Output filename for the split debug info, not used in the skeleton CU.
-  std::string SplitDwarfOutput;
-
-  /// Output filename used in the COFF debug information.
-  std::string ObjectFilenameForDebug;
-
   /// The name of the relocation model to use.
   llvm::Reloc::Model RelocationModel;
 
@@ -511,16 +472,6 @@ class CodeGenOptions : public CodeGenOptionsBase {
   /// Check if CSIR profile use is on.
   bool hasProfileCSIRUse() const { return getProfileUse() == ProfileCSIRInstr; }
 
-  /// Check if type and variable info should be emitted.
-  bool hasReducedDebugInfo() const {
-    return getDebugInfo() >= llvm::codegenoptions::DebugInfoConstructor;
-  }
-
-  /// Check if maybe unused type info should be emitted.
-  bool hasMaybeUnusedDebugInfo() const {
-    return getDebugInfo() >= llvm::codegenoptions::UnusedTypeInfo;
-  }
-
   // Check if any one of SanitizeCoverage* is enabled.
   bool hasSanitizeCoverage() const {
     return SanitizeCoverageType || SanitizeCoverageIndirectCalls ||
@@ -536,7 +487,7 @@ class CodeGenOptions : public CodeGenOptionsBase {
 
   /// Reset all of the options that are not considered when building a
   /// module.
-  void resetNonModularOptions(StringRef ModuleFormat);
+  void resetNonModularOptions();
 };
 
 }  // end namespace clang
diff --git a/clang/include/clang/Basic/DebugOptions.def b/clang/include/clang/Basic/DebugOptions.def
index 7cd3edf08a17ead..7bcbad36873c686 100644
--- a/clang/include/clang/Basic/DebugOptions.def
+++ b/clang/include/clang/Basic/DebugOptions.def
@@ -17,18 +17,17 @@
 //
 //===----------------------------------------------------------------------===//
 #ifndef DEBUGOPT
-#define DEBUGOPT(Name, Bits, Default) \
-CODEGENOPT(Name, Bits, Default)
+#   error Define the DEBUGOPT macro to handle debug options
 #endif
 
 #ifndef VALUE_DEBUGOPT
 #  define VALUE_DEBUGOPT(Name, Bits, Default) \
-VALUE_CODEGENOPT(Name, Bits, Default)
+DEBUGOPT(Name, Bits, Default)
 #endif
 
 #ifndef ENUM_DEBUGOPT
 #  define ENUM_DEBUGOPT(Name, Type, Bits, Default) \
-ENUM_CODEGENOPT(Name, Type, Bits, Default)
+DEBUGOPT(Name, Bits, Default)
 #endif
 
 #ifndef BENIGN_DEBUGOPT
@@ -94,16 +93,16 @@ DEBUGOPT(DebugFwdTemplateParams, 1, 0) ///< Whether to emit complete
                                        ///< forward declarations (versus just
                                        ///< including them in the name).
 ENUM_DEBUGOPT(DebugSimpleTemplateNames,
-              llvm::codegenoptions::DebugTemplateNamesKind, 2,
-              llvm::codegenoptions::DebugTemplateNamesKind::Full)
+              llvm::debugoptions::DebugTemplateNamesKind, 2,
+              llvm::debugoptions::DebugTemplateNamesKind::Full)
               ///< Whether to emit template parameters in the textual names of
               ///< template specializations.
 			  ///< Implies DebugFwdTemplateNames to allow decorated names to be
 			  ///< reconstructed when needed.
 
 /// The kind of generated debug info.
-ENUM_DEBUGOPT(DebugInfo, llvm::codegenoptions::DebugInfoKind, 4,
-              llvm::codegenoptions::NoDebugInfo)
+ENUM_DEBUGOPT(DebugInfo, llvm::debugoptions::DebugInfoKind, 4,
+              llvm::debugoptions::NoDebugInfo)
 
 /// Whether to generate macro debug info.
 DEBUGOPT(MacroDebugInfo, 1, 0)
diff --git a/clang/include/clang/Basic/DebugOptions.h b/clang/include/clang/Basic/DebugOptions.h
new file mode 100644
index 000000000000000..f89e43c862349bd
--- /dev/null
+++ b/clang/include/clang/Basic/DebugOptions.h
@@ -0,0 +1,111 @@
+//===--- DebugOptions.h -----------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+//  This file defines the DebugOptions interface.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_BASIC_DEBUGOPTIONS_H
+#define LLVM_CLANG_BASIC_DEBUGOPTIONS_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Frontend/Debug/Options.h"
+#include "llvm/MC/MCTargetOptions.h"
+#include "llvm/Support/Compression.h"
+#include "llvm/Target/TargetOptions.h"
+#include <string>
+
+namespace clang {
+
+/// Bitfields of DebugOptions, split out from DebugOptions to ensure
+/// that this large collection of bitfields is a trivial class type.
+class DebugOptionsBase {
+  friend class CompilerInvocation;
+  friend class CompilerInvocationBase;
+
+public:
+#define DEBUGOPT(Name, Bits, Default) unsigned Name : Bits;
+#define ENUM_DEBUGOPT(Name, Type, Bits, Default)
+#include "clang/Basic/DebugOptions.def"
+
+protected:
+#define DEBUGOPT(Name, Bits, Default)
+#define ENUM_DEBUGOPT(Name, Type, Bits, Default) unsigned Name : Bits;
+#include "clang/Basic/DebugOptions.def"
+};
+
+/// DebugOptions - Track various options which control how the debug information
+/// is generated for the backend.
+class DebugOptions : public DebugOptionsBase {
+public:
+  enum DebugSrcHashKind {
+    DSH_MD5,
+    DSH_SHA1,
+    DSH_SHA256,
+  };
+
+  /// Enable additional debugging information.
+  std::string DebugPass;
+
+  /// The string to embed in debug information as the current working directory.
+  std::string DebugCompilationDir;
+
+  /// The string to embed in the debug information for the compile unit, if
+  /// non-empty.
+  std::string DwarfDebugFlags;
+
+  enum AssignmentTrackingOpts {
+    Disabled,
+    Enabled,
+    Forced,
+  };
+
+  llvm::SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap;
+
+  /// The file to use for dumping bug report by `Debugify` for original
+  /// debug info.
+  std::string DIBugsReportFilePath;
+
+  /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
+  /// attribute in the skeleton CU.
+  std::string SplitDwarfFile;
+
+  /// Output filename for the split debug info, not used in the skeleton CU.
+  std::string SplitDwarfOutput;
+
+  /// Output filename used in the COFF debug information.
+  std::string ObjectFilenameForDebug;
+
+public:
+  // Define accessors/mutators for code generation options of enumeration type.
+#define DEBUGOPT(Name, Bits, Default)
+#define ENUM_DEBUGOPT(Name, Type, Bits, Default)                               \
+  Type get##Name() const { return static_cast<Type>(Name); }                   \
+  void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
+#include "clang/Basic/DebugOptions.def"
+
+  DebugOptions();
+
+  /// Check if type and variable info should be emitted.
+  bool hasReducedDebugInfo() const {
+    return getDebugInfo() >= llvm::debugoptions::DebugInfoConstructor;
+  }
+
+  /// Check if maybe unused type info should be emitted.
+  bool hasMaybeUnusedDebugInfo() const {
+    return getDebugInfo() >= llvm::debugoptions::UnusedTypeInfo;
+  }
+
+  /// Reset all of the options that are not considered when building a
+  /// module.
+  void resetNonModularOptions(llvm::StringRef ModuleFormat);
+};
+
+} // end namespace clang
+
+#endif
diff --git a/clang/include/clang/Basic/TargetInfo.h b/clang/include/clang/Basic/TargetInfo.h
index 3eb23ebdacf0edd..4481176158b685d 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -16,7 +16,6 @@
 
 #include "clang/Basic/AddressSpaces.h"
 #include "clang/Basic/BitmaskEnum.h"
-#include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/Specifiers.h"
@@ -48,7 +47,6 @@ struct fltSemantics;
 namespace clang {
 class DiagnosticsEngine;
 class LangOptions;
-class CodeGenOptions;
 class MacroBuilder;
 
 /// Contains information gathered from parsing the contents of TargetAttr.
diff --git a/clang/include/clang/CodeGen/BackendUtil.h b/clang/include/clang/CodeGen/BackendUtil.h
index fc8ed4f011f922f..9f3fd0b96399a47 100644
--- a/clang/include/clang/CodeGen/BackendUtil.h
+++ b/clang/include/clang/CodeGen/BackendUtil.h
@@ -28,6 +28,7 @@ namespace clang {
   class DiagnosticsEngine;
   class HeaderSearchOptions;
   class CodeGenOptions;
+  class DebugOptions;
   class TargetOptions;
   class LangOptions;
   class BackendConsumer;
@@ -43,8 +44,9 @@ namespace clang {
 
   void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &,
                          const CodeGenOptions &CGOpts,
-                         const TargetOptions &TOpts, const LangOptions &LOpts,
-                         StringRef TDesc, llvm::Module *M, BackendAction Action,
+                         const DebugOptions &DOpts, const TargetOptions &TOpts,
+                         const LangOptions &LOpts, StringRef TDesc,
+                         llvm::Module *M, BackendAction Action,
                          llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
                          std::unique_ptr<raw_pwrite_stream> OS,
                          BackendConsumer *BC = nullptr);
diff --git a/clang/include/clang/CodeGen/ModuleBuilder.h b/clang/include/clang/CodeGen/ModuleBuilder.h
index edacd82bf899db8..10ce2ecd9bb29b0 100644
--- a/clang/include/clang/CodeGen/ModuleBuilder.h
+++ b/clang/include/clang/CodeGen/ModuleBuilder.h
@@ -29,6 +29,7 @@ namespace llvm {
 
 namespace clang {
   class CodeGenOptions;
+  class DebugOptions;
   class CoverageSourceInfo;
   class Decl;
   class DiagnosticsEngine;
@@ -107,7 +108,7 @@ CodeGenerator *CreateLLVMCodeGen(DiagnosticsEngine &Diags,
                                  const HeaderSearchOptions &HeaderSearchOpts,
                                  const PreprocessorOptions &PreprocessorOpts,
                                  const CodeGenOptions &CGO,
-                                 llvm::LLVMContext &C,
+                                 const DebugOptions &DO, llvm::LLVMContext &C,
                                  CoverageSourceInfo *CoverageInfo = nullptr);
 
 } // end namespace clang
diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td
index 7f4fa33748facaf..a83f22e757e27ec 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -299,6 +299,8 @@ class DependencyOutputOpts<string base>
   : KeyPathAndMacro<"DependencyOutputOpts.", base, "DEPENDENCY_OUTPUT_"> {}
 class CodeGenOpts<string base>
   : KeyPathAndMacro<"CodeGenOpts.", base, "CODEGEN_"> {}
+class DebugOpts<string base>
+  : KeyPathAndMacro<"DebugOpts.", base, "DEBUG_"> {}
 class HeaderSearchOpts<string base>
   : KeyPathAndMacro<"HeaderSearchOpts->", base, "HEADER_SEARCH_"> {}
 class PreprocessorOpts<string base>
@@ -1658,7 +1660,7 @@ def fdebug_compilation_dir_EQ : Joined<["-"], "fdebug-compilation-dir=">,
     Group<f_Group>,
     Visibility<[ClangOption, CC1Option, CC1AsOption, CLOption, DXCOption]>,
     HelpText<"The compilation directory to embed in the debug info">,
-    MarshallingInfoString<CodeGenOpts<"DebugCompilationDir">>;
+    MarshallingInfoString<DebugOpts<"DebugCompilationDir">>;
 def fdebug_compilation_dir : Separate<["-"], "fdebug-compilation-dir">,
     Group<f_Group>,
     Visibility<[ClangOption, CC1Option, CC1AsOption, CLOption, DXCOption]>,
@@ -1671,7 +1673,7 @@ def ffile_compilation_dir_EQ : Joined<["-"], "ffile-compilation-dir=">, Group<f_
     Visibility<[ClangOption, CLOption, DXCOption]>,
     HelpText<"The compilation directory to embed in the debug info and coverage mapping.">;
 defm debug_info_for_profiling : BoolFOption<"debug-info-for-profiling",
-  CodeGenOpts<"DebugInfoForProfiling">, DefaultFalse,
+  DebugOpts<"DebugInfoForProfiling">, DefaultFalse,
   PosFlag<SetTrue, [], [ClangOption, CC1Option],
           "Emit extra debug info to make sample profile more accurate">,
   NegFlag<SetFalse>>;
@@ -2013,7 +2015,7 @@ defm dollars_in_identifiers : BoolFOption<"dollars-in-identifiers",
 def fdwarf2_cfi_asm : Flag<["-"], "fdwarf2-cfi-asm">, Group<clang_ignored_f_Group>;
 def fno_dwarf2_cfi_asm : Flag<["-"], "fno-dwarf2-cfi-asm">, Group<clang_ignored_f_Group>;
 defm dwarf_directory_asm : BoolFOption<"dwarf-directory-asm",
-  CodeGenOpts<"NoDwarfDirectoryAsm">, DefaultFalse,
+  DebugOpts<"NoDwarfDirectoryAsm">, DefaultFalse,
   NegFlag<SetTrue, [], [ClangOption, CC1Option]>,
   PosFlag<SetFalse>>;
 defm elide_constructors : BoolFOption<"elide-constructors",
@@ -4052,12 +4054,12 @@ def fdebug_types_section: Flag <["-"], "fdebug-types-section">, Group<f_Group>,
   HelpText<"Place debug types in their own section (ELF Only)">;
 def fno_debug_types_section: Flag<["-"], "fno-debug-types-section">, Group<f_Group>;
 defm debug_ranges_base_address : BoolFOption<"debug-ranges-base-address",
-  CodeGenOpts<"DebugRangesBaseAddress">, DefaultFalse,
+  DebugOpts<"DebugRangesBaseAddress">, DefaultFalse,
   PosFlag<SetTrue, [], [ClangOption, CC1Option],
           "Use DWARF base address selection entries in .debug_ranges">,
   NegFlag<SetFalse>>;
 defm split_dwarf_inlining : BoolFOption<"split-dwarf-inlining",
-  CodeGenOpts<"SplitDwarfInlining">, DefaultFalse,
+  DebugOpts<"SplitDwarfInlining">, DefaultFalse,
   NegFlag<SetFalse, [], [ClangOption]>,
   PosFlag<SetTrue, [], [ClangOption, CC1Option],
           "Provide minimal debug info in the object/executable"
@@ -4085,7 +4087,7 @@ def fmacro_prefix_map_EQ
     HelpText<"remap file source paths in predefined preprocessor macros and "
              "__builtin_FILE(). Implies -ffile-reproducible.">;
 defm force_dwarf_frame : BoolFOption<"force-dwarf-frame",
-  CodeGenOpts<"ForceDwarfFrameSection">, DefaultFalse,
+  DebugOpts<"ForceDwarfFrameSection">, DefaultFalse,
   PosFlag<SetTrue, [], [ClangOption, CC1Option],
           "Always emit a debug frame section">,
   NegFlag<SetFalse>>;
@@ -4095,7 +4097,7 @@ def femit_dwarf_unwind_EQ : Joined<["-"], "femit-dwarf-unwind=">,
   Values<"always,no-compact-unwind,default">,
   NormalizedValues<["Always", "NoCompactUnwind", "Default"]>,
   NormalizedValuesScope<"llvm::EmitDwarfUnwindType">,
-  MarshallingInfoEnum<CodeGenOpts<"EmitDwarfUnwind">, "Default">;
+  MarshallingInfoEnum<DebugOpts<"EmitDwarfUnwind">, "Default">;
 defm emit_compact_unwind_non_canonical : BoolFOption<"emit-compact-unwind-non-canonical",
   CodeGenOpts<"EmitCompactUnwindNonCanonical">, DefaultFalse,
   PosFlag<SetTrue, [], [ClangOption, CC1Option, CC1AsOption],
@@ -4139,7 +4141,7 @@ def gdwarf_5 : Flag<["-"], "gdwarf-5">, Group<g_Group>,
 def gdwarf64 : Flag<["-"], "gdwarf64">, Group<g_Group>,
   Visibility<[ClangOption, CC1Option, CC1AsOption]>,
   HelpText<"Enables DWARF64 format for ELF binaries, if debug information emission is enabled.">,
-  MarshallingInfoFlag<CodeGenOpts<"Dwarf64">>;
+  MarshallingInfoFlag<DebugOpts<"Dwarf64">>;
 def gdwarf32 : Flag<["-"], "gdwarf32">, Group<g_Group>,
   Visibility<[ClangOption, CC1Option, CC1AsOption]>,
   HelpText<"Enables DWARF32 format for ELF binaries, if debug information emission is enabled.">;
@@ -4147,19 +4149,19 @@ def gdwarf32 : Flag<["-"], "gdwarf32">, Group<g_Group>,
 def gcodeview : Flag<["-"], "gcodeview">,
   HelpText<"Generate CodeView debug information">,
   Visibility<[ClangOption, CC1Option, CC1AsOption, CLOption, DXCOption]>,
-  MarshallingInfoFlag<CodeGenOpts<"EmitCodeView">>;
+  MarshallingInfoFlag<DebugOpts<"EmitCodeView">>;
 defm codeview_ghash : BoolOption<"g", "codeview-ghash",
-  CodeGenOpts<"CodeViewGHash">, DefaultFalse,
+  DebugOpts<"CodeViewGHash">, DefaultFalse,
   PosFlag<SetTrue, [], [ClangOption, CC1Option],
           "Emit type record hashes in a .debug$H section">,
   NegFlag<SetFalse>, BothFlags<[], [ClangOption, CLOption, DXCOption]>>;
 defm codeview_command_line : BoolOption<"g", "codeview-command-line",
-  CodeGenOpts<"CodeViewCommandLine">, DefaultTrue,
+  DebugOpts<"CodeViewCommandLine">, DefaultTrue,
   PosFlag<SetTrue, [], [ClangOption], "Emit compiler path and command line into CodeView debug information">,
   NegFlag<SetFalse, [], [ClangOption], "Don't emit compiler path and command line into CodeView debug information">,
   BothFlags<[], [ClangOption, CLOption, DXCOption, CC1Option]>>;
 defm inline_line_tables : BoolGOption<"inline-line-tables",
-  CodeGenOpts<"NoInlineLineTables">, DefaultFalse,
+  DebugOpts<"NoInlineLineTables">, DefaultFalse,
   NegFlag<SetTrue, [], [ClangOption, CC1Option],
           "Don't emit inline line tables.">,
   PosFlag<SetFalse>, BothFlags<[], [ClangOption, CLOption, DXCOption]>>;
@@ -4178,14 +4180,14 @@ def gno_record_command_line : Flag<["-"], "gno-record-command-line">,
 def : Flag<["-"], "grecord-gcc-switches">, Alias<grecord_command_line>;
 def : Flag<["-"], "gno-record-gcc-switches">, Alias<gno_record_command_line>;
 defm strict_dwarf : BoolOption<"g", "strict-dwarf",
-  CodeGenOpts<"DebugStrictDwarf">, DefaultFalse,
+  DebugOpts<"DebugStrictDwarf">, DefaultFalse,
   PosFlag<SetTrue, [], [ClangOption, CC1Option],
           "Restrict DWARF features to those defined in "
           "the specified version, avoiding features from later versions.">,
   NegFlag<SetFalse>, BothFlags<[], [ClangOption, CLOption, DXCOption]>>,
   Group<g_flags_Group>;
 defm column_info : BoolOption<"g", "column-info",
-  CodeGenOpts<"DebugColumnInfo">, DefaultTrue,
+  DebugOpts<"DebugColumnInfo">, DefaultTrue,
   NegFlag<SetFalse, [], [ClangOption, CC1Option]>,
   PosFlag<SetTrue>, BothFlags<[], [ClangOption, CLOption, DXCOption]>>,
   Group<g_flags_Group>;
@@ -4207,8 +4209,8 @@ def gsrc_hash_EQ : Joined<["-"], "gsrc-hash=">,
   Group<g_flags_Group>, Visibility<[CC1Option]>,
   Values<"md5,sha1,sha256">,
   NormalizedValues<["DSH_MD5", "DSH_SHA1", "DSH_SHA256"]>,
-  NormalizedValuesScope<"CodeGenOptions">,
-  MarshallingInfoEnum<CodeGenOpts<"DebugSrcHash">, "DSH_MD5">;
+  NormalizedValuesScope<"DebugOptions">,
+  MarshallingInfoEnum<DebugOpts<"DebugSrcHash">, "DSH_MD5">;
 def gno_simple_template_names : Flag<["-"], "gno-simple-template-names">,
                                 Group<g_flags_Group>;
 def ggnu_pubnames : Flag<["-"], "ggnu-pubnames">, Group<g_flags_Group>,
@@ -4228,7 +4230,7 @@ def gz : Flag<["-"], "gz">, Alias<gz_EQ>, AliasArgs<["zlib"]>, Group<g_flags_Gro
 def gembed_source : Flag<["-"], "gembed-source">, Group<g_flags_Group>,
   Visibility<[ClangOption, CC1Option]>,
     HelpText<"Embed source text in DWARF debug sections">,
-    MarshallingInfoFlag<CodeGenOpts<"EmbedSource">>;
+    MarshallingInfoFlag<DebugOpts<"EmbedSource">>;
 def gno_embed_source : Flag<["-"], "gno-embed-source">, Group<g_flags_Group>,
     Flags<[NoXarchOption]>,
     HelpText<"Restore the default behavior of not embedding source text in DWARF debug sections">;
@@ -5254,7 +5256,7 @@ def o : JoinedOrSeparate<["-"], "o">,
 def object_file_name_EQ : Joined<["-"], "object-file-name=">,
   Visibility<[ClangOption, CC1Option, CC1AsOption, CLOption, DXCOption]>,
   HelpText<"Set the output <file> for debug infos">, MetaVarName<"<file>">,
-  MarshallingInfoString<CodeGenOpts<"ObjectFilenameForDebug">>;
+  MarshallingInfoString<DebugOpts<"ObjectFilenameForDebug">>;
 def object_file_name : Separate<["-"], "object-file-name">,
   Visibility<[ClangOption, CC1Option, CC1AsOption, CLOption, DXCOption]>,
     Alias<object_file_name_EQ>;
@@ -6740,26 +6742,26 @@ let Visibility = [CC1Option, CC1AsOption] in {
 
 def debug_info_macro : Flag<["-"], "debug-info-macro">,
   HelpText<"Emit macro debug information">,
-  MarshallingInfoFlag<CodeGenOpts<"MacroDebugInfo">>;
+  MarshallingInfoFlag<DebugOpts<"MacroDebugInfo">>;
 def default_function_attr : Separate<["-"], "default-function-attr">,
   HelpText<"Apply given attribute to all functions">,
   MarshallingInfoStringVector<CodeGenOpts<"DefaultFunctionAttrs">>;
 def dwarf_version_EQ : Joined<["-"], "dwarf-version=">,
-  MarshallingInfoInt<CodeGenOpts<"DwarfVersion">>;
+  MarshallingInfoInt<DebugOpts<"DwarfVersion">>;
 def debugger_tuning_EQ : Joined<["-"], "debugger-tuning=">,
   Values<"gdb,lldb,sce,dbx">,
   NormalizedValuesScope<"llvm::DebuggerKind">, NormalizedValues<["GDB", "LLDB", "SCE", "DBX"]>,
-  MarshallingInfoEnum<CodeGenOpts<"DebuggerTuning">, "Default">;
+  MarshallingInfoEnum<DebugOpts<"DebuggerTuning">, "Default">;
 def dwarf_debug_flags : Separate<["-"], "dwarf-debug-flags">,
   HelpText<"The string to embed in the Dwarf debug flags record.">,
-  MarshallingInfoString<CodeGenOpts<"DwarfDebugFlags">>;
+  MarshallingInfoString<DebugOpts<"DwarfDebugFlags">>;
 def record_command_line : Separate<["-"], "record-command-line">,
   HelpText<"The string to embed in the .LLVM.command.line section.">,
   MarshallingInfoString<CodeGenOpts<"RecordCommandLine">>;
 def compress_debug_sections_EQ : Joined<["-", "--"], "compress-debug-sections=">,
     HelpText<"DWARF debug sections compression type">, Values<"none,zlib,zstd">,
     NormalizedValuesScope<"llvm::DebugCompressionType">, NormalizedValues<["None", "Zlib", "Zstd"]>,
-    MarshallingInfoEnum<CodeGenOpts<"CompressDebugSections">, "None">;
+    MarshallingInfoEnum<DebugOpts<"CompressDebugSections">, "None">;
 def compress_debug_sections : Flag<["-", "--"], "compress-debug-sections">,
   Alias<compress_debug_sections_EQ>, AliasArgs<["zlib"]>;
 def mno_exec_stack : Flag<["-"], "mnoexecstack">,
@@ -6822,15 +6824,15 @@ def disable_red_zone : Flag<["-"], "disable-red-zone">,
 def dwarf_ext_refs : Flag<["-"], "dwarf-ext-refs">,
   HelpText<"Generate debug info with external references to clang modules"
            " or precompiled headers">,
-  MarshallingInfoFlag<CodeGenOpts<"DebugTypeExtRefs">>;
+  MarshallingInfoFlag<DebugOpts<"DebugTypeExtRefs">>;
 def dwarf_explicit_import : Flag<["-"], "dwarf-explicit-import">,
   HelpText<"Generate explicit import from anonymous namespace to containing"
            " scope">,
-  MarshallingInfoFlag<CodeGenOpts<"DebugExplicitImport">>;
+  MarshallingInfoFlag<DebugOpts<"DebugExplicitImport">>;
 def debug_forward_template_params : Flag<["-"], "debug-forward-template-params">,
   HelpText<"Emit complete descriptions of template parameters in forward"
            " declarations">,
-  MarshallingInfoFlag<CodeGenOpts<"DebugFwdTemplateParams">>;
+  MarshallingInfoFlag<DebugOpts<"DebugFwdTemplateParams">>;
 def fforbid_guard_variables : Flag<["-"], "fforbid-guard-variables">,
   HelpText<"Emit an error if a C++ static local initializer would need a guard variable">,
   MarshallingInfoFlag<CodeGenOpts<"ForbidGuardVariables">>;
@@ -7018,14 +7020,14 @@ def fverify_debuginfo_preserve
     : Flag<["-"], "fverify-debuginfo-preserve">,
       HelpText<"Enable Debug Info Metadata preservation testing in "
                "optimizations.">,
-      MarshallingInfoFlag<CodeGenOpts<"EnableDIPreservationVerify">>;
+      MarshallingInfoFlag<DebugOpts<"EnableDIPreservationVerify">>;
 def fverify_debuginfo_preserve_export
     : Joined<["-"], "fverify-debuginfo-preserve-export=">,
       MetaVarName<"<file>">,
       HelpText<"Export debug info (by testing original Debug Info) failures "
                "into specified (JSON) file (should be abs path as we use "
                "append mode to insert new JSON objects).">,
-      MarshallingInfoString<CodeGenOpts<"DIBugsReportFilePath">>;
+      MarshallingInfoString<DebugOpts<"DIBugsReportFilePath">>;
 def fwarn_stack_size_EQ
     : Joined<["-"], "fwarn-stack-size=">,
       MarshallingInfoInt<CodeGenOpts<"WarnStackSize">, "UINT_MAX">;
@@ -7061,10 +7063,10 @@ def fctor_dtor_return_this : Flag<["-"], "fctor-dtor-return-this">,
   MarshallingInfoFlag<CodeGenOpts<"CtorDtorReturnThis">>;
 
 def fexperimental_assignment_tracking_EQ : Joined<["-"], "fexperimental-assignment-tracking=">,
-  Group<f_Group>, CodeGenOpts<"EnableAssignmentTracking">,
-  NormalizedValuesScope<"CodeGenOptions::AssignmentTrackingOpts">,
+  Group<f_Group>, DebugOpts<"EnableAssignmentTracking">,
+  NormalizedValuesScope<"DebugOptions::AssignmentTrackingOpts">,
   Values<"disabled,enabled,forced">, NormalizedValues<["Disabled","Enabled","Forced"]>,
-  MarshallingInfoEnum<CodeGenOpts<"AssignmentTrackingMode">, "Enabled">;
+  MarshallingInfoEnum<DebugOpts<"AssignmentTrackingMode">, "Enabled">;
 
 } // let Visibility = [CC1Option]
 
@@ -7459,7 +7461,7 @@ def main_file_name : Separate<["-"], "main-file-name">,
 def split_dwarf_output : Separate<["-"], "split-dwarf-output">,
   HelpText<"File name to use for split dwarf debug info output">,
   Visibility<[CC1Option, CC1AsOption]>,
-  MarshallingInfoString<CodeGenOpts<"SplitDwarfOutput">>;
+  MarshallingInfoString<DebugOpts<"SplitDwarfOutput">>;
 
 let Visibility = [CC1Option, FC1Option] in {
 
@@ -7502,7 +7504,7 @@ def fexternc_nounwind : Flag<["-"], "fexternc-nounwind">,
   MarshallingInfoFlag<LangOpts<"ExternCNoUnwind">>;
 def split_dwarf_file : Separate<["-"], "split-dwarf-file">,
   HelpText<"Name of the split dwarf debug info file to encode in the object file">,
-  MarshallingInfoString<CodeGenOpts<"SplitDwarfFile">>;
+  MarshallingInfoString<DebugOpts<"SplitDwarfFile">>;
 def fno_wchar : Flag<["-"], "fno-wchar">,
   HelpText<"Disable C++ builtin type wchar_t">,
   MarshallingInfoNegativeFlag<LangOpts<"WChar">, cplusplus.KeyPath>,
diff --git a/clang/include/clang/Driver/ToolChain.h b/clang/include/clang/Driver/ToolChain.h
index 2d0c1f826c1728a..b210bdb31d3805d 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -557,8 +557,8 @@ class ToolChain {
   virtual void CheckObjCARC() const {}
 
   /// Get the default debug info format. Typically, this is DWARF.
-  virtual llvm::codegenoptions::DebugInfoFormat getDefaultDebugFormat() const {
-    return llvm::codegenoptions::DIF_DWARF;
+  virtual llvm::debugoptions::DebugInfoFormat getDefaultDebugFormat() const {
+    return llvm::debugoptions::DIF_DWARF;
   }
 
   /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
@@ -595,7 +595,7 @@ class ToolChain {
 
   /// Adjust debug information kind considering all passed options.
   virtual void
-  adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
+  adjustDebugInfoKind(llvm::debugoptions::DebugInfoKind &DebugInfoKind,
                       const llvm::opt::ArgList &Args) const {}
 
   /// GetExceptionModel - Return the tool chain exception model.
diff --git a/clang/include/clang/Frontend/CompilerInstance.h b/clang/include/clang/Frontend/CompilerInstance.h
index ac2f940769fbe90..e065ee351af621a 100644
--- a/clang/include/clang/Frontend/CompilerInstance.h
+++ b/clang/include/clang/Frontend/CompilerInstance.h
@@ -266,6 +266,11 @@ class CompilerInstance : public ModuleLoader {
     return Invocation->getCodeGenOpts();
   }
 
+  DebugOptions &getDebugOpts() { return Invocation->getDebugOpts(); }
+  const DebugOptions &getDebugOpts() const {
+    return Invocation->getDebugOpts();
+  }
+
   DependencyOutputOptions &getDependencyOutputOpts() {
     return Invocation->getDependencyOutputOpts();
   }
@@ -655,15 +660,13 @@ class CompilerInstance : public ModuleLoader {
   /// attached to (and, then, owned by) the returned DiagnosticsEngine
   /// object.
   ///
-  /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
+  /// \param DebugOpts If non-NULL, the debug options in use, which may be
   /// used by some diagnostics printers (for logging purposes only).
   ///
   /// \return The new object on success, or null on failure.
-  static IntrusiveRefCntPtr<DiagnosticsEngine>
-  createDiagnostics(DiagnosticOptions *Opts,
-                    DiagnosticConsumer *Client = nullptr,
-                    bool ShouldOwnClient = true,
-                    const CodeGenOptions *CodeGenOpts = nullptr);
+  static IntrusiveRefCntPtr<DiagnosticsEngine> createDiagnostics(
+      DiagnosticOptions *Opts, DiagnosticConsumer *Client = nullptr,
+      bool ShouldOwnClient = true, const DebugOptions *DebugOpts = nullptr);
 
   /// Create the file manager and replace any existing one with it.
   ///
diff --git a/clang/include/clang/Frontend/CompilerInvocation.h b/clang/include/clang/Frontend/CompilerInvocation.h
index c6528779bde7b2e..0969a6bdda067ab 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -11,6 +11,7 @@
 
 #include "clang/APINotes/APINotesOptions.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Basic/LLVM.h"
@@ -21,8 +22,8 @@
 #include "clang/Frontend/MigratorOptions.h"
 #include "clang/Frontend/PreprocessorOutputOptions.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
-#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include <memory>
 #include <string>
 
@@ -99,6 +100,9 @@ class CompilerInvocationBase {
   /// Options controlling IRgen and the backend.
   std::shared_ptr<CodeGenOptions> CodeGenOpts;
 
+  /// Options controlling debug generation.
+  std::shared_ptr<DebugOptions> DebugOpts;
+
   /// Options controlling file system operations.
   std::shared_ptr<FileSystemOptions> FSOpts;
 
@@ -137,6 +141,7 @@ class CompilerInvocationBase {
   const MigratorOptions &getMigratorOpts() const { return *MigratorOpts; }
   const APINotesOptions &getAPINotesOpts() const { return *APINotesOpts; }
   const CodeGenOptions &getCodeGenOpts() const { return *CodeGenOpts; }
+  const DebugOptions &getDebugOpts() const { return *DebugOpts; }
   const FileSystemOptions &getFileSystemOpts() const { return *FSOpts; }
   const FrontendOptions &getFrontendOpts() const { return *FrontendOpts; }
   const DependencyOutputOptions &getDependencyOutputOpts() const {
@@ -198,6 +203,10 @@ class CompilerInvocationBase {
                                   const llvm::Triple &T,
                                   const std::string &OutputFile,
                                   const LangOptions *LangOpts);
+
+  // Generate command line options from DebugOptions.
+  static void GenerateDebugArgs(const DebugOptions &Opts,
+                                ArgumentConsumer Consumer);
   /// @}
 };
 
@@ -224,19 +233,20 @@ class CompilerInvocation : public CompilerInvocationBase {
   /// @{
   // Note: These need to be pulled in manually. Otherwise, they get hidden by
   // the mutable getters with the same names.
-  using CompilerInvocationBase::getLangOpts;
-  using CompilerInvocationBase::getTargetOpts;
-  using CompilerInvocationBase::getDiagnosticOpts;
-  using CompilerInvocationBase::getHeaderSearchOpts;
-  using CompilerInvocationBase::getPreprocessorOpts;
   using CompilerInvocationBase::getAnalyzerOpts;
-  using CompilerInvocationBase::getMigratorOpts;
   using CompilerInvocationBase::getAPINotesOpts;
   using CompilerInvocationBase::getCodeGenOpts;
+  using CompilerInvocationBase::getDebugOpts;
+  using CompilerInvocationBase::getDependencyOutputOpts;
+  using CompilerInvocationBase::getDiagnosticOpts;
   using CompilerInvocationBase::getFileSystemOpts;
   using CompilerInvocationBase::getFrontendOpts;
-  using CompilerInvocationBase::getDependencyOutputOpts;
+  using CompilerInvocationBase::getHeaderSearchOpts;
+  using CompilerInvocationBase::getLangOpts;
+  using CompilerInvocationBase::getMigratorOpts;
+  using CompilerInvocationBase::getPreprocessorOpts;
   using CompilerInvocationBase::getPreprocessorOutputOpts;
+  using CompilerInvocationBase::getTargetOpts;
   /// @}
 
   /// Mutable getters.
@@ -250,6 +260,7 @@ class CompilerInvocation : public CompilerInvocationBase {
   MigratorOptions &getMigratorOpts() { return *MigratorOpts; }
   APINotesOptions &getAPINotesOpts() { return *APINotesOpts; }
   CodeGenOptions &getCodeGenOpts() { return *CodeGenOpts; }
+  DebugOptions &getDebugOpts() { return *DebugOpts; }
   FileSystemOptions &getFileSystemOpts() { return *FSOpts; }
   FrontendOptions &getFrontendOpts() { return *FrontendOpts; }
   DependencyOutputOptions &getDependencyOutputOpts() {
@@ -334,11 +345,18 @@ class CompilerInvocation : public CompilerInvocationBase {
                             DiagnosticsEngine &Diags);
 
   /// Parse command line options that map to CodeGenOptions.
-  static bool ParseCodeGenArgs(CodeGenOptions &Opts, llvm::opt::ArgList &Args,
-                               InputKind IK, DiagnosticsEngine &Diags,
-                               const llvm::Triple &T,
+  static bool ParseCodeGenArgs(CodeGenOptions &Opts, DebugOptions &DebugOpts,
+                               llvm::opt::ArgList &Args, InputKind IK,
+                               DiagnosticsEngine &Diags, const llvm::Triple &T,
                                const std::string &OutputFile,
                                const LangOptions &LangOptsRef);
+
+  /// Parse command line options that map to DebugOptions.
+  static bool ParseDebugArgs(DebugOptions &Opts, llvm::opt::ArgList &Args,
+                             InputKind IK, DiagnosticsEngine &Diags,
+                             const llvm::Triple &T,
+                             const std::string &OutputFile,
+                             const LangOptions &LangOptsRef);
 };
 
 /// Same as \c CompilerInvocation, but with copy-on-write optimization.
@@ -377,6 +395,7 @@ class CowCompilerInvocation : public CompilerInvocationBase {
   MigratorOptions &getMutMigratorOpts();
   APINotesOptions &getMutAPINotesOpts();
   CodeGenOptions &getMutCodeGenOpts();
+  DebugOptions &getMutDebugOpts();
   FileSystemOptions &getMutFileSystemOpts();
   FrontendOptions &getMutFrontendOpts();
   DependencyOutputOptions &getMutDependencyOutputOpts();
diff --git a/clang/lib/Basic/CMakeLists.txt b/clang/lib/Basic/CMakeLists.txt
index 2e218ba7c84ccab..b93c1b9cbeb87de 100644
--- a/clang/lib/Basic/CMakeLists.txt
+++ b/clang/lib/Basic/CMakeLists.txt
@@ -62,6 +62,7 @@ add_clang_library(clangBasic
   CodeGenOptions.cpp
   Cuda.cpp
   DarwinSDKInfo.cpp
+  DebugOptions.cpp
   Diagnostic.cpp
   DiagnosticIDs.cpp
   DiagnosticOptions.cpp
diff --git a/clang/lib/Basic/CodeGenOptions.cpp b/clang/lib/Basic/CodeGenOptions.cpp
index 79d715305ef20b7..0e5a9b845d9542a 100644
--- a/clang/lib/Basic/CodeGenOptions.cpp
+++ b/clang/lib/Basic/CodeGenOptions.cpp
@@ -11,48 +11,15 @@
 
 namespace clang {
 
-CodeGenOptions::CodeGenOptions() {
-#define CODEGENOPT(Name, Bits, Default) Name = Default;
-#define ENUM_CODEGENOPT(Name, Type, Bits, Default) set##Name(Default);
-#include "clang/Basic/CodeGenOptions.def"
+CodeGenOptions::CodeGenOptions() { resetNonModularOptions(); }
 
-  RelocationModel = llvm::Reloc::PIC_;
-  memcpy(CoverageVersion, "408*", 4);
-}
-
-void CodeGenOptions::resetNonModularOptions(StringRef ModuleFormat) {
-  // First reset all CodeGen options only. The Debug options are handled later.
-#define DEBUGOPT(Name, Bits, Default)
-#define VALUE_DEBUGOPT(Name, Bits, Default)
-#define ENUM_DEBUGOPT(Name, Type, Bits, Default)
+void CodeGenOptions::resetNonModularOptions() {
 #define CODEGENOPT(Name, Bits, Default) Name = Default;
 #define ENUM_CODEGENOPT(Name, Type, Bits, Default) set##Name(Default);
 // Do not reset AST affecting code generation options.
 #define AFFECTING_VALUE_CODEGENOPT(Name, Bits, Default)
 #include "clang/Basic/CodeGenOptions.def"
 
-  // Next reset all debug options that can always be reset, because they never
-  // affect the PCM.
-#define DEBUGOPT(Name, Bits, Default)
-#define VALUE_DEBUGOPT(Name, Bits, Default)
-#define ENUM_DEBUGOPT(Name, Type, Bits, Default)
-#define BENIGN_DEBUGOPT(Name, Bits, Default) Name = Default;
-#define BENIGN_VALUE_DEBUGOPT(Name, Bits, Default) Name = Default;
-#define BENIGN_ENUM_DEBUGOPT(Name, Type, Bits, Default) set##Name(Default);
-#include "clang/Basic/DebugOptions.def"
-
-  // Conditionally reset debug options that only matter when the debug info is
-  // emitted into the PCM (-gmodules).
-  if (ModuleFormat == "raw" && !DebugTypeExtRefs) {
-#define DEBUGOPT(Name, Bits, Default) Name = Default;
-#define VALUE_DEBUGOPT(Name, Bits, Default) Name = Default;
-#define ENUM_DEBUGOPT(Name, Type, Bits, Default) set##Name(Default);
-#define BENIGN_DEBUGOPT(Name, Bits, Default)
-#define BENIGN_VALUE_DEBUGOPT(Name, Bits, Default)
-#define BENIGN_ENUM_DEBUGOPT(Name, Type, Bits, Default)
-#include "clang/Basic/DebugOptions.def"
-  }
-
   RelocationModel = llvm::Reloc::PIC_;
   memcpy(CoverageVersion, "408*", 4);
 }
diff --git a/clang/lib/Basic/DebugOptions.cpp b/clang/lib/Basic/DebugOptions.cpp
new file mode 100644
index 000000000000000..26c706a3b367bad
--- /dev/null
+++ b/clang/lib/Basic/DebugOptions.cpp
@@ -0,0 +1,40 @@
+//===--- DebugOptions.cpp -------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Basic/DebugOptions.h"
+
+namespace clang {
+
+DebugOptions::DebugOptions() {
+#define DEBUGOPT(Name, Bits, Default) Name = Default;
+#define ENUM_DEBUGOPT(Name, Type, Bits, Default) set##Name(Default);
+#include "clang/Basic/DebugOptions.def"
+}
+
+void DebugOptions::resetNonModularOptions(llvm::StringRef ModuleFormat) {
+  // First reset all debug options that can always be reset, because they never
+  // affect the PCM.
+#define DEBUGOPT(Name, Bits, Default)
+#define BENIGN_DEBUGOPT(Name, Bits, Default) Name = Default;
+#define BENIGN_VALUE_DEBUGOPT(Name, Bits, Default) Name = Default;
+#define BENIGN_ENUM_DEBUGOPT(Name, Type, Bits, Default) set##Name(Default);
+#include "clang/Basic/DebugOptions.def"
+
+  // Conditionally reset debug options that only matter when the debug info is
+  // emitted into the PCM (-gmodules).
+  if (ModuleFormat == "raw" && !DebugTypeExtRefs) {
+#define DEBUGOPT(Name, Bits, Default) Name = Default;
+#define ENUM_DEBUGOPT(Name, Type, Bits, Default) set##Name(Default);
+#define BENIGN_DEBUGOPT(Name, Bits, Default)
+#define BENIGN_VALUE_DEBUGOPT(Name, Bits, Default)
+#define BENIGN_ENUM_DEBUGOPT(Name, Type, Bits, Default)
+#include "clang/Basic/DebugOptions.def"
+  }
+}
+
+} // end namespace clang
diff --git a/clang/lib/CodeGen/BackendConsumer.h b/clang/lib/CodeGen/BackendConsumer.h
index 72a814cd43d738d..0b4229c3cd18cd9 100644
--- a/clang/lib/CodeGen/BackendConsumer.h
+++ b/clang/lib/CodeGen/BackendConsumer.h
@@ -32,6 +32,7 @@ class BackendConsumer : public ASTConsumer {
   BackendAction Action;
   const HeaderSearchOptions &HeaderSearchOpts;
   const CodeGenOptions &CodeGenOpts;
+  const DebugOptions &DebugOpts;
   const TargetOptions &TargetOpts;
   const LangOptions &LangOpts;
   std::unique_ptr<raw_pwrite_stream> AsmOutStream;
@@ -74,8 +75,9 @@ class BackendConsumer : public ASTConsumer {
                   const HeaderSearchOptions &HeaderSearchOpts,
                   const PreprocessorOptions &PPOpts,
                   const CodeGenOptions &CodeGenOpts,
-                  const TargetOptions &TargetOpts,
-                  const LangOptions &LangOpts, const std::string &InFile,
+                  const DebugOptions &DebugOpts,
+                  const TargetOptions &TargetOpts, const LangOptions &LangOpts,
+                  const std::string &InFile,
                   SmallVector<LinkModule, 4> LinkModules,
                   std::unique_ptr<raw_pwrite_stream> OS, llvm::LLVMContext &C,
                   CoverageSourceInfo *CoverageInfo = nullptr);
@@ -88,9 +90,10 @@ class BackendConsumer : public ASTConsumer {
                   const HeaderSearchOptions &HeaderSearchOpts,
                   const PreprocessorOptions &PPOpts,
                   const CodeGenOptions &CodeGenOpts,
-                  const TargetOptions &TargetOpts,
-                  const LangOptions &LangOpts, llvm::Module *Module,
-                  SmallVector<LinkModule, 4> LinkModules, llvm::LLVMContext &C,
+                  const DebugOptions &DebugOpts,
+                  const TargetOptions &TargetOpts, const LangOptions &LangOpts,
+                  llvm::Module *Module, SmallVector<LinkModule, 4> LinkModules,
+                  llvm::LLVMContext &C,
                   CoverageSourceInfo *CoverageInfo = nullptr);
 
   llvm::Module *getModule() const;
diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index a6142d99f3b688d..395463c3c685050 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -10,6 +10,7 @@
 #include "BackendConsumer.h"
 #include "LinkInModulesPass.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/TargetOptions.h"
@@ -124,6 +125,7 @@ class EmitAssemblyHelper {
   DiagnosticsEngine &Diags;
   const HeaderSearchOptions &HSOpts;
   const CodeGenOptions &CodeGenOpts;
+  const DebugOptions &DebugOpts;
   const clang::TargetOptions &TargetOpts;
   const LangOptions &LangOpts;
   llvm::Module *TheModule;
@@ -189,12 +191,13 @@ class EmitAssemblyHelper {
 public:
   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
                      const HeaderSearchOptions &HeaderSearchOpts,
-                     const CodeGenOptions &CGOpts,
+                     const CodeGenOptions &CGOpts, const DebugOptions &DOpts,
                      const clang::TargetOptions &TOpts,
                      const LangOptions &LOpts, llvm::Module *M,
                      IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
-        TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), VFS(std::move(VFS)),
+        DebugOpts(DOpts), TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
+        VFS(std::move(VFS)),
         CodeGenerationTime("codegen", "Code Generation Time"),
         TargetTriple(TheModule->getTargetTriple()) {}
 
@@ -305,6 +308,7 @@ static bool actionRequiresCodeGen(BackendAction Action) {
 static bool initTargetOptions(DiagnosticsEngine &Diags,
                               llvm::TargetOptions &Options,
                               const CodeGenOptions &CodeGenOpts,
+                              const DebugOptions &DebugOpts,
                               const clang::TargetOptions &TargetOpts,
                               const LangOptions &LangOpts,
                               const HeaderSearchOptions &HSOpts) {
@@ -348,7 +352,7 @@ static bool initTargetOptions(DiagnosticsEngine &Diags,
       llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
   Options.UseInitArray = CodeGenOpts.UseInitArray;
   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
-  Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
+  Options.CompressDebugSections = DebugOpts.getCompressDebugSections();
   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
 
   // Set EABI version.
@@ -402,17 +406,17 @@ static bool initTargetOptions(DiagnosticsEngine &Diags,
       CodeGenOpts.UniqueBasicBlockSectionNames;
   Options.TLSSize = CodeGenOpts.TLSSize;
   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
-  Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
+  Options.DebuggerTuning = DebugOpts.getDebuggerTuning();
   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
   Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
   Options.EmitAddrsig = CodeGenOpts.Addrsig;
-  Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
+  Options.ForceDwarfFrameSection = DebugOpts.ForceDwarfFrameSection;
   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
   Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
   Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
   Options.LoopAlignment = CodeGenOpts.LoopAlignment;
-  Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
-  Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
+  Options.DebugStrictDwarf = DebugOpts.DebugStrictDwarf;
+  Options.ObjectFilenameForDebug = DebugOpts.ObjectFilenameForDebug;
   Options.Hotpatch = CodeGenOpts.HotPatch;
   Options.JMCInstrument = CodeGenOpts.JMCInstrument;
   Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
@@ -432,14 +436,14 @@ static bool initTargetOptions(DiagnosticsEngine &Diags,
     break;
   }
 
-  Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
-  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
+  Options.MCOptions.SplitDwarfFile = DebugOpts.SplitDwarfFile;
+  Options.MCOptions.EmitDwarfUnwind = DebugOpts.getEmitDwarfUnwind();
   Options.MCOptions.EmitCompactUnwindNonCanonical =
       CodeGenOpts.EmitCompactUnwindNonCanonical;
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
   Options.MCOptions.MCUseDwarfDirectory =
-      CodeGenOpts.NoDwarfDirectoryAsm
+      DebugOpts.NoDwarfDirectoryAsm
           ? llvm::MCTargetOptions::DisableDwarfDirectory
           : llvm::MCTargetOptions::EnableDwarfDirectory;
   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
@@ -448,7 +452,7 @@ static bool initTargetOptions(DiagnosticsEngine &Diags,
   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
-  Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
+  Options.MCOptions.Dwarf64 = DebugOpts.Dwarf64;
   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
   Options.MCOptions.ABIName = TargetOpts.ABI;
   for (const auto &Entry : HSOpts.UserEntries)
@@ -543,8 +547,8 @@ void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
   CodeGenOptLevel OptLevel = *OptLevelOrNone;
 
   llvm::TargetOptions Options;
-  if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
-                         HSOpts))
+  if (!initTargetOptions(Diags, Options, CodeGenOpts, DebugOpts, TargetOpts,
+                         LangOpts, HSOpts))
     return;
   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
                                           Options, RM, CM, OptLevel));
@@ -746,7 +750,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
         CodeGenOpts.InstrProfileOutput.empty() ? getDefaultProfileGenName()
                                                : CodeGenOpts.InstrProfileOutput,
         "", "", CodeGenOpts.MemoryProfileUsePath, nullptr, PGOOptions::IRInstr,
-        PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling,
+        PGOOptions::NoCSAction, DebugOpts.DebugInfoForProfiling,
         /*PseudoProbeForProfiling=*/false, CodeGenOpts.AtomicProfileUpdate);
   else if (CodeGenOpts.hasProfileIRUse()) {
     // -fprofile-use.
@@ -755,25 +759,25 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
     PGOOpt = PGOOptions(
         CodeGenOpts.ProfileInstrumentUsePath, "",
         CodeGenOpts.ProfileRemappingFile, CodeGenOpts.MemoryProfileUsePath, VFS,
-        PGOOptions::IRUse, CSAction, CodeGenOpts.DebugInfoForProfiling);
+        PGOOptions::IRUse, CSAction, DebugOpts.DebugInfoForProfiling);
   } else if (!CodeGenOpts.SampleProfileFile.empty())
     // -fprofile-sample-use
     PGOOpt = PGOOptions(
         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
         CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse,
-        PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling,
+        PGOOptions::NoCSAction, DebugOpts.DebugInfoForProfiling,
         CodeGenOpts.PseudoProbeForProfiling);
   else if (!CodeGenOpts.MemoryProfileUsePath.empty())
     // -fmemory-profile-use (without any of the above options)
     PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, VFS,
                         PGOOptions::NoAction, PGOOptions::NoCSAction,
-                        CodeGenOpts.DebugInfoForProfiling);
+                        DebugOpts.DebugInfoForProfiling);
   else if (CodeGenOpts.PseudoProbeForProfiling)
     // -fpseudo-probe-for-profiling
     PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
                         PGOOptions::NoAction, PGOOptions::NoCSAction,
-                        CodeGenOpts.DebugInfoForProfiling, true);
-  else if (CodeGenOpts.DebugInfoForProfiling)
+                        DebugOpts.DebugInfoForProfiling, true);
+  else if (DebugOpts.DebugInfoForProfiling)
     // -fdebug-info-for-profiling
     PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
                         PGOOptions::NoAction, PGOOptions::NoCSAction, true);
@@ -799,7 +803,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
                          ? getDefaultProfileGenName()
                          : CodeGenOpts.InstrProfileOutput,
                      "", /*MemoryProfile=*/"", nullptr, PGOOptions::NoAction,
-                     PGOOptions::CSIRInstr, CodeGenOpts.DebugInfoForProfiling);
+                     PGOOptions::CSIRInstr, DebugOpts.DebugInfoForProfiling);
   }
   if (TM)
     TM->setPGOOption(PGOOpt);
@@ -835,18 +839,18 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
 
   // Handle the assignment tracking feature options.
-  switch (CodeGenOpts.getAssignmentTrackingMode()) {
-  case CodeGenOptions::AssignmentTrackingOpts::Forced:
+  switch (DebugOpts.getAssignmentTrackingMode()) {
+  case DebugOptions::AssignmentTrackingOpts::Forced:
     PB.registerPipelineStartEPCallback(
         [&](ModulePassManager &MPM, OptimizationLevel Level) {
           MPM.addPass(AssignmentTrackingPass());
         });
     break;
-  case CodeGenOptions::AssignmentTrackingOpts::Enabled:
+  case DebugOptions::AssignmentTrackingOpts::Enabled:
     // Disable assignment tracking in LTO builds for now as the performance
     // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
     if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
-        CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
+        DebugOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
       PB.registerPipelineStartEPCallback(
           [&](ModulePassManager &MPM, OptimizationLevel Level) {
             // Only use assignment tracking if optimisations are enabled.
@@ -855,20 +859,20 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
           });
     }
     break;
-  case CodeGenOptions::AssignmentTrackingOpts::Disabled:
+  case DebugOptions::AssignmentTrackingOpts::Disabled:
     break;
   }
 
   // Enable verify-debuginfo-preserve-each for new PM.
   DebugifyEachInstrumentation Debugify;
   DebugInfoPerPass DebugInfoBeforePass;
-  if (CodeGenOpts.EnableDIPreservationVerify) {
+  if (DebugOpts.EnableDIPreservationVerify) {
     Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
     Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
 
-    if (!CodeGenOpts.DIBugsReportFilePath.empty())
+    if (!DebugOpts.DIBugsReportFilePath.empty())
       Debugify.setOrigDIVerifyBugsReportFilePath(
-          CodeGenOpts.DIBugsReportFilePath);
+          DebugOpts.DIBugsReportFilePath);
     Debugify.registerCallbacks(PIC, MAM);
   }
   // Attempt to load pass plugins and register their callbacks with PB.
@@ -1116,8 +1120,8 @@ void EmitAssemblyHelper::RunCodegenPipeline(
   case Backend_EmitObj:
     CodeGenPasses.add(
         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
-    if (!CodeGenOpts.SplitDwarfOutput.empty()) {
-      DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
+    if (!DebugOpts.SplitDwarfOutput.empty()) {
+      DwoOS = openOutputFile(DebugOpts.SplitDwarfOutput);
       if (!DwoOS)
         return;
     }
@@ -1171,13 +1175,14 @@ void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
     DwoOS->keep();
 }
 
-static void runThinLTOBackend(
-    DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex,
-    llvm::Module *M, const HeaderSearchOptions &HeaderOpts,
-    const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
-    const LangOptions &LOpts, std::unique_ptr<raw_pwrite_stream> OS,
-    std::string SampleProfile, std::string ProfileRemapping,
-    BackendAction Action) {
+static void
+runThinLTOBackend(DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex,
+                  llvm::Module *M, const HeaderSearchOptions &HeaderOpts,
+                  const CodeGenOptions &CGOpts, const DebugOptions &DOpts,
+                  const clang::TargetOptions &TOpts, const LangOptions &LOpts,
+                  std::unique_ptr<raw_pwrite_stream> OS,
+                  std::string SampleProfile, std::string ProfileRemapping,
+                  BackendAction Action) {
   DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
       ModuleToDefinedGVSummaries;
   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
@@ -1193,7 +1198,7 @@ static void runThinLTOBackend(
 
   auto AddStream = [&](size_t Task, const Twine &ModuleName) {
     return std::make_unique<CachedFileStream>(std::move(OS),
-                                              CGOpts.ObjectFilenameForDebug);
+                                              DOpts.ObjectFilenameForDebug);
   };
   lto::Config Conf;
   if (CGOpts.SaveTempsFilePrefix != "") {
@@ -1214,7 +1219,8 @@ static void runThinLTOBackend(
   assert(OptLevelOrNone && "Invalid optimization level!");
   Conf.CGOptLevel = *OptLevelOrNone;
   Conf.OptLevel = CGOpts.OptimizationLevel;
-  initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
+  initTargetOptions(Diags, Conf.Options, CGOpts, DOpts, TOpts, LOpts,
+                    HeaderOpts);
   Conf.SampleProfile = std::move(SampleProfile);
   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
   // For historical reasons, loop interleaving is set to mirror setting for loop
@@ -1242,8 +1248,8 @@ static void runThinLTOBackend(
   Conf.RemarksFilename = CGOpts.OptRecordFile;
   Conf.RemarksPasses = CGOpts.OptRecordPasses;
   Conf.RemarksFormat = CGOpts.OptRecordFormat;
-  Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
-  Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
+  Conf.SplitDwarfFile = DOpts.SplitDwarfFile;
+  Conf.SplitDwarfOutput = DOpts.SplitDwarfOutput;
   switch (Action) {
   case Backend_EmitNothing:
     Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) {
@@ -1278,9 +1284,10 @@ static void runThinLTOBackend(
 
 void clang::EmitBackendOutput(
     DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderOpts,
-    const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts,
-    const LangOptions &LOpts, StringRef TDesc, llvm::Module *M,
-    BackendAction Action, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
+    const CodeGenOptions &CGOpts, const DebugOptions &DOpts,
+    const clang::TargetOptions &TOpts, const LangOptions &LOpts,
+    StringRef TDesc, llvm::Module *M, BackendAction Action,
+    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
     std::unique_ptr<raw_pwrite_stream> OS, BackendConsumer *BC) {
 
   llvm::TimeTraceScope TimeScope("Backend");
@@ -1307,8 +1314,9 @@ void clang::EmitBackendOutput(
     if (CombinedIndex) {
       if (!CombinedIndex->skipModuleByDistributedBackend()) {
         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
-                          TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
-                          CGOpts.ProfileRemappingFile, Action);
+                          DOpts, TOpts, LOpts, std::move(OS),
+                          CGOpts.SampleProfileFile, CGOpts.ProfileRemappingFile,
+                          Action);
         return;
       }
       // Distributed indexing detected that nothing from the module is needed
@@ -1323,7 +1331,8 @@ void clang::EmitBackendOutput(
     }
   }
 
-  EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M, VFS);
+  EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, DOpts, TOpts, LOpts,
+                               M, VFS);
   AsmHelper.EmitAssembly(Action, std::move(OS), BC);
 
   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
diff --git a/clang/lib/CodeGen/CGBlocks.cpp b/clang/lib/CodeGen/CGBlocks.cpp
index 0cbace7b7f7bbd5..d88fe8d9b35c9f2 100644
--- a/clang/lib/CodeGen/CGBlocks.cpp
+++ b/clang/lib/CodeGen/CGBlocks.cpp
@@ -21,6 +21,7 @@
 #include "TargetInfo.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/CodeGen/ConstantInitBuilder.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/IR/DataLayout.h"
@@ -1380,7 +1381,7 @@ void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
   Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
   Builder.CreateStore(arg, alloc);
   if (CGDebugInfo *DI = getDebugInfo()) {
-    if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
+    if (CGM.getDebugOpts().hasReducedDebugInfo()) {
       DI->setLocation(D->getLocation());
       DI->EmitDeclareOfBlockLiteralArgVariable(
           *BlockInfo, D->getName(), argNum,
@@ -1550,7 +1551,7 @@ llvm::Function *CodeGenFunction::GenerateBlockFunction(
       const VarDecl *variable = CI.getVariable();
       DI->EmitLocation(Builder, variable->getLocation());
 
-      if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
+      if (CGM.getDebugOpts().hasReducedDebugInfo()) {
         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
         if (capture.isConstant()) {
           auto addr = LocalDeclMap.find(variable)->second;
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp
index 0f3f684d61dc943..a17401f2d0a31d3 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -29,6 +29,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/VTableBuilder.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/Version.h"
@@ -70,8 +71,8 @@ static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
 }
 
 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
-    : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
-      DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
+    : CGM(CGM), DebugKind(CGM.getDebugOpts().getDebugInfo()),
+      DebugTypeExtRefs(CGM.getDebugOpts().DebugTypeExtRefs),
       DBuilder(CGM.getModule()) {
   CreateCompileUnit();
 }
@@ -238,7 +239,7 @@ PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
   // particular, we can't have spaces between arguments of standard templates
   // like basic_string and vector, but we must have spaces between consecutive
   // angle brackets that close nested template argument lists.
-  if (CGM.getCodeGenOpts().EmitCodeView) {
+  if (CGM.getDebugOpts().EmitCodeView) {
     PP.MSVCFormatting = true;
     PP.SplitTemplateClosers = true;
   } else {
@@ -304,7 +305,7 @@ StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
   // The CodeView printer in LLVM wants to see the names of unnamed types
   // because they need to have a unique identifier.
   // These names are used to reconstruct the fully qualified type names.
-  if (CGM.getCodeGenOpts().EmitCodeView) {
+  if (CGM.getDebugOpts().EmitCodeView) {
     if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
       assert(RD->getDeclContext() == D->getDeclContext() &&
              "Typedef should not be in another decl context!");
@@ -349,8 +350,7 @@ std::optional<llvm::DIFile::ChecksumKind>
 CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {
   Checksum.clear();
 
-  if (!CGM.getCodeGenOpts().EmitCodeView &&
-      CGM.getCodeGenOpts().DwarfVersion < 5)
+  if (!CGM.getDebugOpts().EmitCodeView && CGM.getDebugOpts().DwarfVersion < 5)
     return std::nullopt;
 
   SourceManager &SM = CGM.getContext().getSourceManager();
@@ -359,14 +359,14 @@ CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {
     return std::nullopt;
 
   auto Data = llvm::arrayRefFromStringRef(MemBuffer->getBuffer());
-  switch (CGM.getCodeGenOpts().getDebugSrcHash()) {
-  case clang::CodeGenOptions::DSH_MD5:
+  switch (CGM.getDebugOpts().getDebugSrcHash()) {
+  case clang::DebugOptions::DSH_MD5:
     llvm::toHex(llvm::MD5::hash(Data), /*LowerCase=*/true, Checksum);
     return llvm::DIFile::CSK_MD5;
-  case clang::CodeGenOptions::DSH_SHA1:
+  case clang::DebugOptions::DSH_SHA1:
     llvm::toHex(llvm::SHA1::hash(Data), /*LowerCase=*/true, Checksum);
     return llvm::DIFile::CSK_SHA1;
-  case clang::CodeGenOptions::DSH_SHA256:
+  case clang::DebugOptions::DSH_SHA256:
     llvm::toHex(llvm::SHA256::hash(Data), /*LowerCase=*/true, Checksum);
     return llvm::DIFile::CSK_SHA256;
   }
@@ -375,7 +375,7 @@ CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {
 
 std::optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
                                                 FileID FID) {
-  if (!CGM.getCodeGenOpts().EmbedSource)
+  if (!CGM.getDebugOpts().EmbedSource)
     return std::nullopt;
 
   bool SourceInvalid = false;
@@ -472,7 +472,7 @@ llvm::DIFile *CGDebugInfo::createFile(
 
 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
   SmallString<256> P = Path;
-  for (auto &[From, To] : llvm::reverse(CGM.getCodeGenOpts().DebugPrefixMap))
+  for (auto &[From, To] : llvm::reverse(CGM.getDebugOpts().DebugPrefixMap))
     if (llvm::sys::path::replace_path_prefix(P, From, To))
       break;
   return P.str().str();
@@ -487,7 +487,7 @@ unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
 
 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
   // We may not want column information at all.
-  if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
+  if (!Force && !CGM.getDebugOpts().DebugColumnInfo)
     return 0;
 
   // If the location is invalid then use the current column.
@@ -499,8 +499,8 @@ unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
 }
 
 StringRef CGDebugInfo::getCurrentDirname() {
-  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
-    return CGM.getCodeGenOpts().DebugCompilationDir;
+  if (!CGM.getDebugOpts().DebugCompilationDir.empty())
+    return CGM.getDebugOpts().DebugCompilationDir;
 
   if (!CWDName.empty())
     return CWDName;
@@ -526,6 +526,7 @@ void CGDebugInfo::CreateCompileUnit() {
   // Get absolute path name.
   SourceManager &SM = CGM.getContext().getSourceManager();
   auto &CGO = CGM.getCodeGenOpts();
+  auto &DO = CGM.getDebugOpts();
   const LangOptions &LO = CGM.getLangOpts();
   std::string MainFileName = CGO.MainFileName;
   if (MainFileName.empty())
@@ -570,7 +571,7 @@ void CGDebugInfo::CreateCompileUnit() {
   if (LO.CPlusPlus) {
     if (LO.ObjC)
       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
-    else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)
+    else if (DO.DebugStrictDwarf && DO.DwarfVersion < 5)
       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
     else if (LO.CPlusPlus14)
       LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
@@ -580,13 +581,12 @@ void CGDebugInfo::CreateCompileUnit() {
       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
   } else if (LO.ObjC) {
     LangTag = llvm::dwarf::DW_LANG_ObjC;
-  } else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
-                           CGM.getCodeGenOpts().DwarfVersion >= 5)) {
+  } else if (LO.OpenCL && (!DO.DebugStrictDwarf || DO.DwarfVersion >= 5)) {
     LangTag = llvm::dwarf::DW_LANG_OpenCL;
   } else if (LO.RenderScript) {
     LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
-  } else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) {
-      LangTag = llvm::dwarf::DW_LANG_C11;
+  } else if (LO.C11 && !(DO.DebugStrictDwarf && DO.DwarfVersion < 5)) {
+    LangTag = llvm::dwarf::DW_LANG_C11;
   } else if (LO.C99) {
     LangTag = llvm::dwarf::DW_LANG_C99;
   } else {
@@ -602,26 +602,25 @@ void CGDebugInfo::CreateCompileUnit() {
 
   llvm::DICompileUnit::DebugEmissionKind EmissionKind;
   switch (DebugKind) {
-  case llvm::codegenoptions::NoDebugInfo:
-  case llvm::codegenoptions::LocTrackingOnly:
+  case llvm::debugoptions::NoDebugInfo:
+  case llvm::debugoptions::LocTrackingOnly:
     EmissionKind = llvm::DICompileUnit::NoDebug;
     break;
-  case llvm::codegenoptions::DebugLineTablesOnly:
+  case llvm::debugoptions::DebugLineTablesOnly:
     EmissionKind = llvm::DICompileUnit::LineTablesOnly;
     break;
-  case llvm::codegenoptions::DebugDirectivesOnly:
+  case llvm::debugoptions::DebugDirectivesOnly:
     EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
     break;
-  case llvm::codegenoptions::DebugInfoConstructor:
-  case llvm::codegenoptions::LimitedDebugInfo:
-  case llvm::codegenoptions::FullDebugInfo:
-  case llvm::codegenoptions::UnusedTypeInfo:
+  case llvm::debugoptions::DebugInfoConstructor:
+  case llvm::debugoptions::LimitedDebugInfo:
+  case llvm::debugoptions::FullDebugInfo:
+  case llvm::debugoptions::UnusedTypeInfo:
     EmissionKind = llvm::DICompileUnit::FullDebug;
     break;
   }
 
   uint64_t DwoId = 0;
-  auto &CGOpts = CGM.getCodeGenOpts();
   // The DIFile used by the CU is distinct from the main source
   // file. Its directory part specifies what becomes the
   // DW_AT_comp_dir (the compilation directory), even if the source
@@ -633,7 +632,7 @@ void CGDebugInfo::CreateCompileUnit() {
       getSource(SM, SM.getMainFileID()));
 
   StringRef Sysroot, SDK;
-  if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
+  if (DO.getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
     Sysroot = CGM.getHeaderSearchOpts().Sysroot;
     auto B = llvm::sys::path::rbegin(Sysroot);
     auto E = llvm::sys::path::rend(Sysroot);
@@ -644,8 +643,7 @@ void CGDebugInfo::CreateCompileUnit() {
   }
 
   llvm::DICompileUnit::DebugNameTableKind NameTableKind =
-      static_cast<llvm::DICompileUnit::DebugNameTableKind>(
-          CGOpts.DebugNameTable);
+      static_cast<llvm::DICompileUnit::DebugNameTableKind>(DO.DebugNameTable);
   if (CGM.getTarget().getTriple().isNVPTX())
     NameTableKind = llvm::DICompileUnit::DebugNameTableKind::None;
   else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple)
@@ -653,11 +651,11 @@ void CGDebugInfo::CreateCompileUnit() {
 
   // Create new compile unit.
   TheCU = DBuilder.createCompileUnit(
-      LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
-      LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
-      CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
-      DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
-      NameTableKind, CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
+      LangTag, CUFile, CGO.EmitVersionIdentMetadata ? Producer : "",
+      LO.Optimize || CGO.PrepareForLTO || CGO.PrepareForThinLTO,
+      DO.DwarfDebugFlags, RuntimeVers, DO.SplitDwarfFile, EmissionKind, DwoId,
+      DO.SplitDwarfInlining, DO.DebugInfoForProfiling, NameTableKind,
+      DO.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
 }
 
 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
@@ -1096,7 +1094,7 @@ static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
     return true;
 
   // CodeView types with C++ mangling need a type identifier.
-  if (CGM.getCodeGenOpts().EmitCodeView)
+  if (CGM.getDebugOpts().EmitCodeView)
     return true;
 
   return false;
@@ -1170,12 +1168,12 @@ CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
   // Create the type.
   SmallString<256> Identifier;
   // Don't include a linkage name in line tables only.
-  if (CGM.getCodeGenOpts().hasReducedDebugInfo())
+  if (CGM.getDebugOpts().hasReducedDebugInfo())
     Identifier = getTypeIdentifier(Ty, CGM, TheCU);
   llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
       getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
       Identifier);
-  if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
+  if (CGM.getDebugOpts().DebugFwdTemplateParams)
     if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
       DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
                              CollectCXXTemplateParams(TSpecial, DefUnit));
@@ -1660,8 +1658,7 @@ void CGDebugInfo::CollectRecordLambdaFields(
       FieldDecl *f = *Field;
       llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
       QualType type = f->getType();
-      StringRef ThisName =
-          CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this";
+      StringRef ThisName = CGM.getDebugOpts().EmitCodeView ? "__this" : "this";
       llvm::DIType *fieldType = createFieldType(
           ThisName, type, f->getLocation(), f->getAccess(),
           layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
@@ -1697,9 +1694,8 @@ CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
   }
 
   llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
-  auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
-                 ? llvm::dwarf::DW_TAG_variable
-                 : llvm::dwarf::DW_TAG_member;
+  auto Tag = CGM.getDebugOpts().DwarfVersion >= 5 ? llvm::dwarf::DW_TAG_variable
+                                                  : llvm::dwarf::DW_TAG_member;
   auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
   llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
       RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Tag, Align);
@@ -1770,7 +1766,7 @@ void CGDebugInfo::CollectRecordFields(
 
         // Skip variable template specializations when emitting CodeView. MSVC
         // doesn't emit them.
-        if (CGM.getCodeGenOpts().EmitCodeView &&
+        if (CGM.getDebugOpts().EmitCodeView &&
             isa<VarTemplateSpecializationDecl>(V))
           continue;
 
@@ -1793,7 +1789,7 @@ void CGDebugInfo::CollectRecordFields(
 
         // Bump field number for next field.
         ++fieldNo;
-      } else if (CGM.getCodeGenOpts().EmitCodeView) {
+      } else if (CGM.getDebugOpts().EmitCodeView) {
         // Debug info for nested types is included in the member list only for
         // CodeView.
         if (const auto *nestedType = dyn_cast<TypeDecl>(I)) {
@@ -1994,7 +1990,7 @@ llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
 
   // In this debug mode, emit type info for a class when its constructor type
   // info is emitted.
-  if (DebugKind == llvm::codegenoptions::DebugInfoConstructor)
+  if (DebugKind == llvm::debugoptions::DebugInfoConstructor)
     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
       completeUnusedClass(*CD->getParent());
 
@@ -2056,7 +2052,7 @@ void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
 
   // If we are generating CodeView debug info, we also need to emit records for
   // indirect virtual base classes.
-  if (CGM.getCodeGenOpts().EmitCodeView) {
+  if (CGM.getDebugOpts().EmitCodeView) {
     CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
                        llvm::DINode::FlagIndirectVirtualBase);
   }
@@ -2343,7 +2339,7 @@ StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
                                                  llvm::Function *InitFn) {
   // If we're not emitting codeview, use the mangled name. For Itanium, this is
   // arbitrary.
-  if (!CGM.getCodeGenOpts().EmitCodeView ||
+  if (!CGM.getDebugOpts().EmitCodeView ||
       StubKind == DynamicInitKind::GlobalArrayDestructor)
     return InitFn->getName();
 
@@ -2410,7 +2406,7 @@ void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
   // emit a special named pointer type into the element list. The vptr type
   // points to this type as well.
   llvm::DIType *VPtrTy = nullptr;
-  bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
+  bool NeedVTableShape = CGM.getDebugOpts().EmitCodeView &&
                          CGM.getTarget().getCXXABI().isMicrosoft();
   if (NeedVTableShape) {
     uint64_t PtrWidth =
@@ -2449,7 +2445,7 @@ void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
 
 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
                                                  SourceLocation Loc) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
   return T;
 }
@@ -2461,7 +2457,7 @@ llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
 
 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
                                                      SourceLocation Loc) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   assert(!D.isNull() && "null type");
   llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
   assert(T && "could not create debug info for type");
@@ -2473,8 +2469,8 @@ llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
                                            QualType AllocatedTy,
                                            SourceLocation Loc) {
-  if (CGM.getCodeGenOpts().getDebugInfo() <=
-      llvm::codegenoptions::DebugLineTablesOnly)
+  if (CGM.getDebugOpts().getDebugInfo() <=
+      llvm::debugoptions::DebugLineTablesOnly)
     return;
   llvm::MDNode *node;
   if (AllocatedTy->isVoidType())
@@ -2486,7 +2482,7 @@ void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
 }
 
 void CGDebugInfo::completeType(const EnumDecl *ED) {
-  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
+  if (DebugKind <= llvm::debugoptions::DebugLineTablesOnly)
     return;
   QualType Ty = CGM.getContext().getEnumType(ED);
   void *TyPtr = Ty.getAsOpaquePtr();
@@ -2499,7 +2495,7 @@ void CGDebugInfo::completeType(const EnumDecl *ED) {
 }
 
 void CGDebugInfo::completeType(const RecordDecl *RD) {
-  if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
+  if (DebugKind > llvm::debugoptions::LimitedDebugInfo ||
       !CGM.getLangOpts().CPlusPlus)
     completeRequiredType(RD);
 }
@@ -2561,7 +2557,7 @@ void CGDebugInfo::completeClassData(const RecordDecl *RD) {
 }
 
 void CGDebugInfo::completeClass(const RecordDecl *RD) {
-  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
+  if (DebugKind <= llvm::debugoptions::DebugLineTablesOnly)
     return;
   QualType Ty = CGM.getContext().getRecordType(RD);
   void *TyPtr = Ty.getAsOpaquePtr();
@@ -2613,7 +2609,7 @@ static bool canUseCtorHoming(const CXXRecordDecl *RD) {
   return false;
 }
 
-static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
+static bool shouldOmitDefinition(llvm::debugoptions::DebugInfoKind DebugKind,
                                  bool DebugTypeExtRefs, const RecordDecl *RD,
                                  const LangOptions &LangOpts) {
   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
@@ -2626,10 +2622,10 @@ static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
   // Only emit forward declarations in line tables only to keep debug info size
   // small. This only applies to CodeView, since we don't emit types in DWARF
   // line tables only.
-  if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)
+  if (DebugKind == llvm::debugoptions::DebugLineTablesOnly)
     return true;
 
-  if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
+  if (DebugKind > llvm::debugoptions::LimitedDebugInfo ||
       RD->hasAttr<StandaloneDebugAttr>())
     return false;
 
@@ -2665,7 +2661,7 @@ static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
 
   // In constructor homing mode, only emit complete debug info for a class
   // when its constructor is emitted.
-  if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&
+  if ((DebugKind == llvm::debugoptions::DebugInfoConstructor) &&
       canUseCtorHoming(CXXDecl))
     return true;
 
@@ -2766,7 +2762,7 @@ CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
 
   RegionMap[Ty->getDecl()].reset(FwdDecl);
 
-  if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
+  if (CGM.getDebugOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
     if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))
       return {FwdDecl, PrefDI};
 
@@ -3278,8 +3274,8 @@ llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
                                       llvm::DIFile *Unit) {
   llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
   // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
-  if (CGM.getCodeGenOpts().DebugStrictDwarf &&
-      CGM.getCodeGenOpts().DwarfVersion < 4)
+  if (CGM.getDebugOpts().DebugStrictDwarf &&
+      CGM.getDebugOpts().DwarfVersion < 4)
     Tag = llvm::dwarf::DW_TAG_reference_type;
 
   return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
@@ -3513,7 +3509,7 @@ void CGDebugInfo::completeTemplateDefinition(
 }
 
 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
-  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
+  if (DebugKind <= llvm::debugoptions::DebugLineTablesOnly ||
       D.isDynamicClass())
     return;
 
@@ -3850,16 +3846,16 @@ void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
   if (LinkageName == Name ||
       (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
        CGM.getCodeGenOpts().CoverageDataFile.empty() &&
-       !CGM.getCodeGenOpts().DebugInfoForProfiling &&
+       !CGM.getDebugOpts().DebugInfoForProfiling &&
        !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
-       DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
+       DebugKind <= llvm::debugoptions::DebugLineTablesOnly))
     LinkageName = StringRef();
 
   // Emit the function scope in line tables only mode (if CodeView) to
   // differentiate between function names.
-  if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
-      (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
-       CGM.getCodeGenOpts().EmitCodeView)) {
+  if (CGM.getDebugOpts().hasReducedDebugInfo() ||
+      (DebugKind == llvm::debugoptions::DebugLineTablesOnly &&
+       CGM.getDebugOpts().EmitCodeView)) {
     if (const NamespaceDecl *NSDecl =
             dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
       FDContext = getOrCreateNamespace(NSDecl);
@@ -3869,7 +3865,7 @@ void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
       FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
     }
   }
-  if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
+  if (CGM.getDebugOpts().hasReducedDebugInfo()) {
     // Check if it is a noreturn-marked function
     if (FD->isNoReturn())
       Flags |= llvm::DINode::FlagNoReturn;
@@ -4050,7 +4046,7 @@ llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
 }
 
 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
-  if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
+  if (!D || DebugKind <= llvm::debugoptions::DebugLineTablesOnly)
     return nullptr;
 
   const auto *FD = dyn_cast<FunctionDecl>(D);
@@ -4087,14 +4083,14 @@ llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
     const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
     llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
-  if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
+  if (!D || DebugKind <= llvm::debugoptions::DebugLineTablesOnly)
     return nullptr;
 
   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
   if (!OMD)
     return nullptr;
 
-  if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
+  if (CGM.getDebugOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
     return nullptr;
 
   if (OMD->isDirectMethod())
@@ -4127,8 +4123,8 @@ llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
                                                              llvm::DIFile *F) {
   // In CodeView, we emit the function types in line tables only because the
   // only way to distinguish between functions is by display name and type.
-  if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
-             !CGM.getCodeGenOpts().EmitCodeView))
+  if (!D || (DebugKind <= llvm::debugoptions::DebugLineTablesOnly &&
+             !CGM.getDebugOpts().EmitCodeView))
     // Create fake but valid subroutine type. Otherwise -verify would fail, and
     // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
     return DBuilder.createSubroutineType(
@@ -4482,7 +4478,7 @@ void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
       CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
       LexicalBlockStack.back(), CurInlinedAt));
 
-  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
+  if (DebugKind <= llvm::debugoptions::DebugLineTablesOnly)
     return;
 
   // Create a new lexical block and push it on the stack.
@@ -4496,7 +4492,7 @@ void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
   // Provide an entry in the line table for the end of the block.
   EmitLocation(Builder, Loc);
 
-  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
+  if (DebugKind <= llvm::debugoptions::DebugLineTablesOnly)
     return;
 
   LexicalBlockStack.pop_back();
@@ -4595,7 +4591,7 @@ llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
                                                 std::optional<unsigned> ArgNo,
                                                 CGBuilderTy &Builder,
                                                 const bool UsePointerValue) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
   if (VD->hasAttr<NoDebugAttr>())
     return nullptr;
@@ -4809,7 +4805,7 @@ llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
                                                 std::optional<unsigned> ArgNo,
                                                 CGBuilderTy &Builder,
                                                 const bool UsePointerValue) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
   if (BD->hasAttr<NoDebugAttr>())
     return nullptr;
@@ -4898,7 +4894,7 @@ llvm::DILocalVariable *
 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
                                        CGBuilderTy &Builder,
                                        const bool UsePointerValue) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
 
   if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
     for (auto *B : DD->bindings()) {
@@ -4914,7 +4910,7 @@ CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
 }
 
 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
 
   if (D->hasAttr<NoDebugAttr>())
@@ -4951,7 +4947,7 @@ llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
     const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
     const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
 
   if (Builder.GetInsertBlock() == nullptr)
@@ -5024,7 +5020,7 @@ llvm::DILocalVariable *
 CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
                                       unsigned ArgNo, CGBuilderTy &Builder,
                                       bool UsePointerValue) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
 }
 
@@ -5081,7 +5077,7 @@ void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
                                                        unsigned ArgNo,
                                                        llvm::AllocaInst *Alloca,
                                                        CGBuilderTy &Builder) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   ASTContext &C = CGM.getContext();
   const BlockDecl *blockDecl = block.getBlockDecl();
 
@@ -5356,11 +5352,11 @@ std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
   const NamedDecl *ND = dyn_cast<NamedDecl>(D);
   if (!ND)
     return Name;
-  llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
-      CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
+  llvm::debugoptions::DebugTemplateNamesKind TemplateNamesKind =
+      CGM.getDebugOpts().getDebugSimpleTemplateNames();
 
-  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
-    TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;
+  if (!CGM.getDebugOpts().hasReducedDebugInfo())
+    TemplateNamesKind = llvm::debugoptions::DebugTemplateNamesKind::Full;
 
   std::optional<TemplateArgs> Args;
 
@@ -5445,12 +5441,12 @@ std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
 
   PrintingPolicy PP = getPrintingPolicy();
 
-  if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||
+  if (TemplateNamesKind == llvm::debugoptions::DebugTemplateNamesKind::Full ||
       !Reconstitutable) {
     ND->getNameForDiagnostic(OS, PP, Qualified);
   } else {
     bool Mangled = TemplateNamesKind ==
-                   llvm::codegenoptions::DebugTemplateNamesKind::Mangled;
+                   llvm::debugoptions::DebugTemplateNamesKind::Mangled;
     // check if it's a template
     if (Mangled)
       OS << "_STN|";
@@ -5477,7 +5473,7 @@ std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
 
 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
                                      const VarDecl *D) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   if (D->hasAttr<NoDebugAttr>())
     return;
 
@@ -5542,7 +5538,7 @@ void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
 }
 
 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   if (VD->hasAttr<NoDebugAttr>())
     return;
   llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
@@ -5559,7 +5555,7 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
     const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
 
-    if (CGM.getCodeGenOpts().EmitCodeView) {
+    if (CGM.getDebugOpts().EmitCodeView) {
       // If CodeView, emit enums as global variables, unless they are defined
       // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
       // enums in classes, and because it is difficult to attach this scope
@@ -5619,7 +5615,7 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
 
 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
                                        const VarDecl *D) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  assert(CGM.getDebugOpts().hasReducedDebugInfo());
   if (D->hasAttr<NoDebugAttr>())
     return;
 
@@ -5641,7 +5637,7 @@ void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
 
   assert(GV);
 
-  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
+  if (!CGM.getDebugOpts().hasReducedDebugInfo())
     return;
 
   const auto *D = cast<ValueDecl>(GD.getDecl());
@@ -5700,11 +5696,11 @@ llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
 }
 
 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
-  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
+  if (!CGM.getDebugOpts().hasReducedDebugInfo())
     return;
   const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
   if (!NSDecl->isAnonymousNamespace() ||
-      CGM.getCodeGenOpts().DebugExplicitImport) {
+      CGM.getDebugOpts().DebugExplicitImport) {
     auto Loc = UD.getLocation();
     if (!Loc.isValid())
       Loc = CurLoc;
@@ -5725,7 +5721,7 @@ void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) {
 }
 
 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
-  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
+  if (!CGM.getDebugOpts().hasReducedDebugInfo())
     return;
   assert(UD.shadow_size() &&
          "We shouldn't be codegening an invalid UsingDecl containing no decls");
@@ -5750,7 +5746,7 @@ void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
 }
 
 void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {
-  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
+  if (!CGM.getDebugOpts().hasReducedDebugInfo())
     return;
   assert(UD.shadow_size() &&
          "We shouldn't be codegening an invalid UsingEnumDecl"
@@ -5761,7 +5757,7 @@ void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {
 }
 
 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
-  if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
+  if (CGM.getDebugOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
     return;
   if (Module *M = ID.getImportedModule()) {
     auto Info = ASTSourceDescriptor(*M);
@@ -5775,7 +5771,7 @@ void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
 
 llvm::DIImportedEntity *
 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
-  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
+  if (!CGM.getDebugOpts().hasReducedDebugInfo())
     return nullptr;
   auto &VH = NamespaceAliasCache[&NA];
   if (VH)
@@ -5848,7 +5844,7 @@ void CGDebugInfo::finalize() {
 
     // For DWARF v4 or earlier, only add objc_direct methods.
     for (auto &SubprogramDirect : P.second)
-      if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
+      if (CGM.getDebugOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
         EltTys.push_back(SubprogramDirect.getPointer());
 
     llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
@@ -5898,13 +5894,13 @@ void CGDebugInfo::finalize() {
 
 // Don't ignore in case of explicit cast where it is referenced indirectly.
 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
-  if (CGM.getCodeGenOpts().hasReducedDebugInfo())
+  if (CGM.getDebugOpts().hasReducedDebugInfo())
     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
       DBuilder.retainType(DieTy);
 }
 
 void CGDebugInfo::EmitAndRetainType(QualType Ty) {
-  if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
+  if (CGM.getDebugOpts().hasMaybeUnusedDebugInfo())
     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
       DBuilder.retainType(DieTy);
 }
@@ -5922,19 +5918,19 @@ llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
   // Call site-related attributes are only useful in optimized programs, and
   // when there's a possibility of debugging backtraces.
   if (!CGM.getLangOpts().Optimize ||
-      DebugKind == llvm::codegenoptions::NoDebugInfo ||
-      DebugKind == llvm::codegenoptions::LocTrackingOnly)
+      DebugKind == llvm::debugoptions::NoDebugInfo ||
+      DebugKind == llvm::debugoptions::LocTrackingOnly)
     return llvm::DINode::FlagZero;
 
   // Call site-related attributes are available in DWARF v5. Some debuggers,
   // while not fully DWARF v5-compliant, may accept these attributes as if they
   // were part of DWARF v4.
   bool SupportsDWARFv4Ext =
-      CGM.getCodeGenOpts().DwarfVersion == 4 &&
-      (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
-       CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
+      CGM.getDebugOpts().DwarfVersion == 4 &&
+      (CGM.getDebugOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
+       CGM.getDebugOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
 
-  if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
+  if (!SupportsDWARFv4Ext && CGM.getDebugOpts().DwarfVersion < 5)
     return llvm::DINode::FlagZero;
 
   return llvm::DINode::FlagAllCallsDescribed;
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 7b60e94555d0608..68c3bf8bf7adae5 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -20,11 +20,11 @@
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeOrdering.h"
-#include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/Frontend/Debug/Options.h"
 #include "llvm/IR/DIBuilder.h"
 #include "llvm/IR/DebugInfo.h"
 #include "llvm/IR/ValueHandle.h"
@@ -56,7 +56,7 @@ class CGDebugInfo {
   friend class ApplyDebugLocation;
   friend class SaveAndRestoreLocation;
   CodeGenModule &CGM;
-  const llvm::codegenoptions::DebugInfoKind DebugKind;
+  const llvm::debugoptions::DebugInfoKind DebugKind;
   bool DebugTypeExtRefs;
   llvm::DIBuilder DBuilder;
   llvm::DICompileUnit *TheCU = nullptr;
diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index bbe14ef4c17244f..1773841c2b5041e 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -28,6 +28,7 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclOpenMP.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
@@ -485,7 +486,7 @@ void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
 
   // Emit global variable debug descriptor for static vars.
   CGDebugInfo *DI = getDebugInfo();
-  if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
+  if (DI && CGM.getDebugOpts().hasReducedDebugInfo()) {
     DI->setLocation(D.getLocation());
     DI->EmitGlobalVariable(var, &D);
   }
@@ -1446,7 +1447,7 @@ CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
     EmitVariablyModifiedType(Ty);
 
   auto *DI = getDebugInfo();
-  bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
+  bool EmitDebugInfo = DI && CGM.getDebugOpts().hasReducedDebugInfo();
 
   Address address = Address::invalid();
   Address AllocaAddr = Address::invalid();
@@ -2673,7 +2674,7 @@ void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
 
   // Emit debug info for param declarations in non-thunk functions.
   if (CGDebugInfo *DI = getDebugInfo()) {
-    if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
+    if (CGM.getDebugOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
         !NoDebugInfo) {
       llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
           &D, AllocaPtr.getPointer(), ArgNo, Builder, UseIndirectDebugAddress);
diff --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index e887d35198b3c7b..b9fc6c238111b3e 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -16,6 +16,7 @@
 #include "CGDebugInfo.h"
 #include "CodeGenModule.h"
 #include "clang/AST/Decl.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/TargetOptions.h"
 #include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/Metadata.h"
@@ -127,8 +128,8 @@ void CGHLSLRuntime::addConstant(VarDecl *D, Buffer &CB) {
   auto *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(D));
   // Add debug info for constVal.
   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
-    if (CGM.getCodeGenOpts().getDebugInfo() >=
-        codegenoptions::DebugInfoKind::LimitedDebugInfo)
+    if (CGM.getDebugOpts().getDebugInfo() >=
+        debugoptions::DebugInfoKind::LimitedDebugInfo)
       DI->EmitGlobalVariable(cast<GlobalVariable>(GV), D);
 
   // FIXME: support packoffset.
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 4855e7410a015aa..852bf904ee6b0d5 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -23,6 +23,7 @@
 #include "clang/AST/StmtOpenMP.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/BitmaskEnum.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/OpenMPKinds.h"
 #include "clang/Basic/SourceManager.h"
@@ -1368,8 +1369,8 @@ llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
                                                  unsigned Flags, bool EmitLoc) {
   uint32_t SrcLocStrSize;
   llvm::Constant *SrcLocStr;
-  if ((!EmitLoc && CGM.getCodeGenOpts().getDebugInfo() ==
-                       llvm::codegenoptions::NoDebugInfo) ||
+  if ((!EmitLoc &&
+       CGM.getDebugOpts().getDebugInfo() == llvm::debugoptions::NoDebugInfo) ||
       Loc.isInvalid()) {
     SrcLocStr = OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize);
   } else {
@@ -8835,8 +8836,7 @@ static void emitOffloadingArrays(
   auto FillInfoMap = [&](MappableExprsHandler::MappingExprInfo &MapExpr) {
     return emitMappingInformation(CGF, OMPBuilder, MapExpr);
   };
-  if (CGM.getCodeGenOpts().getDebugInfo() !=
-      llvm::codegenoptions::NoDebugInfo) {
+  if (CGM.getDebugOpts().getDebugInfo() != llvm::debugoptions::NoDebugInfo) {
     CombinedInfo.Names.resize(CombinedInfo.Exprs.size());
     llvm::transform(CombinedInfo.Exprs, CombinedInfo.Names.begin(),
                     FillInfoMap);
@@ -9137,8 +9137,7 @@ void CGOpenMPRuntime::emitUserDefinedMapper(const OMPDeclareMapperDecl *D,
         Info.Pointers[I], CGM.getTypes().ConvertTypeForMem(C.VoidPtrTy));
     llvm::Value *CurSizeArg = Info.Sizes[I];
     llvm::Value *CurNameArg =
-        (CGM.getCodeGenOpts().getDebugInfo() ==
-         llvm::codegenoptions::NoDebugInfo)
+        (CGM.getDebugOpts().getDebugInfo() == llvm::debugoptions::NoDebugInfo)
             ? llvm::ConstantPointerNull::get(CGM.VoidPtrTy)
             : emitMappingInformation(MapperCGF, OMPBuilder, Info.Exprs[I]);
 
@@ -9518,8 +9517,8 @@ static void emitTargetCallKernelLaunch(
   CGOpenMPRuntime::TargetDataInfo Info;
   // Fill up the arrays and create the arguments.
   emitOffloadingArrays(CGF, CombinedInfo, Info, OMPBuilder);
-  bool EmitDebug = CGF.CGM.getCodeGenOpts().getDebugInfo() !=
-                   llvm::codegenoptions::NoDebugInfo;
+  bool EmitDebug =
+      CGF.CGM.getDebugOpts().getDebugInfo() != llvm::debugoptions::NoDebugInfo;
   OMPBuilder.emitOffloadingArraysArgument(CGF.Builder, Info.RTArgs, Info,
                                           EmitDebug,
                                           /*ForEndCall=*/false);
@@ -10248,8 +10247,7 @@ void CGOpenMPRuntime::emitTargetDataCalls(
     auto FillInfoMap = [&](MappableExprsHandler::MappingExprInfo &MapExpr) {
       return emitMappingInformation(CGF, OMPBuilder, MapExpr);
     };
-    if (CGM.getCodeGenOpts().getDebugInfo() !=
-        llvm::codegenoptions::NoDebugInfo) {
+    if (CGM.getDebugOpts().getDebugInfo() != llvm::debugoptions::NoDebugInfo) {
       CombinedInfo.Names.resize(CombinedInfo.Exprs.size());
       llvm::transform(CombinedInfo.Exprs, CombinedInfo.Names.begin(),
                       FillInfoMap);
@@ -10462,8 +10460,8 @@ void CGOpenMPRuntime::emitTargetDataStandAloneCall(
                          /*IsNonContiguous=*/true);
     bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>() ||
                              D.hasClausesOfKind<OMPNowaitClause>();
-    bool EmitDebug = CGF.CGM.getCodeGenOpts().getDebugInfo() !=
-                     llvm::codegenoptions::NoDebugInfo;
+    bool EmitDebug = CGF.CGM.getDebugOpts().getDebugInfo() !=
+                     llvm::debugoptions::NoDebugInfo;
     OMPBuilder.emitOffloadingArraysArgument(CGF.Builder, Info.RTArgs, Info,
                                             EmitDebug,
                                             /*ForEndCall=*/false);
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index beff0ad9da2709c..02021ab76720a66 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/Builtins.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/PrettyStackTrace.h"
 #include "clang/Basic/SourceManager.h"
@@ -659,7 +660,7 @@ void CodeGenFunction::EmitLabel(const LabelDecl *D) {
 
   // Emit debug info for labels.
   if (CGDebugInfo *DI = getDebugInfo()) {
-    if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
+    if (CGM.getDebugOpts().hasReducedDebugInfo()) {
       DI->setLocation(D->getLocation());
       DI->EmitLabel(D, Builder);
     }
@@ -1548,7 +1549,7 @@ void CodeGenFunction::EmitCaseStmt(const CaseStmt &S,
   if (CE) {
     if (auto DE = dyn_cast<DeclRefExpr>(CE->getSubExpr()))
       if (CGDebugInfo *Dbg = getDebugInfo())
-        if (CGM.getCodeGenOpts().hasReducedDebugInfo())
+        if (CGM.getDebugOpts().hasReducedDebugInfo())
           Dbg->EmitGlobalVariable(DE->getDecl(),
               APValue(llvm::APSInt(CaseVal->getValue())));
   }
diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index e362c9da51fe31d..5f5645da3116d52 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -22,6 +22,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtOpenMP.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/OpenMPKinds.h"
 #include "clang/Basic/PrettyStackTrace.h"
 #include "llvm/ADT/SmallSet.h"
@@ -615,7 +616,7 @@ CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
   const CapturedDecl *CD = S.getCapturedDecl();
   // Build the argument list.
   bool NeedWrapperFunction =
-      getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo();
+      getDebugInfo() && CGM.getDebugOpts().hasReducedDebugInfo();
   FunctionArgList Args;
   llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
   llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
@@ -4743,7 +4744,7 @@ void CodeGenFunction::EmitOMPTaskBasedDirective(
               CGF.getContext().getASTRecordLayout(CaptureRecord);
           unsigned Offset =
               Layout.getFieldOffset(It->second->getFieldIndex()) / CharWidth;
-          if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
+          if (CGF.CGM.getDebugOpts().hasReducedDebugInfo())
             (void)DI->EmitDeclareOfAutoVariable(SharedVar, ContextValue,
                                                 CGF.Builder, false);
           llvm::Instruction &Last = CGF.Builder.GetInsertBlock()->back();
@@ -4842,7 +4843,7 @@ void CodeGenFunction::EmitOMPTaskBasedDirective(
             CGF.getContext().getDeclAlign(Pair.first));
         Scope.addPrivate(Pair.first, Replacement);
         if (auto *DI = CGF.getDebugInfo())
-          if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
+          if (CGF.CGM.getDebugOpts().hasReducedDebugInfo())
             (void)DI->EmitDeclareOfAutoVariable(
                 Pair.first, Pair.second.getPointer(), CGF.Builder,
                 /*UsePointerValue*/ true);
diff --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index 8dee3f74b44b4e6..882764b8a2e6e01 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/CodeGen/ConstantInitBuilder.h"
 #include "llvm/IR/IntrinsicInst.h"
@@ -1059,20 +1060,19 @@ CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
     switch (keyFunction->getTemplateSpecializationKind()) {
       case TSK_Undeclared:
       case TSK_ExplicitSpecialization:
-      assert(
-          (def || CodeGenOpts.OptimizationLevel > 0 ||
-           CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo) &&
-          "Shouldn't query vtable linkage without key function, "
-          "optimizations, or debug info");
-      if (!def && CodeGenOpts.OptimizationLevel > 0)
-        return llvm::GlobalVariable::AvailableExternallyLinkage;
-
-      if (keyFunction->isInlined())
-        return !Context.getLangOpts().AppleKext
-                   ? llvm::GlobalVariable::LinkOnceODRLinkage
-                   : llvm::Function::InternalLinkage;
-
-      return llvm::GlobalVariable::ExternalLinkage;
+        assert((def || CodeGenOpts.OptimizationLevel > 0 ||
+                DebugOpts.getDebugInfo() != llvm::debugoptions::NoDebugInfo) &&
+               "Shouldn't query vtable linkage without key function, "
+               "optimizations, or debug info");
+        if (!def && CodeGenOpts.OptimizationLevel > 0)
+          return llvm::GlobalVariable::AvailableExternallyLinkage;
+
+        if (keyFunction->isInlined())
+          return !Context.getLangOpts().AppleKext
+                     ? llvm::GlobalVariable::LinkOnceODRLinkage
+                     : llvm::Function::InternalLinkage;
+
+        return llvm::GlobalVariable::ExternalLinkage;
 
       case TSK_ImplicitInstantiation:
         return !Context.getLangOpts().AppleKext ?
diff --git a/clang/lib/CodeGen/CodeGenAction.cpp b/clang/lib/CodeGen/CodeGenAction.cpp
index f8038497d90a7bf..157143fb0a32396 100644
--- a/clang/lib/CodeGen/CodeGenAction.cpp
+++ b/clang/lib/CodeGen/CodeGenAction.cpp
@@ -16,6 +16,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclGroup.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/DiagnosticFrontend.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangStandard.h"
@@ -109,56 +110,52 @@ static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
       });
 }
 
-BackendConsumer::BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
-                                 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
-                                 const HeaderSearchOptions &HeaderSearchOpts,
-                                 const PreprocessorOptions &PPOpts,
-                                 const CodeGenOptions &CodeGenOpts,
-                                 const TargetOptions &TargetOpts,
-                                 const LangOptions &LangOpts,
-                                 const std::string &InFile,
-                                 SmallVector<LinkModule, 4> LinkModules,
-                                 std::unique_ptr<raw_pwrite_stream> OS,
-                                 LLVMContext &C,
-                                 CoverageSourceInfo *CoverageInfo)
-  : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
-  CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
-  AsmOutStream(std::move(OS)), Context(nullptr), FS(VFS),
-  LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
-  LLVMIRGenerationRefCount(0),
-  Gen(CreateLLVMCodeGen(Diags, InFile, std::move(VFS), HeaderSearchOpts,
-                        PPOpts, CodeGenOpts, C, CoverageInfo)),
-  LinkModules(std::move(LinkModules)) {
-    TimerIsEnabled = CodeGenOpts.TimePasses;
-    llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
-    llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
+BackendConsumer::BackendConsumer(
+    BackendAction Action, DiagnosticsEngine &Diags,
+    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
+    const HeaderSearchOptions &HeaderSearchOpts,
+    const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
+    const DebugOptions &DebugOpts, const TargetOptions &TargetOpts,
+    const LangOptions &LangOpts, const std::string &InFile,
+    SmallVector<LinkModule, 4> LinkModules,
+    std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
+    CoverageSourceInfo *CoverageInfo)
+    : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
+      CodeGenOpts(CodeGenOpts), DebugOpts(DebugOpts), TargetOpts(TargetOpts),
+      LangOpts(LangOpts), AsmOutStream(std::move(OS)), Context(nullptr),
+      FS(VFS), LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
+      LLVMIRGenerationRefCount(0),
+      Gen(CreateLLVMCodeGen(Diags, InFile, std::move(VFS), HeaderSearchOpts,
+                            PPOpts, CodeGenOpts, DebugOpts, C, CoverageInfo)),
+      LinkModules(std::move(LinkModules)) {
+  TimerIsEnabled = CodeGenOpts.TimePasses;
+  llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
+  llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
 }
 
 // This constructor is used in installing an empty BackendConsumer
 // to use the clang diagnostic handler for IR input files. It avoids
 // initializing the OS field.
-BackendConsumer::BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
-                                 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
-                                 const HeaderSearchOptions &HeaderSearchOpts,
-                                 const PreprocessorOptions &PPOpts,
-                                 const CodeGenOptions &CodeGenOpts,
-                                 const TargetOptions &TargetOpts,
-                                 const LangOptions &LangOpts,
-                                 llvm::Module *Module,
-                                 SmallVector<LinkModule, 4> LinkModules,
-                                 LLVMContext &C,
-                                 CoverageSourceInfo *CoverageInfo)
-  : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
-  CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
-  Context(nullptr), FS(VFS),
-  LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
-  LLVMIRGenerationRefCount(0),
-  Gen(CreateLLVMCodeGen(Diags, "", std::move(VFS), HeaderSearchOpts,
-                        PPOpts, CodeGenOpts, C, CoverageInfo)),
-  LinkModules(std::move(LinkModules)), CurLinkModule(Module) {
-    TimerIsEnabled = CodeGenOpts.TimePasses;
-    llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
-    llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
+BackendConsumer::BackendConsumer(
+    BackendAction Action, DiagnosticsEngine &Diags,
+    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
+    const HeaderSearchOptions &HeaderSearchOpts,
+    const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
+    const DebugOptions &DebugOpts, const TargetOptions &TargetOpts,
+    const LangOptions &LangOpts, llvm::Module *Module,
+    SmallVector<LinkModule, 4> LinkModules, LLVMContext &C,
+    CoverageSourceInfo *CoverageInfo)
+    : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
+      CodeGenOpts(CodeGenOpts), DebugOpts(DebugOpts), TargetOpts(TargetOpts),
+      LangOpts(LangOpts), Context(nullptr), FS(VFS),
+      LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
+      LLVMIRGenerationRefCount(0),
+      Gen(CreateLLVMCodeGen(Diags, "", std::move(VFS), HeaderSearchOpts, PPOpts,
+                            CodeGenOpts, DebugOpts, C, CoverageInfo)),
+      LinkModules(std::move(LinkModules)), CurLinkModule(Module) {
+  TimerIsEnabled = CodeGenOpts.TimePasses;
+  llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
+  llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
 }
 
 llvm::Module* BackendConsumer::getModule() const {
@@ -376,9 +373,9 @@ void BackendConsumer::HandleTranslationUnit(ASTContext &C) {
 
   EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
 
-  EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
-                    C.getTargetInfo().getDataLayoutString(), getModule(),
-                    Action, FS, std::move(AsmOutStream), this);
+  EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, DebugOpts, TargetOpts,
+                    LangOpts, C.getTargetInfo().getDataLayoutString(),
+                    getModule(), Action, FS, std::move(AsmOutStream), this);
 
   Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
 
@@ -1037,14 +1034,15 @@ CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
   std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
       BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
       CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
-      CI.getTargetOpts(), CI.getLangOpts(), std::string(InFile),
-      std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
+      CI.getDebugOpts(), CI.getTargetOpts(), CI.getLangOpts(),
+      std::string(InFile), std::move(LinkModules), std::move(OS), *VMContext,
+      CoverageInfo));
   BEConsumer = Result.get();
 
   // Enable generating macro debug info only when debug info is not disabled and
   // also macro debug info is enabled.
-  if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
-      CI.getCodeGenOpts().MacroDebugInfo) {
+  if (CI.getDebugOpts().getDebugInfo() != debugoptions::NoDebugInfo &&
+      CI.getDebugOpts().MacroDebugInfo) {
     std::unique_ptr<PPCallbacks> Callbacks =
         std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
                                             CI.getPreprocessor());
@@ -1158,6 +1156,7 @@ void CodeGenAction::ExecuteAction() {
   BackendAction BA = static_cast<BackendAction>(Act);
   CompilerInstance &CI = getCompilerInstance();
   auto &CodeGenOpts = CI.getCodeGenOpts();
+  auto &DebugOpts = CI.getDebugOpts();
   auto &Diagnostics = CI.getDiagnostics();
   std::unique_ptr<raw_pwrite_stream> OS =
       GetOutputStream(CI, getCurrentFileOrBufferName(), BA);
@@ -1198,8 +1197,8 @@ void CodeGenAction::ExecuteAction() {
   // BackendConsumer.
   BackendConsumer Result(BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(),
                          CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),
-                         CI.getCodeGenOpts(), CI.getTargetOpts(),
-                         CI.getLangOpts(), TheModule.get(),
+                         CI.getCodeGenOpts(), CI.getDebugOpts(),
+                         CI.getTargetOpts(), CI.getLangOpts(), TheModule.get(),
                          std::move(LinkModules), *VMContext, nullptr);
 
   // Link in each pending link module.
@@ -1226,7 +1225,7 @@ void CodeGenAction::ExecuteAction() {
       std::move(*OptRecordFileOrErr);
 
   EmitBackendOutput(
-      Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts, TargetOpts,
+      Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts, DebugOpts, TargetOpts,
       CI.getLangOpts(), CI.getTarget().getDataLayoutString(), TheModule.get(),
       BA, CI.getFileManager().getVirtualFileSystemPtr(), std::move(OS));
   if (OptRecordFile)
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp b/clang/lib/CodeGen/CodeGenFunction.cpp
index 2673e4a5cee7bb5..f4af65053583094 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -31,6 +31,7 @@
 #include "clang/AST/StmtObjC.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
@@ -921,7 +922,7 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
     Fn->addFnAttr("no-jump-tables", "true");
 
   // Add no-inline-line-tables value.
-  if (CGM.getCodeGenOpts().NoInlineLineTables)
+  if (CGM.getDebugOpts().NoInlineLineTables)
     Fn->addFnAttr("no-inline-line-tables");
 
   // Add profile-sample-accurate value.
@@ -2440,7 +2441,7 @@ void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
                                               const APValue &Init) {
   assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
   if (CGDebugInfo *Dbg = getDebugInfo())
-    if (CGM.getCodeGenOpts().hasReducedDebugInfo())
+    if (CGM.getDebugOpts().hasReducedDebugInfo())
       Dbg->EmitGlobalVariable(E->getDecl(), Init);
 }
 
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 1280bcd36de9431..4356aea9a98bb7f 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -39,6 +39,7 @@
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/Module.h"
@@ -329,12 +330,12 @@ CodeGenModule::CodeGenModule(ASTContext &C,
                              IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
                              const HeaderSearchOptions &HSO,
                              const PreprocessorOptions &PPO,
-                             const CodeGenOptions &CGO, llvm::Module &M,
-                             DiagnosticsEngine &diags,
+                             const CodeGenOptions &CGO, const DebugOptions &DO,
+                             llvm::Module &M, DiagnosticsEngine &diags,
                              CoverageSourceInfo *CoverageInfo)
     : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
-      PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
-      Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
+      PreprocessorOpts(PPO), CodeGenOpts(CGO), DebugOpts(DO), TheModule(M),
+      Diags(diags), Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
       VMContext(M.getContext()), Types(*this), VTables(*this),
       SanitizerMD(new SanitizerMetadata(*this)) {
 
@@ -400,7 +401,7 @@ CodeGenModule::CodeGenModule(ASTContext &C,
 
   // If debug info or coverage generation is enabled, create the CGDebugInfo
   // object.
-  if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
+  if (DebugOpts.getDebugInfo() != llvm::debugoptions::NoDebugInfo ||
       CodeGenOpts.CoverageNotesFile.size() ||
       CodeGenOpts.CoverageDataFile.size())
     DebugInfo.reset(new CGDebugInfo(*this));
@@ -950,23 +951,23 @@ void CodeGenModule::Release() {
     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
                               CodeGenOpts.NumRegisterParameters);
 
-  if (CodeGenOpts.DwarfVersion) {
+  if (DebugOpts.DwarfVersion) {
     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
-                              CodeGenOpts.DwarfVersion);
+                              DebugOpts.DwarfVersion);
   }
 
-  if (CodeGenOpts.Dwarf64)
+  if (DebugOpts.Dwarf64)
     getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
 
   if (Context.getLangOpts().SemanticInterposition)
     // Require various optimization to respect semantic interposition.
     getModule().setSemanticInterposition(true);
 
-  if (CodeGenOpts.EmitCodeView) {
+  if (DebugOpts.EmitCodeView) {
     // Indicate that we want CodeView in the metadata.
     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
   }
-  if (CodeGenOpts.CodeViewGHash) {
+  if (DebugOpts.CodeViewGHash) {
     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
   }
   if (CodeGenOpts.ControlFlowGuard) {
@@ -5499,13 +5500,13 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
 
   // Emit global variable debug information.
   if (CGDebugInfo *DI = getModuleDebugInfo())
-    if (getCodeGenOpts().hasReducedDebugInfo())
+    if (getDebugOpts().hasReducedDebugInfo())
       DI->EmitGlobalVariable(GV, D);
 }
 
 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
   if (CGDebugInfo *DI = getModuleDebugInfo())
-    if (getCodeGenOpts().hasReducedDebugInfo()) {
+    if (getDebugOpts().hasReducedDebugInfo()) {
       QualType ASTTy = D->getType();
       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
       llvm::Constant *GV =
@@ -6227,7 +6228,7 @@ CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
 }
 
 bool CodeGenModule::getExpressionLocationsEnabled() const {
-  return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
+  return !DebugOpts.EmitCodeView || DebugOpts.DebugColumnInfo;
 }
 
 QualType CodeGenModule::getObjCFastEnumerationStateType() {
@@ -6365,7 +6366,7 @@ CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
 
   CGDebugInfo *DI = getModuleDebugInfo();
-  if (DI && getCodeGenOpts().hasReducedDebugInfo())
+  if (DI && getDebugOpts().hasReducedDebugInfo())
     DI->AddStringLiteralDebugInfo(GV, S);
 
   if (Entry)
@@ -6840,7 +6841,7 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
     ObjCRuntime->GenerateClass(OMD);
     // Emit global variable debug information.
     if (CGDebugInfo *DI = getModuleDebugInfo())
-      if (getCodeGenOpts().hasReducedDebugInfo())
+      if (getDebugOpts().hasReducedDebugInfo())
         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
             OMD->getClassInterface()), OMD->getLocation());
     break;
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index ec34680fd3f7e6e..f1ed2718f65e825 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -74,6 +74,7 @@ class ValueDecl;
 class VarDecl;
 class LangOptions;
 class CodeGenOptions;
+class DebugOptions;
 class HeaderSearchOptions;
 class DiagnosticsEngine;
 class AnnotateAttr;
@@ -305,6 +306,7 @@ class CodeGenModule : public CodeGenTypeCache {
   const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
   const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
   const CodeGenOptions &CodeGenOpts;
+  const DebugOptions &DebugOpts;
   unsigned NumAutoVarInit = 0;
   llvm::Module &TheModule;
   DiagnosticsEngine &Diags;
@@ -611,7 +613,8 @@ class CodeGenModule : public CodeGenTypeCache {
   CodeGenModule(ASTContext &C, IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
                 const HeaderSearchOptions &headersearchopts,
                 const PreprocessorOptions &ppopts,
-                const CodeGenOptions &CodeGenOpts, llvm::Module &M,
+                const CodeGenOptions &CodeGenOpts,
+                const DebugOptions &DebugOpts, llvm::Module &M,
                 DiagnosticsEngine &Diags,
                 CoverageSourceInfo *CoverageInfo = nullptr);
 
@@ -746,6 +749,7 @@ class CodeGenModule : public CodeGenTypeCache {
   const PreprocessorOptions &getPreprocessorOpts()
     const { return PreprocessorOpts; }
   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
+  const DebugOptions &getDebugOpts() const { return DebugOpts; }
   llvm::Module &getModule() const { return TheModule; }
   DiagnosticsEngine &getDiags() const { return Diags; }
   const llvm::DataLayout &getDataLayout() const {
diff --git a/clang/lib/CodeGen/ModuleBuilder.cpp b/clang/lib/CodeGen/ModuleBuilder.cpp
index 3594f4c66e67745..898949e73fc234a 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -37,6 +37,7 @@ namespace {
     const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
     const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
     const CodeGenOptions &CodeGenOpts;
+    const DebugOptions &DebugOpts;
 
     unsigned HandlingTopLevelDecls;
 
@@ -79,11 +80,11 @@ namespace {
                       IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
                       const HeaderSearchOptions &HSO,
                       const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
-                      llvm::LLVMContext &C,
+                      const DebugOptions &DO, llvm::LLVMContext &C,
                       CoverageSourceInfo *CoverageInfo = nullptr)
         : Diags(diags), Ctx(nullptr), FS(std::move(FS)), HeaderSearchOpts(HSO),
-          PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
-          CoverageInfo(CoverageInfo),
+          PreprocessorOpts(PPO), CodeGenOpts(CGO), DebugOpts(DO),
+          HandlingTopLevelDecls(0), CoverageInfo(CoverageInfo),
           M(new llvm::Module(ExpandModuleName(ModuleName, CGO), C)) {
       C.setDiscardValueNames(CGO.DiscardValueNames);
     }
@@ -161,9 +162,9 @@ namespace {
       if (auto TVSDKVersion =
               Ctx->getTargetInfo().getDarwinTargetVariantSDKVersion())
         M->setDarwinTargetVariantSDKVersion(*TVSDKVersion);
-      Builder.reset(new CodeGen::CodeGenModule(Context, FS, HeaderSearchOpts,
-                                               PreprocessorOpts, CodeGenOpts,
-                                               *M, Diags, CoverageInfo));
+      Builder.reset(new CodeGen::CodeGenModule(
+          Context, FS, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts,
+          DebugOpts, *M, Diags, CoverageInfo));
 
       for (auto &&Lib : CodeGenOpts.DependentLibraries)
         Builder->AddDependentLib(Lib);
@@ -365,9 +366,10 @@ clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
                          IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
                          const HeaderSearchOptions &HeaderSearchOpts,
                          const PreprocessorOptions &PreprocessorOpts,
-                         const CodeGenOptions &CGO, llvm::LLVMContext &C,
+                         const CodeGenOptions &CGO, const DebugOptions &DO,
+                         llvm::LLVMContext &C,
                          CoverageSourceInfo *CoverageInfo) {
   return new CodeGeneratorImpl(Diags, ModuleName, std::move(FS),
-                               HeaderSearchOpts, PreprocessorOpts, CGO, C,
+                               HeaderSearchOpts, PreprocessorOpts, CGO, DO, C,
                                CoverageInfo);
 }
diff --git a/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp b/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
index ee543e40b46099d..cee48f71f1af02a 100644
--- a/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
+++ b/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
@@ -49,6 +49,7 @@ class PCHContainerGenerator : public ASTConsumer {
   const HeaderSearchOptions &HeaderSearchOpts;
   const PreprocessorOptions &PreprocessorOpts;
   CodeGenOptions CodeGenOpts;
+  DebugOptions DebugOpts;
   const TargetOptions TargetOpts;
   LangOptions LangOpts;
   std::unique_ptr<llvm::LLVMContext> VMContext;
@@ -154,18 +155,17 @@ class PCHContainerGenerator : public ASTConsumer {
     // ThreadModel, but the backend expects them to be nonempty.
     CodeGenOpts.CodeModel = "default";
     LangOpts.setThreadModel(LangOptions::ThreadModelKind::Single);
-    CodeGenOpts.DebugTypeExtRefs = true;
+    DebugOpts.DebugTypeExtRefs = true;
     // When building a module MainFileName is the name of the modulemap file.
     CodeGenOpts.MainFileName =
         LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
-    CodeGenOpts.setDebugInfo(llvm::codegenoptions::FullDebugInfo);
-    CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
-    CodeGenOpts.DwarfVersion = CI.getCodeGenOpts().DwarfVersion;
-    CodeGenOpts.DebugCompilationDir =
-        CI.getInvocation().getCodeGenOpts().DebugCompilationDir;
-    CodeGenOpts.DebugPrefixMap =
-        CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
-    CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
+    DebugOpts.setDebugInfo(llvm::debugoptions::FullDebugInfo);
+    DebugOpts.setDebuggerTuning(CI.getDebugOpts().getDebuggerTuning());
+    DebugOpts.DwarfVersion = CI.getDebugOpts().DwarfVersion;
+    DebugOpts.DebugCompilationDir =
+        CI.getInvocation().getDebugOpts().DebugCompilationDir;
+    DebugOpts.DebugPrefixMap = CI.getInvocation().getDebugOpts().DebugPrefixMap;
+    DebugOpts.DebugStrictDwarf = CI.getDebugOpts().DebugStrictDwarf;
   }
 
   ~PCHContainerGenerator() override = default;
@@ -177,8 +177,9 @@ class PCHContainerGenerator : public ASTConsumer {
     VMContext.reset(new llvm::LLVMContext());
     M.reset(new llvm::Module(MainFileName, *VMContext));
     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
-    Builder.reset(new CodeGen::CodeGenModule(
-        *Ctx, FS, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
+    Builder.reset(new CodeGen::CodeGenModule(*Ctx, FS, HeaderSearchOpts,
+                                             PreprocessorOpts, CodeGenOpts,
+                                             DebugOpts, *M, Diags));
 
     // Prepare CGDebugInfo to emit debug info for a clang module.
     auto *DI = Builder->getModuleDebugInfo();
@@ -321,7 +322,7 @@ class PCHContainerGenerator : public ASTConsumer {
       // Print the IR for the PCH container to the debug output.
       llvm::SmallString<0> Buffer;
       clang::EmitBackendOutput(
-          Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
+          Diags, HeaderSearchOpts, CodeGenOpts, DebugOpts, TargetOpts, LangOpts,
           Ctx.getTargetInfo().getDataLayoutString(), M.get(),
           BackendAction::Backend_EmitLL, FS,
           std::make_unique<llvm::raw_svector_ostream>(Buffer));
@@ -329,8 +330,8 @@ class PCHContainerGenerator : public ASTConsumer {
     });
 
     // Use the LLVM backend to emit the pch container.
-    clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
-                             LangOpts,
+    clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, DebugOpts,
+                             TargetOpts, LangOpts,
                              Ctx.getTargetInfo().getDataLayoutString(), M.get(),
                              BackendAction::Backend_EmitObj, FS, std::move(OS));
 
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index bcba7cbbdb58c29..0e3c84b435e59ce 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -860,7 +860,7 @@ static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
 
 static void
 RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
-                        llvm::codegenoptions::DebugInfoKind DebugInfoKind,
+                        llvm::debugoptions::DebugInfoKind DebugInfoKind,
                         unsigned DwarfVersion,
                         llvm::DebuggerKind DebuggerTuning) {
   addDebugInfoKind(CmdArgs, DebugInfoKind);
@@ -2623,7 +2623,7 @@ static void CollectArgsForIntegratedAssembler(Compilation &C,
           CmdArgs.push_back(Value.data());
         } else {
           RenderDebugEnablingArgs(Args, CmdArgs,
-                                  llvm::codegenoptions::DebugInfoConstructor,
+                                  llvm::debugoptions::DebugInfoConstructor,
                                   DwarfVersion, llvm::DebuggerKind::Default);
         }
       } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
@@ -4233,12 +4233,12 @@ static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
   DwarfFormatArg->render(Args, CmdArgs);
 }
 
-static void
-renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
-                   const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
-                   const InputInfo &Output,
-                   llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
-                   DwarfFissionKind &DwarfFission) {
+static void renderDebugOptions(const ToolChain &TC, const Driver &D,
+                               const llvm::Triple &T, const ArgList &Args,
+                               bool IRInput, ArgStringList &CmdArgs,
+                               const InputInfo &Output,
+                               llvm::debugoptions::DebugInfoKind &DebugInfoKind,
+                               DwarfFissionKind &DwarfFission) {
   if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
                    options::OPT_fno_debug_info_for_profiling, false) &&
       checkDebugInfoOption(
@@ -4273,7 +4273,7 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
     }
   }
   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
-    DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
+    DebugInfoKind = llvm::debugoptions::DebugInfoConstructor;
 
     // If the last option explicitly specified a debug-info level, use it.
     if (checkDebugInfoOption(A, Args, D, TC) &&
@@ -4283,9 +4283,9 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
       // complicated if you've disabled inline info in the skeleton CUs
       // (SplitDWARFInlining) - then there's value in composing split-dwarf and
       // line-tables-only, so let those compose naturally in that case.
-      if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
-          DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
-          (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
+      if (DebugInfoKind == llvm::debugoptions::NoDebugInfo ||
+          DebugInfoKind == llvm::debugoptions::DebugDirectivesOnly ||
+          (DebugInfoKind == llvm::debugoptions::DebugLineTablesOnly &&
            SplitDWARFInlining))
         DwarfFission = DwarfFissionKind::None;
     }
@@ -4320,12 +4320,12 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
   // If the user asked for debug info but did not explicitly specify -gcodeview
   // or -gdwarf, ask the toolchain for the default format.
   if (!EmitCodeView && !EmitDwarf &&
-      DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
+      DebugInfoKind != llvm::debugoptions::NoDebugInfo) {
     switch (TC.getDefaultDebugFormat()) {
-    case llvm::codegenoptions::DIF_CodeView:
+    case llvm::debugoptions::DIF_CodeView:
       EmitCodeView = true;
       break;
-    case llvm::codegenoptions::DIF_DWARF:
+    case llvm::debugoptions::DIF_DWARF:
       EmitDwarf = true;
       break;
     }
@@ -4345,8 +4345,8 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
 
   // -gline-directives-only supported only for the DWARF debug info.
   if (RequestedDWARFVersion == 0 &&
-      DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
-    DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
+      DebugInfoKind == llvm::debugoptions::DebugDirectivesOnly)
+    DebugInfoKind = llvm::debugoptions::NoDebugInfo;
 
   // strict DWARF is set to false by default. But for DBX, we need it to be set
   // as true by default.
@@ -4379,9 +4379,9 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
     // wins.
     if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
                              TC)) {
-      if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
-          DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
-        DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
+      if (DebugInfoKind != llvm::debugoptions::DebugLineTablesOnly &&
+          DebugInfoKind != llvm::debugoptions::DebugDirectivesOnly) {
+        DebugInfoKind = llvm::debugoptions::DebugInfoConstructor;
         CmdArgs.push_back("-dwarf-ext-refs");
         CmdArgs.push_back("-fmodule-format=obj");
       }
@@ -4403,13 +4403,13 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
   if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
     (void)checkDebugInfoOption(A, Args, D, TC);
 
-  if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
-      DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
+  if (DebugInfoKind == llvm::debugoptions::LimitedDebugInfo ||
+      DebugInfoKind == llvm::debugoptions::DebugInfoConstructor) {
     if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
                      options::OPT_feliminate_unused_debug_types, false))
-      DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
+      DebugInfoKind = llvm::debugoptions::UnusedTypeInfo;
     else if (NeedFullDebug)
-      DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
+      DebugInfoKind = llvm::debugoptions::FullDebugInfo;
   }
 
   if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
@@ -4447,8 +4447,8 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
 
   // When emitting remarks, we need at least debug lines in the output.
   if (willEmitRemarks(Args) &&
-      DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
-    DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
+      DebugInfoKind <= llvm::debugoptions::DebugDirectivesOnly)
+    DebugInfoKind = llvm::debugoptions::DebugLineTablesOnly;
 
   // Adjust the debug info kind for the given toolchain.
   TC.adjustDebugInfoKind(DebugInfoKind, Args);
@@ -4554,7 +4554,7 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
   // This controls whether or not we perform JustMyCode instrumentation.
   if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
     if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
-      if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
+      if (DebugInfoKind >= llvm::debugoptions::DebugInfoConstructor)
         CmdArgs.push_back("-fjmc");
       else if (D.IsCLMode())
         D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
@@ -5838,8 +5838,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
   if (D.IsCLMode())
     AddClangCLArgs(Args, InputType, CmdArgs);
 
-  llvm::codegenoptions::DebugInfoKind DebugInfoKind =
-      llvm::codegenoptions::NoDebugInfo;
+  llvm::debugoptions::DebugInfoKind DebugInfoKind =
+      llvm::debugoptions::NoDebugInfo;
   DwarfFissionKind DwarfFission = DwarfFissionKind::None;
   renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
                      CmdArgs, Output, DebugInfoKind, DwarfFission);
@@ -7692,7 +7692,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
 
   if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
       (EH || UnwindTables || AsyncUnwindTables ||
-       DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
+       DebugInfoKind != llvm::debugoptions::NoDebugInfo))
     CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
 
   if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
@@ -8322,8 +8322,8 @@ void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
     WantDebug = !A->getOption().matches(options::OPT_g0) &&
                 !A->getOption().matches(options::OPT_ggdb0);
 
-  llvm::codegenoptions::DebugInfoKind DebugInfoKind =
-      llvm::codegenoptions::NoDebugInfo;
+  llvm::debugoptions::DebugInfoKind DebugInfoKind =
+      llvm::debugoptions::NoDebugInfo;
 
   // Add the -fdebug-compilation-dir flag if needed.
   const char *DebugCompilationDir =
@@ -8335,8 +8335,8 @@ void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
     // the guard for source type, however there is a test which asserts
     // that some assembler invocation receives no -debug-info-kind,
     // and it's not clear whether that test is just overly restrictive.
-    DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
-                               : llvm::codegenoptions::NoDebugInfo);
+    DebugInfoKind = (WantDebug ? llvm::debugoptions::DebugInfoConstructor
+                               : llvm::debugoptions::NoDebugInfo);
 
     addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
                          CmdArgs);
@@ -8453,7 +8453,7 @@ void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
 
   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
 
-  if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
+  if (DebugInfoKind > llvm::debugoptions::NoDebugInfo && Output.isFilename())
     addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
                        Output.getFilename());
 
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index fadaf3e60c6616a..cb29edde130dd4f 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1957,25 +1957,25 @@ unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
   return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
 }
 
-void tools::addDebugInfoKind(
-    ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) {
+void tools::addDebugInfoKind(ArgStringList &CmdArgs,
+                             llvm::debugoptions::DebugInfoKind DebugInfoKind) {
   switch (DebugInfoKind) {
-  case llvm::codegenoptions::DebugDirectivesOnly:
+  case llvm::debugoptions::DebugDirectivesOnly:
     CmdArgs.push_back("-debug-info-kind=line-directives-only");
     break;
-  case llvm::codegenoptions::DebugLineTablesOnly:
+  case llvm::debugoptions::DebugLineTablesOnly:
     CmdArgs.push_back("-debug-info-kind=line-tables-only");
     break;
-  case llvm::codegenoptions::DebugInfoConstructor:
+  case llvm::debugoptions::DebugInfoConstructor:
     CmdArgs.push_back("-debug-info-kind=constructor");
     break;
-  case llvm::codegenoptions::LimitedDebugInfo:
+  case llvm::debugoptions::LimitedDebugInfo:
     CmdArgs.push_back("-debug-info-kind=limited");
     break;
-  case llvm::codegenoptions::FullDebugInfo:
+  case llvm::debugoptions::FullDebugInfo:
     CmdArgs.push_back("-debug-info-kind=standalone");
     break;
-  case llvm::codegenoptions::UnusedTypeInfo:
+  case llvm::debugoptions::UnusedTypeInfo:
     CmdArgs.push_back("-debug-info-kind=unused-types");
     break;
   default:
@@ -1985,18 +1985,18 @@ void tools::addDebugInfoKind(
 
 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
 // to the corresponding DebugInfoKind.
-llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) {
+llvm::debugoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) {
   assert(A.getOption().matches(options::OPT_gN_Group) &&
          "Not a -g option that specifies a debug-info level");
   if (A.getOption().matches(options::OPT_g0) ||
       A.getOption().matches(options::OPT_ggdb0))
-    return llvm::codegenoptions::NoDebugInfo;
+    return llvm::debugoptions::NoDebugInfo;
   if (A.getOption().matches(options::OPT_gline_tables_only) ||
       A.getOption().matches(options::OPT_ggdb1))
-    return llvm::codegenoptions::DebugLineTablesOnly;
+    return llvm::debugoptions::DebugLineTablesOnly;
   if (A.getOption().matches(options::OPT_gline_directives_only))
-    return llvm::codegenoptions::DebugDirectivesOnly;
-  return llvm::codegenoptions::DebugInfoConstructor;
+    return llvm::debugoptions::DebugDirectivesOnly;
+  return llvm::debugoptions::DebugInfoConstructor;
 }
 
 static unsigned ParseDebugDefaultVersion(const ToolChain &TC,
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.h b/clang/lib/Driver/ToolChains/CommonArgs.h
index 25d68345a9f9ebf..d5aa31a3427f41c 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.h
+++ b/clang/lib/Driver/ToolChains/CommonArgs.h
@@ -87,10 +87,9 @@ unsigned ParseFunctionAlignment(const ToolChain &TC,
                                 const llvm::opt::ArgList &Args);
 
 void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs,
-                      llvm::codegenoptions::DebugInfoKind DebugInfoKind);
+                      llvm::debugoptions::DebugInfoKind DebugInfoKind);
 
-llvm::codegenoptions::DebugInfoKind
-debugLevelToInfoKind(const llvm::opt::Arg &A);
+llvm::debugoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A);
 
 // Extract the integer N from a string spelled "-dwarf-N", returning 0
 // on mismatch. The StringRef input (rather than an Arg) allows
diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp b/clang/lib/Driver/ToolChains/Cuda.cpp
index 1462576ca870e6f..4ea925b3f064154 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -768,14 +768,14 @@ bool NVPTXToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const {
 }
 
 void NVPTXToolChain::adjustDebugInfoKind(
-    llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
+    llvm::debugoptions::DebugInfoKind &DebugInfoKind,
     const ArgList &Args) const {
   switch (mustEmitDebugInfo(Args)) {
   case DisableDebugInfo:
-    DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
+    DebugInfoKind = llvm::debugoptions::NoDebugInfo;
     break;
   case DebugDirectivesOnly:
-    DebugInfoKind = llvm::codegenoptions::DebugDirectivesOnly;
+    DebugInfoKind = llvm::debugoptions::DebugDirectivesOnly;
     break;
   case EmitSameDebugInfoAsHost:
     // Use same debug info level as the host.
diff --git a/clang/lib/Driver/ToolChains/Cuda.h b/clang/lib/Driver/ToolChains/Cuda.h
index 8a053f3393e1206..d49438d9d0325e9 100644
--- a/clang/lib/Driver/ToolChains/Cuda.h
+++ b/clang/lib/Driver/ToolChains/Cuda.h
@@ -161,7 +161,7 @@ class LLVM_LIBRARY_VISIBILITY NVPTXToolChain : public ToolChain {
   bool IsMathErrnoDefault() const override { return false; }
 
   bool supportsDebugInfoOption(const llvm::opt::Arg *A) const override;
-  void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
+  void adjustDebugInfoKind(llvm::debugoptions::DebugInfoKind &DebugInfoKind,
                            const llvm::opt::ArgList &Args) const override;
 
   // NVPTX supports only DWARF2.
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp
index 03d68c3df7fb374..8adbc44f79b0f3f 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -122,14 +122,14 @@ void Flang::addOtherOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
                    options::OPT_fconvert_EQ, options::OPT_fpass_plugin_EQ,
                    options::OPT_funderscoring, options::OPT_fno_underscoring});
 
-  llvm::codegenoptions::DebugInfoKind DebugInfoKind;
+  llvm::debugoptions::DebugInfoKind DebugInfoKind;
   if (Args.hasArg(options::OPT_gN_Group)) {
     Arg *gNArg = Args.getLastArg(options::OPT_gN_Group);
     DebugInfoKind = debugLevelToInfoKind(*gNArg);
   } else if (Args.hasArg(options::OPT_g_Flag)) {
-    DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
+    DebugInfoKind = llvm::debugoptions::DebugLineTablesOnly;
   } else {
-    DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
+    DebugInfoKind = llvm::debugoptions::NoDebugInfo;
   }
   addDebugInfoKind(CmdArgs, DebugInfoKind);
 }
diff --git a/clang/lib/Driver/ToolChains/HIPSPV.cpp b/clang/lib/Driver/ToolChains/HIPSPV.cpp
index a144b28057f4c20..8c31475b24e4842 100644
--- a/clang/lib/Driver/ToolChains/HIPSPV.cpp
+++ b/clang/lib/Driver/ToolChains/HIPSPV.cpp
@@ -279,10 +279,10 @@ VersionTuple HIPSPVToolChain::computeMSVCVersion(const Driver *D,
 }
 
 void HIPSPVToolChain::adjustDebugInfoKind(
-    llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
+    llvm::debugoptions::DebugInfoKind &DebugInfoKind,
     const llvm::opt::ArgList &Args) const {
   // Debug info generation is disabled for SPIRV-LLVM-Translator
   // which currently aborts on the presence of DW_OP_LLVM_convert.
   // TODO: Enable debug info when the SPIR-V backend arrives.
-  DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
+  DebugInfoKind = llvm::debugoptions::NoDebugInfo;
 }
diff --git a/clang/lib/Driver/ToolChains/HIPSPV.h b/clang/lib/Driver/ToolChains/HIPSPV.h
index ecd82e7052e48aa..781c96ccbf602cd 100644
--- a/clang/lib/Driver/ToolChains/HIPSPV.h
+++ b/clang/lib/Driver/ToolChains/HIPSPV.h
@@ -77,7 +77,7 @@ class LLVM_LIBRARY_VISIBILITY HIPSPVToolChain final : public ToolChain {
   computeMSVCVersion(const Driver *D,
                      const llvm::opt::ArgList &Args) const override;
 
-  void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
+  void adjustDebugInfoKind(llvm::debugoptions::DebugInfoKind &DebugInfoKind,
                            const llvm::opt::ArgList &Args) const override;
   bool IsMathErrnoDefault() const override { return false; }
   bool useIntegratedAs() const override { return true; }
diff --git a/clang/lib/Driver/ToolChains/MSVC.h b/clang/lib/Driver/ToolChains/MSVC.h
index 48369e030aade2f..cbc46f03ea5fd0f 100644
--- a/clang/lib/Driver/ToolChains/MSVC.h
+++ b/clang/lib/Driver/ToolChains/MSVC.h
@@ -60,10 +60,9 @@ class LLVM_LIBRARY_VISIBILITY MSVCToolChain : public ToolChain {
   /// Set CodeView as the default debug info format for non-MachO binary
   /// formats, and to DWARF otherwise. Users can use -gcodeview and -gdwarf to
   /// override the default.
-  llvm::codegenoptions::DebugInfoFormat getDefaultDebugFormat() const override {
-    return getTriple().isOSBinFormatMachO()
-               ? llvm::codegenoptions::DIF_DWARF
-               : llvm::codegenoptions::DIF_CodeView;
+  llvm::debugoptions::DebugInfoFormat getDefaultDebugFormat() const override {
+    return getTriple().isOSBinFormatMachO() ? llvm::debugoptions::DIF_DWARF
+                                            : llvm::debugoptions::DIF_CodeView;
   }
 
   /// Set the debugger tuning to "default", since we're definitely not tuning
diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp
index a25aa88bd85ef42..510b0517de8dd77 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -281,7 +281,7 @@ static void collectVFSEntries(CompilerInstance &CI,
 
 // Diagnostics
 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
-                               const CodeGenOptions *CodeGenOpts,
+                               const DebugOptions *DebugOpts,
                                DiagnosticsEngine &Diags) {
   std::error_code EC;
   std::unique_ptr<raw_ostream> StreamOwner;
@@ -304,8 +304,8 @@ static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
   // Chain in the diagnostic client which will log the diagnostics.
   auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
                                                         std::move(StreamOwner));
-  if (CodeGenOpts)
-    Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
+  if (DebugOpts)
+    Logger->setDwarfDebugFlags(DebugOpts->DwarfDebugFlags);
   if (Diags.ownsClient()) {
     Diags.setClient(
         new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
@@ -332,15 +332,13 @@ static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
 
 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
                                          bool ShouldOwnClient) {
-  Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
-                                  ShouldOwnClient, &getCodeGenOpts());
+  Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client, ShouldOwnClient,
+                                  &getDebugOpts());
 }
 
-IntrusiveRefCntPtr<DiagnosticsEngine>
-CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
-                                    DiagnosticConsumer *Client,
-                                    bool ShouldOwnClient,
-                                    const CodeGenOptions *CodeGenOpts) {
+IntrusiveRefCntPtr<DiagnosticsEngine> CompilerInstance::createDiagnostics(
+    DiagnosticOptions *Opts, DiagnosticConsumer *Client, bool ShouldOwnClient,
+    const DebugOptions *DebugOpts) {
   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
   IntrusiveRefCntPtr<DiagnosticsEngine>
       Diags(new DiagnosticsEngine(DiagID, Opts));
@@ -360,7 +358,7 @@ CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
 
   // Chain in -diagnostic-log-file dumper, if requested.
   if (!Opts->DiagnosticLogFile.empty())
-    SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
+    SetUpDiagnosticLog(Opts, DebugOpts, *Diags);
 
   if (!Opts->DiagnosticSerializationFile.empty())
     SetupSerializedDiagnostics(Opts, *Diags,
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp
index 7edea7798af1ef0..4d5e1929c0704e7 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -146,6 +146,7 @@ CompilerInvocationBase::CompilerInvocationBase()
       MigratorOpts(std::make_shared<MigratorOptions>()),
       APINotesOpts(std::make_shared<APINotesOptions>()),
       CodeGenOpts(std::make_shared<CodeGenOptions>()),
+      DebugOpts(std::make_shared<DebugOptions>()),
       FSOpts(std::make_shared<FileSystemOptions>()),
       FrontendOpts(std::make_shared<FrontendOptions>()),
       DependencyOutputOpts(std::make_shared<DependencyOutputOptions>()),
@@ -163,6 +164,7 @@ CompilerInvocationBase::deep_copy_assign(const CompilerInvocationBase &X) {
     MigratorOpts = make_shared_copy(X.getMigratorOpts());
     APINotesOpts = make_shared_copy(X.getAPINotesOpts());
     CodeGenOpts = make_shared_copy(X.getCodeGenOpts());
+    DebugOpts = make_shared_copy(X.getDebugOpts());
     FSOpts = make_shared_copy(X.getFileSystemOpts());
     FrontendOpts = make_shared_copy(X.getFrontendOpts());
     DependencyOutputOpts = make_shared_copy(X.getDependencyOutputOpts());
@@ -183,6 +185,7 @@ CompilerInvocationBase::shallow_copy_assign(const CompilerInvocationBase &X) {
     MigratorOpts = X.MigratorOpts;
     APINotesOpts = X.APINotesOpts;
     CodeGenOpts = X.CodeGenOpts;
+    DebugOpts = X.DebugOpts;
     FSOpts = X.FSOpts;
     FrontendOpts = X.FrontendOpts;
     DependencyOutputOpts = X.DependencyOutputOpts;
@@ -243,6 +246,10 @@ CodeGenOptions &CowCompilerInvocation::getMutCodeGenOpts() {
   return ensureOwned(CodeGenOpts);
 }
 
+DebugOptions &CowCompilerInvocation::getMutDebugOpts() {
+  return ensureOwned(DebugOpts);
+}
+
 FileSystemOptions &CowCompilerInvocation::getMutFileSystemOpts() {
   return ensureOwned(FSOpts);
 }
@@ -1478,40 +1485,6 @@ void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts,
   else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
     GenerateArg(Consumer, OPT_fno_direct_access_external_data);
 
-  std::optional<StringRef> DebugInfoVal;
-  switch (Opts.DebugInfo) {
-  case llvm::codegenoptions::DebugLineTablesOnly:
-    DebugInfoVal = "line-tables-only";
-    break;
-  case llvm::codegenoptions::DebugDirectivesOnly:
-    DebugInfoVal = "line-directives-only";
-    break;
-  case llvm::codegenoptions::DebugInfoConstructor:
-    DebugInfoVal = "constructor";
-    break;
-  case llvm::codegenoptions::LimitedDebugInfo:
-    DebugInfoVal = "limited";
-    break;
-  case llvm::codegenoptions::FullDebugInfo:
-    DebugInfoVal = "standalone";
-    break;
-  case llvm::codegenoptions::UnusedTypeInfo:
-    DebugInfoVal = "unused-types";
-    break;
-  case llvm::codegenoptions::NoDebugInfo: // default value
-    DebugInfoVal = std::nullopt;
-    break;
-  case llvm::codegenoptions::LocTrackingOnly: // implied value
-    DebugInfoVal = std::nullopt;
-    break;
-  }
-  if (DebugInfoVal)
-    GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal);
-
-  for (const auto &Prefix : Opts.DebugPrefixMap)
-    GenerateArg(Consumer, OPT_fdebug_prefix_map_EQ,
-                Prefix.first + "=" + Prefix.second);
-
   for (const auto &Prefix : Opts.CoveragePrefixMap)
     GenerateArg(Consumer, OPT_fcoverage_prefix_map_EQ,
                 Prefix.first + "=" + Prefix.second);
@@ -1537,21 +1510,6 @@ void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts,
   if (!Opts.BinutilsVersion.empty())
     GenerateArg(Consumer, OPT_fbinutils_version_EQ, Opts.BinutilsVersion);
 
-  if (Opts.DebugNameTable ==
-      static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
-    GenerateArg(Consumer, OPT_ggnu_pubnames);
-  else if (Opts.DebugNameTable ==
-           static_cast<unsigned>(
-               llvm::DICompileUnit::DebugNameTableKind::Default))
-    GenerateArg(Consumer, OPT_gpubnames);
-
-  auto TNK = Opts.getDebugSimpleTemplateNames();
-  if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
-    if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
-      GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "simple");
-    else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
-      GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "mangled");
-  }
   // ProfileInstrumentUsePath is marshalled automatically, no need to generate
   // it or PGOUseInstrumentor.
 
@@ -1690,12 +1648,70 @@ void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts,
   }
 }
 
-bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
-                                          InputKind IK,
-                                          DiagnosticsEngine &Diags,
-                                          const llvm::Triple &T,
-                                          const std::string &OutputFile,
-                                          const LangOptions &LangOptsRef) {
+void CompilerInvocationBase::GenerateDebugArgs(const DebugOptions &Opts,
+                                               ArgumentConsumer Consumer) {
+  const DebugOptions &DebugOpts = Opts;
+
+#define DEBUG_OPTION_WITH_MARSHALLING(...)                                     \
+  GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
+#include "clang/Driver/Options.inc"
+#undef DEBUG_OPTION_WITH_MARSHALLING
+
+  std::optional<StringRef> DebugInfoVal;
+  switch (Opts.DebugInfo) {
+  case llvm::debugoptions::DebugLineTablesOnly:
+    DebugInfoVal = "line-tables-only";
+    break;
+  case llvm::debugoptions::DebugDirectivesOnly:
+    DebugInfoVal = "line-directives-only";
+    break;
+  case llvm::debugoptions::DebugInfoConstructor:
+    DebugInfoVal = "constructor";
+    break;
+  case llvm::debugoptions::LimitedDebugInfo:
+    DebugInfoVal = "limited";
+    break;
+  case llvm::debugoptions::FullDebugInfo:
+    DebugInfoVal = "standalone";
+    break;
+  case llvm::debugoptions::UnusedTypeInfo:
+    DebugInfoVal = "unused-types";
+    break;
+  case llvm::debugoptions::NoDebugInfo: // default value
+    DebugInfoVal = std::nullopt;
+    break;
+  case llvm::debugoptions::LocTrackingOnly: // implied value
+    DebugInfoVal = std::nullopt;
+    break;
+  }
+  if (DebugInfoVal)
+    GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal);
+
+  for (const auto &Prefix : Opts.DebugPrefixMap)
+    GenerateArg(Consumer, OPT_fdebug_prefix_map_EQ,
+                Prefix.first + "=" + Prefix.second);
+
+  if (Opts.DebugNameTable ==
+      static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
+    GenerateArg(Consumer, OPT_ggnu_pubnames);
+  else if (Opts.DebugNameTable ==
+           static_cast<unsigned>(
+               llvm::DICompileUnit::DebugNameTableKind::Default))
+    GenerateArg(Consumer, OPT_gpubnames);
+
+  auto TNK = Opts.getDebugSimpleTemplateNames();
+  if (TNK != llvm::debugoptions::DebugTemplateNamesKind::Full) {
+    if (TNK == llvm::debugoptions::DebugTemplateNamesKind::Simple)
+      GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "simple");
+    else if (TNK == llvm::debugoptions::DebugTemplateNamesKind::Mangled)
+      GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "mangled");
+  }
+}
+
+bool CompilerInvocation::ParseCodeGenArgs(
+    CodeGenOptions &Opts, DebugOptions &DebugOpts, ArgList &Args, InputKind IK,
+    DiagnosticsEngine &Diags, const llvm::Triple &T,
+    const std::string &OutputFile, const LangOptions &LangOptsRef) {
   unsigned NumErrorsBefore = Diags.getNumErrors();
 
   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
@@ -1722,6 +1738,11 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
 #include "clang/Driver/Options.inc"
 #undef CODEGEN_OPTION_WITH_MARSHALLING
 
+#define DEBUG_OPTION_WITH_MARSHALLING(...)                                     \
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
+#include "clang/Driver/Options.inc"
+#undef DEBUG_OPTION_WITH_MARSHALLING
+
   // At O0 we want to fully disable inlining outside of cases marked with
   // 'alwaysinline' that are required for correctness.
   if (Opts.OptimizationLevel == 0) {
@@ -1752,19 +1773,20 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
   if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
     unsigned Val =
         llvm::StringSwitch<unsigned>(A->getValue())
-            .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
+            .Case("line-tables-only", llvm::debugoptions::DebugLineTablesOnly)
             .Case("line-directives-only",
-                  llvm::codegenoptions::DebugDirectivesOnly)
-            .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
-            .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
-            .Case("standalone", llvm::codegenoptions::FullDebugInfo)
-            .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
+                  llvm::debugoptions::DebugDirectivesOnly)
+            .Case("constructor", llvm::debugoptions::DebugInfoConstructor)
+            .Case("limited", llvm::debugoptions::LimitedDebugInfo)
+            .Case("standalone", llvm::debugoptions::FullDebugInfo)
+            .Case("unused-types", llvm::debugoptions::UnusedTypeInfo)
             .Default(~0U);
     if (Val == ~0U)
       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
                                                 << A->getValue();
     else
-      Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val));
+      DebugOpts.setDebugInfo(
+          static_cast<llvm::debugoptions::DebugInfoKind>(Val));
   }
 
   // If -fuse-ctor-homing is set and limited debug info is already on, then use
@@ -1772,16 +1794,16 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
   if (const Arg *A =
           Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
     if (A->getOption().matches(OPT_fuse_ctor_homing) &&
-        Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
-      Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
+        DebugOpts.getDebugInfo() == llvm::debugoptions::LimitedDebugInfo)
+      DebugOpts.setDebugInfo(llvm::debugoptions::DebugInfoConstructor);
     if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
-        Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
-      Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
+        DebugOpts.getDebugInfo() == llvm::debugoptions::DebugInfoConstructor)
+      DebugOpts.setDebugInfo(llvm::debugoptions::LimitedDebugInfo);
   }
 
   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
     auto Split = StringRef(Arg).split('=');
-    Opts.DebugPrefixMap.emplace_back(Split.first, Split.second);
+    DebugOpts.DebugPrefixMap.emplace_back(Split.first, Split.second);
   }
 
   for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
@@ -1794,14 +1816,15 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
       llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
       llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
 
-  if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
+  if (Opts.OptimizationLevel > 0 && DebugOpts.hasReducedDebugInfo() &&
       llvm::is_contained(DebugEntryValueArchs, T.getArch()))
     Opts.EmitCallSiteInfo = true;
 
-  if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
+  if (!DebugOpts.EnableDIPreservationVerify &&
+      DebugOpts.DIBugsReportFilePath.size()) {
     Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
-        << Opts.DIBugsReportFilePath;
-    Opts.DIBugsReportFilePath = "";
+        << DebugOpts.DIBugsReportFilePath;
+    DebugOpts.DIBugsReportFilePath = "";
   }
 
   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
@@ -1816,21 +1839,21 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
   Opts.BinutilsVersion =
       std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
 
-  Opts.DebugNameTable = static_cast<unsigned>(
+  DebugOpts.DebugNameTable = static_cast<unsigned>(
       Args.hasArg(OPT_ggnu_pubnames)
           ? llvm::DICompileUnit::DebugNameTableKind::GNU
-          : Args.hasArg(OPT_gpubnames)
-                ? llvm::DICompileUnit::DebugNameTableKind::Default
-                : llvm::DICompileUnit::DebugNameTableKind::None);
+      : Args.hasArg(OPT_gpubnames)
+          ? llvm::DICompileUnit::DebugNameTableKind::Default
+          : llvm::DICompileUnit::DebugNameTableKind::None);
   if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
     StringRef Value = A->getValue();
     if (Value != "simple" && Value != "mangled")
       Diags.Report(diag::err_drv_unsupported_option_argument)
           << A->getSpelling() << A->getValue();
-    Opts.setDebugSimpleTemplateNames(
+    DebugOpts.setDebugSimpleTemplateNames(
         StringRef(A->getValue()) == "simple"
-            ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
-            : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
+            ? llvm::debugoptions::DebugTemplateNamesKind::Simple
+            : llvm::debugoptions::DebugTemplateNamesKind::Mangled);
   }
 
   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
@@ -2145,8 +2168,8 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
   // If the user requested a flag that requires source locations available in
   // the backend, make sure that the backend tracks source location information.
   if (NeedLocTracking &&
-      Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
-    Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
+      DebugOpts.getDebugInfo() == llvm::debugoptions::NoDebugInfo)
+    DebugOpts.setDebugInfo(llvm::debugoptions::LocTrackingOnly);
 
   // Parse -fsanitize-recover= arguments.
   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
@@ -4643,8 +4666,8 @@ bool CompilerInvocation::CreateFromArgsImpl(
   if (LangOpts.OpenMPIsTargetDevice)
     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
 
-  ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
-                   Res.getFrontendOpts().OutputFile, LangOpts);
+  ParseCodeGenArgs(Res.getCodeGenOpts(), Res.getDebugOpts(), Args, DashX, Diags,
+                   T, Res.getFrontendOpts().OutputFile, LangOpts);
 
   // FIXME: Override value name discarding when asan or msan is used because the
   // backend passes depend on the name of the alloca in order to print out
@@ -4676,7 +4699,7 @@ bool CompilerInvocation::CreateFromArgsImpl(
   }
 
   // Store the command-line for using in the CodeView backend.
-  if (Res.getCodeGenOpts().CodeViewCommandLine) {
+  if (Res.getDebugOpts().CodeViewCommandLine) {
     Res.getCodeGenOpts().Argv0 = Argv0;
     append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
   }
@@ -4808,15 +4831,14 @@ std::string CompilerInvocation::getModuleHash() const {
 
   // When compiling with -gmodules, also hash -fdebug-prefix-map as it
   // affects the debug info in the PCM.
-  if (getCodeGenOpts().DebugTypeExtRefs)
-    HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
+  if (getDebugOpts().DebugTypeExtRefs)
+    HBuilder.addRange(getDebugOpts().DebugPrefixMap);
 
   // Extend the signature with the affecting debug options.
   if (getHeaderSearchOpts().ModuleFormat == "obj") {
-#define DEBUGOPT(Name, Bits, Default) HBuilder.add(CodeGenOpts->Name);
-#define VALUE_DEBUGOPT(Name, Bits, Default) HBuilder.add(CodeGenOpts->Name);
+#define DEBUGOPT(Name, Bits, Default) HBuilder.add(DebugOpts->Name);
 #define ENUM_DEBUGOPT(Name, Type, Bits, Default)                               \
-  HBuilder.add(static_cast<unsigned>(CodeGenOpts->get##Name()));
+  HBuilder.add(static_cast<unsigned>(DebugOpts->get##Name()));
 #define BENIGN_DEBUGOPT(Name, Bits, Default)
 #define BENIGN_VALUE_DEBUGOPT(Name, Bits, Default)
 #define BENIGN_ENUM_DEBUGOPT(Name, Type, Bits, Default)
@@ -4852,6 +4874,7 @@ void CompilerInvocationBase::generateCC1CommandLine(
   GenerateLangArgs(getLangOpts(), Consumer, T, getFrontendOpts().DashX);
   GenerateCodeGenArgs(getCodeGenOpts(), Consumer, T,
                       getFrontendOpts().OutputFile, &getLangOpts());
+  GenerateDebugArgs(getDebugOpts(), Consumer);
   GeneratePreprocessorArgs(getPreprocessorOpts(), Consumer, getLangOpts(),
                            getFrontendOpts(), getCodeGenOpts());
   GeneratePreprocessorOutputArgs(getPreprocessorOutputOpts(), Consumer,
@@ -4869,7 +4892,8 @@ std::vector<std::string> CompilerInvocationBase::getCC1CommandLine() const {
 void CompilerInvocation::resetNonModularOptions() {
   getLangOpts().resetNonModularOptions();
   getPreprocessorOpts().resetNonModularOptions();
-  getCodeGenOpts().resetNonModularOptions(getHeaderSearchOpts().ModuleFormat);
+  getCodeGenOpts().resetNonModularOptions();
+  getDebugOpts().resetNonModularOptions(getHeaderSearchOpts().ModuleFormat);
 }
 
 void CompilerInvocation::clearImplicitModuleBuildOptions() {
diff --git a/clang/lib/Frontend/Rewrite/FrontendActions.cpp b/clang/lib/Frontend/Rewrite/FrontendActions.cpp
index cf5a9437e89e6c2..6bec124381b9b06 100644
--- a/clang/lib/Frontend/Rewrite/FrontendActions.cpp
+++ b/clang/lib/Frontend/Rewrite/FrontendActions.cpp
@@ -168,8 +168,8 @@ RewriteObjCAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
       return CreateModernObjCRewriter(std::string(InFile), std::move(OS),
                                       CI.getDiagnostics(), CI.getLangOpts(),
                                       CI.getDiagnosticOpts().NoRewriteMacros,
-                                      (CI.getCodeGenOpts().getDebugInfo() !=
-                                       llvm::codegenoptions::NoDebugInfo));
+                                      (CI.getDebugOpts().getDebugInfo() !=
+                                       llvm::debugoptions::NoDebugInfo));
     return CreateObjCRewriter(std::string(InFile), std::move(OS),
                               CI.getDiagnostics(), CI.getLangOpts(),
                               CI.getDiagnosticOpts().NoRewriteMacros);
diff --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index bfaa897851041db..dfd940728642b66 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -124,9 +124,9 @@ makeCommonInvocationForModuleBuild(CompilerInvocation CI) {
 
   // TODO: Figure out better way to set options to their default value.
   CI.getCodeGenOpts().MainFileName.clear();
-  CI.getCodeGenOpts().DwarfDebugFlags.clear();
+  CI.getDebugOpts().DwarfDebugFlags.clear();
   if (!CI.getLangOpts().ModulesCodegen) {
-    CI.getCodeGenOpts().DebugCompilationDir.clear();
+    CI.getDebugOpts().DebugCompilationDir.clear();
     CI.getCodeGenOpts().CoverageCompilationDir.clear();
     CI.getCodeGenOpts().CoverageDataFile.clear();
     CI.getCodeGenOpts().CoverageNotesFile.clear();
diff --git a/clang/tools/clang-import-test/clang-import-test.cpp b/clang/tools/clang-import-test/clang-import-test.cpp
index 2473e16a546dc0b..6e3880dbf337f14 100644
--- a/clang/tools/clang-import-test/clang-import-test.cpp
+++ b/clang/tools/clang-import-test/clang-import-test.cpp
@@ -200,7 +200,7 @@ std::unique_ptr<CompilerInstance> BuildCompilerInstance() {
   Inv->getLangOpts().CXXExceptions = true;
   // Needed for testing dynamic_cast.
   Inv->getLangOpts().RTTI = true;
-  Inv->getCodeGenOpts().setDebugInfo(llvm::codegenoptions::FullDebugInfo);
+  Inv->getDebugOpts().setDebugInfo(llvm::debugoptions::FullDebugInfo);
   Inv->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
 
   Ins->setInvocation(std::move(Inv));
@@ -232,7 +232,7 @@ std::unique_ptr<CodeGenerator> BuildCodeGen(CompilerInstance &CI,
   return std::unique_ptr<CodeGenerator>(CreateLLVMCodeGen(
       CI.getDiagnostics(), ModuleName, &CI.getVirtualFileSystem(),
       CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
-      LLVMCtx));
+      CI.getDebugOpts(), LLVMCtx));
 }
 } // namespace init_convenience
 
diff --git a/clang/unittests/CodeGen/TestCompiler.h b/clang/unittests/CodeGen/TestCompiler.h
index 891489cb511a4fb..0b2c3e6040dfa5b 100644
--- a/clang/unittests/CodeGen/TestCompiler.h
+++ b/clang/unittests/CodeGen/TestCompiler.h
@@ -59,7 +59,8 @@ struct TestCompiler {
     CG.reset(CreateLLVMCodeGen(
         compiler.getDiagnostics(), "main-module",
         &compiler.getVirtualFileSystem(), compiler.getHeaderSearchOpts(),
-        compiler.getPreprocessorOpts(), compiler.getCodeGenOpts(), Context));
+        compiler.getPreprocessorOpts(), compiler.getCodeGenOpts(),
+        compiler.getDebugOpts(), Context));
   }
 
   void init(const char *TestProgram,
diff --git a/clang/unittests/Frontend/CodeGenActionTest.cpp b/clang/unittests/Frontend/CodeGenActionTest.cpp
index a6520910c83996b..2a6a14b73271735 100644
--- a/clang/unittests/Frontend/CodeGenActionTest.cpp
+++ b/clang/unittests/Frontend/CodeGenActionTest.cpp
@@ -95,7 +95,7 @@ TEST(CodeGenTest, DebugInfoCWDCodeGen) {
       FrontendInputFile("test.cpp", Language::CXX));
   Invocation->getFrontendOpts().ProgramAction = EmitLLVM;
   Invocation->getTargetOpts().Triple = "x86_64-unknown-linux-gnu";
-  Invocation->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
+  Invocation->getDebugOpts().setDebugInfo(debugoptions::FullDebugInfo);
   CompilerInstance Compiler;
 
   SmallString<256> IRBuffer;
diff --git a/clang/unittests/Frontend/CompilerInvocationTest.cpp b/clang/unittests/Frontend/CompilerInvocationTest.cpp
index 7912253b761e9ba..6e6ff7918c72677 100644
--- a/clang/unittests/Frontend/CompilerInvocationTest.cpp
+++ b/clang/unittests/Frontend/CompilerInvocationTest.cpp
@@ -256,7 +256,7 @@ TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentNone) {
   const char *Args[] = {""};
 
   ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
-  ASSERT_FALSE(Invocation.getCodeGenOpts().NoInlineLineTables);
+  ASSERT_FALSE(Invocation.getDebugOpts().NoInlineLineTables);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
   ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-ginline-line-tables"))));
@@ -267,7 +267,7 @@ TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentNegChange) {
   const char *Args[] = {"-gno-inline-line-tables"};
 
   ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
-  ASSERT_TRUE(Invocation.getCodeGenOpts().NoInlineLineTables);
+  ASSERT_TRUE(Invocation.getDebugOpts().NoInlineLineTables);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
   ASSERT_THAT(GeneratedArgs, Contains(StrEq("-gno-inline-line-tables")));
@@ -279,7 +279,7 @@ TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentPosReset) {
 
   // Driver-only flag.
   ASSERT_FALSE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
-  ASSERT_FALSE(Invocation.getCodeGenOpts().NoInlineLineTables);
+  ASSERT_FALSE(Invocation.getDebugOpts().NoInlineLineTables);
 }
 
 // Boolean option with a keypath that defaults to false.
@@ -290,7 +290,7 @@ TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentNoneX) {
   const char *Args[] = {""};
 
   ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
-  ASSERT_FALSE(Invocation.getCodeGenOpts().CodeViewGHash);
+  ASSERT_FALSE(Invocation.getDebugOpts().CodeViewGHash);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
   ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-gcodeview-ghash"))));
@@ -301,7 +301,7 @@ TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentPosChange) {
   const char *Args[] = {"-gcodeview-ghash"};
 
   ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
-  ASSERT_TRUE(Invocation.getCodeGenOpts().CodeViewGHash);
+  ASSERT_TRUE(Invocation.getDebugOpts().CodeViewGHash);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
   ASSERT_THAT(GeneratedArgs, Contains(StrEq("-gcodeview-ghash")));
@@ -313,7 +313,7 @@ TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentNegReset) {
 
   // Driver-only flag.
   ASSERT_FALSE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
-  ASSERT_FALSE(Invocation.getCodeGenOpts().CodeViewGHash);
+  ASSERT_FALSE(Invocation.getDebugOpts().CodeViewGHash);
 }
 
 // Boolean option with a keypath that defaults to an arbitrary expression.
@@ -1027,9 +1027,9 @@ TEST_F(CommandLineTest, RoundTrip) {
 
   ASSERT_TRUE(Invocation.getMigratorOpts().NoNSAllocReallocError);
 
-  ASSERT_EQ(Invocation.getCodeGenOpts().getDebugInfo(),
-            codegenoptions::DebugInfoKind::LimitedDebugInfo);
-  ASSERT_TRUE(Invocation.getCodeGenOpts().MacroDebugInfo);
+  ASSERT_EQ(Invocation.getDebugOpts().getDebugInfo(),
+            debugoptions::DebugInfoKind::LimitedDebugInfo);
+  ASSERT_TRUE(Invocation.getDebugOpts().MacroDebugInfo);
 
   ASSERT_EQ(Invocation.getDependencyOutputOpts().ShowIncludesDest,
             ShowIncludesDestination::Stdout);
diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
index 574d661e2a215e9..8960f10f020147b 100644
--- a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
+++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
@@ -695,7 +695,7 @@ ClangExpressionParser::ClangExpressionParser(
       m_compiler->getDiagnostics(), module_name,
       &m_compiler->getVirtualFileSystem(), m_compiler->getHeaderSearchOpts(),
       m_compiler->getPreprocessorOpts(), m_compiler->getCodeGenOpts(),
-      *m_llvm_context));
+      m_compiler->getDebugOpts(), *m_llvm_context));
 }
 
 ClangExpressionParser::~ClangExpressionParser() = default;
diff --git a/llvm/include/llvm/Frontend/Debug/Options.h b/llvm/include/llvm/Frontend/Debug/Options.h
index c490508d3793a35..38dd0627a3da978 100644
--- a/llvm/include/llvm/Frontend/Debug/Options.h
+++ b/llvm/include/llvm/Frontend/Debug/Options.h
@@ -10,7 +10,7 @@
 #define LLVM_FRONTEND_DEBUG_OPTIONS_H
 
 namespace llvm {
-namespace codegenoptions {
+namespace debugoptions {
 
 enum DebugInfoFormat {
   DIF_DWARF,
@@ -56,7 +56,7 @@ enum DebugInfoKind {
 
 enum class DebugTemplateNamesKind { Full, Simple, Mangled };
 
-} // end namespace codegenoptions
+} // namespace debugoptions
 } // end namespace llvm
 
 #endif

>From 9f76bbb619c872084fb40ad83d77885e14858d7e Mon Sep 17 00:00:00 2001
From: Juergen Ributzka <juergen at ributzka.de>
Date: Mon, 18 Dec 2023 10:25:59 -0800
Subject: [PATCH 2/8] Fix flang build

---
 .../include/flang/Frontend/CodeGenOptions.def |  2 +-
 flang/include/flang/Tools/CLOptions.inc       | 10 ++++-----
 flang/include/flang/Tools/CrossToolHelpers.h  |  4 ++--
 flang/lib/Frontend/CompilerInvocation.cpp     | 22 +++++++++----------
 4 files changed, 19 insertions(+), 19 deletions(-)

diff --git a/flang/include/flang/Frontend/CodeGenOptions.def b/flang/include/flang/Frontend/CodeGenOptions.def
index 9d03ec88a56b8a8..156c8cebe2817eb 100644
--- a/flang/include/flang/Frontend/CodeGenOptions.def
+++ b/flang/include/flang/Frontend/CodeGenOptions.def
@@ -36,7 +36,7 @@ CODEGENOPT(AliasAnalysis, 1, 0) ///< Enable alias analysis pass
 
 CODEGENOPT(Underscoring, 1, 1)
 ENUM_CODEGENOPT(RelocationModel, llvm::Reloc::Model, 3, llvm::Reloc::PIC_) ///< Name of the relocation model to use.
-ENUM_CODEGENOPT(DebugInfo,  llvm::codegenoptions::DebugInfoKind, 4,  llvm::codegenoptions::NoDebugInfo) ///< Level of debug info to generate
+ENUM_CODEGENOPT(DebugInfo,  llvm::debugoptions::DebugInfoKind, 4,  llvm::debugoptions::NoDebugInfo) ///< Level of debug info to generate
 ENUM_CODEGENOPT(VecLib, llvm::driver::VectorLibrary, 3, llvm::driver::VectorLibrary::NoLibrary) ///< Vector functions library to use
 ENUM_CODEGENOPT(FramePointer, llvm::FramePointerKind, 2, llvm::FramePointerKind::None) ///< Enable the usage of frame pointers
 
diff --git a/flang/include/flang/Tools/CLOptions.inc b/flang/include/flang/Tools/CLOptions.inc
index 96d3869cd093912..58be98511dd0ee9 100644
--- a/flang/include/flang/Tools/CLOptions.inc
+++ b/flang/include/flang/Tools/CLOptions.inc
@@ -57,8 +57,8 @@ namespace {
 const static llvm::OptimizationLevel &defaultOptLevel{
     llvm::OptimizationLevel::O0};
 
-const static llvm::codegenoptions::DebugInfoKind &NoDebugInfo{
-    llvm::codegenoptions::NoDebugInfo};
+const static llvm::debugoptions::DebugInfoKind &NoDebugInfo{
+    llvm::debugoptions::NoDebugInfo};
 
 /// Optimizer Passes
 DisableOption(CfgConversion, "cfg-conversion", "disable FIR to CFG pass");
@@ -281,13 +281,13 @@ inline void createOpenMPFIRPassPipeline(
 
 #if !defined(FLANG_EXCLUDE_CODEGEN)
 inline void createDebugPasses(
-    mlir::PassManager &pm, llvm::codegenoptions::DebugInfoKind debugLevel) {
+    mlir::PassManager &pm, llvm::debugoptions::DebugInfoKind debugLevel) {
   // Currently only -g1, -g, -gline-tables-only supported
   switch (debugLevel) {
-  case llvm::codegenoptions::DebugLineTablesOnly:
+  case llvm::debugoptions::DebugLineTablesOnly:
     addDebugFoundationPass(pm);
     return;
-  case llvm::codegenoptions::NoDebugInfo:
+  case llvm::debugoptions::NoDebugInfo:
     return;
   default:
     // TODO: Add cases and passes for other debug options.
diff --git a/flang/include/flang/Tools/CrossToolHelpers.h b/flang/include/flang/Tools/CrossToolHelpers.h
index b61224ff4f1b3cd..14514e36fb386a2 100644
--- a/flang/include/flang/Tools/CrossToolHelpers.h
+++ b/flang/include/flang/Tools/CrossToolHelpers.h
@@ -43,8 +43,8 @@ struct MLIRToLLVMPassPipelineConfig {
   bool Underscoring = true; ///< add underscores to function names.
   bool LoopVersioning = false; ///< Run the version loop pass.
   bool AliasAnalysis = false; ///< Add TBAA tags to generated LLVMIR
-  llvm::codegenoptions::DebugInfoKind DebugInfo =
-      llvm::codegenoptions::NoDebugInfo; ///< Debug info generation.
+  llvm::debugoptions::DebugInfoKind DebugInfo =
+      llvm::debugoptions::NoDebugInfo; ///< Debug info generation.
   llvm::FramePointerKind FramePointerKind =
       llvm::FramePointerKind::None; ///< Add frame pointer to functions.
   unsigned VScaleMin = 0; ///< SVE vector range minimum.
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp
index a3c41fb4611f562..a05607497c9e104 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -125,18 +125,18 @@ bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts,
 static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts,
                            llvm::opt::ArgList &args,
                            clang::DiagnosticsEngine &diags) {
-  using DebugInfoKind = llvm::codegenoptions::DebugInfoKind;
+  using DebugInfoKind = llvm::debugoptions::DebugInfoKind;
   if (llvm::opt::Arg *arg =
           args.getLastArg(clang::driver::options::OPT_debug_info_kind_EQ)) {
     std::optional<DebugInfoKind> val =
         llvm::StringSwitch<std::optional<DebugInfoKind>>(arg->getValue())
-            .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
+            .Case("line-tables-only", llvm::debugoptions::DebugLineTablesOnly)
             .Case("line-directives-only",
-                  llvm::codegenoptions::DebugDirectivesOnly)
-            .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
-            .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
-            .Case("standalone", llvm::codegenoptions::FullDebugInfo)
-            .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
+                  llvm::debugoptions::DebugDirectivesOnly)
+            .Case("constructor", llvm::debugoptions::DebugInfoConstructor)
+            .Case("limited", llvm::debugoptions::LimitedDebugInfo)
+            .Case("standalone", llvm::debugoptions::FullDebugInfo)
+            .Case("unused-types", llvm::debugoptions::UnusedTypeInfo)
             .Default(std::nullopt);
     if (!val.has_value()) {
       diags.Report(clang::diag::err_drv_invalid_value)
@@ -144,8 +144,8 @@ static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts,
       return false;
     }
     opts.setDebugInfo(val.value());
-    if (val != llvm::codegenoptions::DebugLineTablesOnly &&
-        val != llvm::codegenoptions::NoDebugInfo) {
+    if (val != llvm::debugoptions::DebugLineTablesOnly &&
+        val != llvm::debugoptions::NoDebugInfo) {
       const auto debugWarning = diags.getCustomDiagID(
           clang::DiagnosticsEngine::Warning, "Unsupported debug option: %0");
       diags.Report(debugWarning) << arg->getValue();
@@ -326,7 +326,7 @@ static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
       diags, args, clang::driver::options::OPT_Rpass_analysis_EQ,
       /*remarkOptName=*/"pass-analysis");
 
-  if (opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo) {
+  if (opts.getDebugInfo() == llvm::debugoptions::NoDebugInfo) {
     // If the user requested a flag that requires source locations available in
     // the backend, make sure that the backend tracks source location
     // information.
@@ -338,7 +338,7 @@ static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
                            opts.OptimizationRemarkAnalysis.hasValidPattern();
 
     if (needLocTracking)
-      opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
+      opts.setDebugInfo(llvm::debugoptions::LocTrackingOnly);
   }
 
   if (auto *a = args.getLastArg(clang::driver::options::OPT_save_temps_EQ))

>From ec6f7a21df56db2f7f8826a18adecccad0653fe0 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka <juergen at ributzka.de>
Date: Mon, 18 Dec 2023 10:37:07 -0800
Subject: [PATCH 3/8] Forward declare *Options in CompilerInvocation.h

---
 clang/include/clang/Frontend/CompilerInvocation.h      | 6 ++++--
 clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp | 1 +
 clang/lib/Frontend/CompilerInstance.cpp                | 2 ++
 clang/lib/Frontend/CompilerInvocation.cpp              | 1 +
 clang/lib/Frontend/FrontendAction.cpp                  | 1 +
 clang/lib/Frontend/Rewrite/FrontendActions.cpp         | 2 ++
 clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp   | 1 +
 7 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Frontend/CompilerInvocation.h b/clang/include/clang/Frontend/CompilerInvocation.h
index 0969a6bdda067ab..f2ccd03e3ce171d 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -10,8 +10,8 @@
 #define LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
 
 #include "clang/APINotes/APINotesOptions.h"
-#include "clang/Basic/CodeGenOptions.h"
-#include "clang/Basic/DebugOptions.h"
+// #include "clang/Basic/CodeGenOptions.h"
+// #include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Basic/LLVM.h"
@@ -47,6 +47,8 @@ class FileSystem;
 
 namespace clang {
 
+class CodeGenOptions;
+class DebugOptions;
 class DiagnosticsEngine;
 class HeaderSearchOptions;
 class PreprocessorOptions;
diff --git a/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp b/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
index cee48f71f1af02a..c04b278659cf559 100644
--- a/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
+++ b/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGen/BackendUtil.h"
diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp
index 510b0517de8dd77..3b7d61775790545 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -11,6 +11,8 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/CharInfo.h"
+#include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp
index 4d5e1929c0704e7..b5ceeead8de0332 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -12,6 +12,7 @@
 #include "clang/Basic/CharInfo.h"
 #include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/CommentOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticDriver.h"
 #include "clang/Basic/DiagnosticOptions.h"
diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp
index eff785b99a09a4f..7dbf41b613ee53c 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -11,6 +11,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/Basic/Builtins.h"
+#include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LangStandard.h"
diff --git a/clang/lib/Frontend/Rewrite/FrontendActions.cpp b/clang/lib/Frontend/Rewrite/FrontendActions.cpp
index 6bec124381b9b06..2b686f554fadfe1 100644
--- a/clang/lib/Frontend/Rewrite/FrontendActions.cpp
+++ b/clang/lib/Frontend/Rewrite/FrontendActions.cpp
@@ -9,6 +9,7 @@
 #include "clang/Rewrite/Frontend/FrontendActions.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/Basic/CharInfo.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/LangStandard.h"
 #include "clang/Config/config.h"
 #include "clang/Frontend/CompilerInstance.h"
@@ -24,6 +25,7 @@
 #include "clang/Serialization/ModuleFile.h"
 #include "clang/Serialization/ModuleManager.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/Frontend/Debug/Options.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
diff --git a/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
index b280a1359d2f272..c5ebc2a31dafd74 100644
--- a/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ b/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -12,6 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/ARCMigrate/ARCMTActions.h"
+#include "clang/Basic/CodeGenOptions.h"
 #include "clang/CodeGen/CodeGenAction.h"
 #include "clang/Config/config.h"
 #include "clang/Driver/Options.h"

>From 603d0e73fefa686ee0e6e9ebc8847206503ba8d1 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka <juergen at ributzka.de>
Date: Mon, 18 Dec 2023 16:41:23 -0800
Subject: [PATCH 4/8] More fixes.

---
 clang/lib/Interpreter/DeviceOffload.cpp                     | 1 +
 clang/lib/Interpreter/Interpreter.cpp                       | 1 +
 clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp | 2 ++
 clang/lib/Tooling/Tooling.cpp                               | 1 +
 clang/tools/clang-import-test/clang-import-test.cpp         | 1 +
 clang/unittests/CodeGen/TestCompiler.h                      | 1 +
 clang/unittests/Frontend/CodeGenActionTest.cpp              | 1 +
 clang/unittests/Frontend/CompilerInvocationTest.cpp         | 2 ++
 8 files changed, 10 insertions(+)

diff --git a/clang/lib/Interpreter/DeviceOffload.cpp b/clang/lib/Interpreter/DeviceOffload.cpp
index fb42964e4936f2d..624c9f8eb65e566 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -12,6 +12,7 @@
 
 #include "DeviceOffload.h"
 
+#include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/TargetOptions.h"
 #include "clang/CodeGen/ModuleBuilder.h"
 #include "clang/Frontend/CompilerInstance.h"
diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp
index 9f97a3c6b0be9e6..9d8abf9d123f0d2 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Mangle.h"
 #include "clang/AST/TypeVisitor.h"
+#include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGen/CodeGenAction.h"
diff --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index dfd940728642b66..88b20a5504fcff1 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -8,6 +8,8 @@
 
 #include "clang/Tooling/DependencyScanning/ModuleDepCollector.h"
 
+#include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/MakeSupport.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/Preprocessor.h"
diff --git a/clang/lib/Tooling/Tooling.cpp b/clang/lib/Tooling/Tooling.cpp
index c5c3cdb47e92e89..65ccea3092493b1 100644
--- a/clang/lib/Tooling/Tooling.cpp
+++ b/clang/lib/Tooling/Tooling.cpp
@@ -12,6 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Tooling/Tooling.h"
+#include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/DiagnosticOptions.h"
diff --git a/clang/tools/clang-import-test/clang-import-test.cpp b/clang/tools/clang-import-test/clang-import-test.cpp
index 6e3880dbf337f14..6dd5d53a8e88827 100644
--- a/clang/tools/clang-import-test/clang-import-test.cpp
+++ b/clang/tools/clang-import-test/clang-import-test.cpp
@@ -11,6 +11,7 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExternalASTMerger.h"
 #include "clang/Basic/Builtins.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/SourceLocation.h"
diff --git a/clang/unittests/CodeGen/TestCompiler.h b/clang/unittests/CodeGen/TestCompiler.h
index 0b2c3e6040dfa5b..9a81c2990c9deba 100644
--- a/clang/unittests/CodeGen/TestCompiler.h
+++ b/clang/unittests/CodeGen/TestCompiler.h
@@ -11,6 +11,7 @@
 
 
 #include "clang/AST/ASTConsumer.h"
+#include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "clang/CodeGen/ModuleBuilder.h"
diff --git a/clang/unittests/Frontend/CodeGenActionTest.cpp b/clang/unittests/Frontend/CodeGenActionTest.cpp
index 2a6a14b73271735..0d091bb6130fdc7 100644
--- a/clang/unittests/Frontend/CodeGenActionTest.cpp
+++ b/clang/unittests/Frontend/CodeGenActionTest.cpp
@@ -11,6 +11,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/CodeGen/CodeGenAction.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/LangStandard.h"
 #include "clang/CodeGen/BackendUtil.h"
 #include "clang/Frontend/CompilerInstance.h"
diff --git a/clang/unittests/Frontend/CompilerInvocationTest.cpp b/clang/unittests/Frontend/CompilerInvocationTest.cpp
index 6e6ff7918c72677..4f471c9993c2fca 100644
--- a/clang/unittests/Frontend/CompilerInvocationTest.cpp
+++ b/clang/unittests/Frontend/CompilerInvocationTest.cpp
@@ -7,6 +7,8 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/TargetOptions.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/TextDiagnosticBuffer.h"

>From 4e7d04f1f858f7be72704c683a81fc50aa254d95 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka <juergen at ributzka.de>
Date: Thu, 4 Jan 2024 12:30:40 -0800
Subject: [PATCH 5/8] Undo clang formating changes.

---
 .../include/clang/Frontend/CompilerInvocation.h  | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)

diff --git a/clang/include/clang/Frontend/CompilerInvocation.h b/clang/include/clang/Frontend/CompilerInvocation.h
index f2ccd03e3ce171d..716b8ed3033691b 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -10,8 +10,6 @@
 #define LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
 
 #include "clang/APINotes/APINotesOptions.h"
-// #include "clang/Basic/CodeGenOptions.h"
-// #include "clang/Basic/DebugOptions.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Basic/LLVM.h"
@@ -235,20 +233,20 @@ class CompilerInvocation : public CompilerInvocationBase {
   /// @{
   // Note: These need to be pulled in manually. Otherwise, they get hidden by
   // the mutable getters with the same names.
+  using CompilerInvocationBase::getLangOpts;
+  using CompilerInvocationBase::getTargetOpts;
+  using CompilerInvocationBase::getDiagnosticOpts;
+  using CompilerInvocationBase::getHeaderSearchOpts;
+  using CompilerInvocationBase::getPreprocessorOpts;
   using CompilerInvocationBase::getAnalyzerOpts;
+  using CompilerInvocationBase::getMigratorOpts;
   using CompilerInvocationBase::getAPINotesOpts;
   using CompilerInvocationBase::getCodeGenOpts;
   using CompilerInvocationBase::getDebugOpts;
-  using CompilerInvocationBase::getDependencyOutputOpts;
-  using CompilerInvocationBase::getDiagnosticOpts;
   using CompilerInvocationBase::getFileSystemOpts;
   using CompilerInvocationBase::getFrontendOpts;
-  using CompilerInvocationBase::getHeaderSearchOpts;
-  using CompilerInvocationBase::getLangOpts;
-  using CompilerInvocationBase::getMigratorOpts;
-  using CompilerInvocationBase::getPreprocessorOpts;
+  using CompilerInvocationBase::getDependencyOutputOpts;
   using CompilerInvocationBase::getPreprocessorOutputOpts;
-  using CompilerInvocationBase::getTargetOpts;
   /// @}
 
   /// Mutable getters.

>From 7fe0c8b0a72baa15e83c3a1ac568aac75f945187 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka <juergen at ributzka.de>
Date: Thu, 4 Jan 2024 13:06:23 -0800
Subject: [PATCH 6/8] Create a separate method to reset all codegen options.

---
 clang/include/clang/Basic/CodeGenOptions.h | 3 +++
 clang/lib/Basic/CodeGenOptions.cpp         | 5 ++++-
 2 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/CodeGenOptions.h b/clang/include/clang/Basic/CodeGenOptions.h
index fb615a3563d860f..38c69299005b584 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -485,6 +485,9 @@ class CodeGenOptions : public CodeGenOptionsBase {
            SanitizeBinaryMetadataUAR;
   }
 
+  /// Reset all of options to their default value.
+  void resetAllOptions();
+
   /// Reset all of the options that are not considered when building a
   /// module.
   void resetNonModularOptions();
diff --git a/clang/lib/Basic/CodeGenOptions.cpp b/clang/lib/Basic/CodeGenOptions.cpp
index 0e5a9b845d9542a..f4fc7e9ca5b3779 100644
--- a/clang/lib/Basic/CodeGenOptions.cpp
+++ b/clang/lib/Basic/CodeGenOptions.cpp
@@ -11,7 +11,10 @@
 
 namespace clang {
 
-CodeGenOptions::CodeGenOptions() { resetNonModularOptions(); }
+CodeGenOptions::CodeGenOptions() { resetAllOptions(); }
+
+// FIXME: really reset all codegen options.
+void CodeGenOptions::resetAllOptions() { resetNonModularOptions(); }
 
 void CodeGenOptions::resetNonModularOptions() {
 #define CODEGENOPT(Name, Bits, Default) Name = Default;

>From 7b3e0388d7ddb0c995dfa5821cce962839b979fd Mon Sep 17 00:00:00 2001
From: Juergen Ributzka <juergen at ributzka.de>
Date: Thu, 4 Jan 2024 13:51:09 -0800
Subject: [PATCH 7/8] Split out debug option parsing into its own method.

---
 .../clang/Frontend/CompilerInvocation.h       |  15 +-
 clang/lib/Frontend/CompilerInvocation.cpp     | 240 ++++++++++--------
 2 files changed, 135 insertions(+), 120 deletions(-)

diff --git a/clang/include/clang/Frontend/CompilerInvocation.h b/clang/include/clang/Frontend/CompilerInvocation.h
index 716b8ed3033691b..fb662e88a7a69bd 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -345,18 +345,17 @@ class CompilerInvocation : public CompilerInvocationBase {
                             DiagnosticsEngine &Diags);
 
   /// Parse command line options that map to CodeGenOptions.
-  static bool ParseCodeGenArgs(CodeGenOptions &Opts, DebugOptions &DebugOpts,
-                               llvm::opt::ArgList &Args, InputKind IK,
-                               DiagnosticsEngine &Diags, const llvm::Triple &T,
+  static bool ParseCodeGenArgs(CodeGenOptions &Opts, llvm::opt::ArgList &Args,
+                               InputKind IK, DiagnosticsEngine &Diags,
+                               const llvm::Triple &T,
                                const std::string &OutputFile,
                                const LangOptions &LangOptsRef);
 
   /// Parse command line options that map to DebugOptions.
-  static bool ParseDebugArgs(DebugOptions &Opts, llvm::opt::ArgList &Args,
-                             InputKind IK, DiagnosticsEngine &Diags,
-                             const llvm::Triple &T,
-                             const std::string &OutputFile,
-                             const LangOptions &LangOptsRef);
+  static bool ParseDebugArgs(DebugOptions &Opts,
+                             const CodeGenOptions &CodeGenOpts,
+                             llvm::opt::ArgList &Args, InputKind IK,
+                             DiagnosticsEngine &Diags);
 };
 
 /// Same as \c CompilerInvocation, but with copy-on-write optimization.
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp
index b5ceeead8de0332..921ab3ec019ac83 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -1709,10 +1709,12 @@ void CompilerInvocationBase::GenerateDebugArgs(const DebugOptions &Opts,
   }
 }
 
-bool CompilerInvocation::ParseCodeGenArgs(
-    CodeGenOptions &Opts, DebugOptions &DebugOpts, ArgList &Args, InputKind IK,
-    DiagnosticsEngine &Diags, const llvm::Triple &T,
-    const std::string &OutputFile, const LangOptions &LangOptsRef) {
+bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
+                                          InputKind IK,
+                                          DiagnosticsEngine &Diags,
+                                          const llvm::Triple &T,
+                                          const std::string &OutputFile,
+                                          const LangOptions &LangOptsRef) {
   unsigned NumErrorsBefore = Diags.getNumErrors();
 
   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
@@ -1739,11 +1741,6 @@ bool CompilerInvocation::ParseCodeGenArgs(
 #include "clang/Driver/Options.inc"
 #undef CODEGEN_OPTION_WITH_MARSHALLING
 
-#define DEBUG_OPTION_WITH_MARSHALLING(...)                                     \
-  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
-#include "clang/Driver/Options.inc"
-#undef DEBUG_OPTION_WITH_MARSHALLING
-
   // At O0 we want to fully disable inlining outside of cases marked with
   // 'alwaysinline' that are required for correctness.
   if (Opts.OptimizationLevel == 0) {
@@ -1771,63 +1768,11 @@ bool CompilerInvocation::ParseCodeGenArgs(
       (!Args.hasArg(OPT_fno_direct_access_external_data) &&
        LangOpts->PICLevel == 0);
 
-  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
-    unsigned Val =
-        llvm::StringSwitch<unsigned>(A->getValue())
-            .Case("line-tables-only", llvm::debugoptions::DebugLineTablesOnly)
-            .Case("line-directives-only",
-                  llvm::debugoptions::DebugDirectivesOnly)
-            .Case("constructor", llvm::debugoptions::DebugInfoConstructor)
-            .Case("limited", llvm::debugoptions::LimitedDebugInfo)
-            .Case("standalone", llvm::debugoptions::FullDebugInfo)
-            .Case("unused-types", llvm::debugoptions::UnusedTypeInfo)
-            .Default(~0U);
-    if (Val == ~0U)
-      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
-                                                << A->getValue();
-    else
-      DebugOpts.setDebugInfo(
-          static_cast<llvm::debugoptions::DebugInfoKind>(Val));
-  }
-
-  // If -fuse-ctor-homing is set and limited debug info is already on, then use
-  // constructor homing, and vice versa for -fno-use-ctor-homing.
-  if (const Arg *A =
-          Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
-    if (A->getOption().matches(OPT_fuse_ctor_homing) &&
-        DebugOpts.getDebugInfo() == llvm::debugoptions::LimitedDebugInfo)
-      DebugOpts.setDebugInfo(llvm::debugoptions::DebugInfoConstructor);
-    if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
-        DebugOpts.getDebugInfo() == llvm::debugoptions::DebugInfoConstructor)
-      DebugOpts.setDebugInfo(llvm::debugoptions::LimitedDebugInfo);
-  }
-
-  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
-    auto Split = StringRef(Arg).split('=');
-    DebugOpts.DebugPrefixMap.emplace_back(Split.first, Split.second);
-  }
-
   for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
     auto Split = StringRef(Arg).split('=');
     Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second);
   }
 
-  const llvm::Triple::ArchType DebugEntryValueArchs[] = {
-      llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
-      llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
-      llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
-
-  if (Opts.OptimizationLevel > 0 && DebugOpts.hasReducedDebugInfo() &&
-      llvm::is_contained(DebugEntryValueArchs, T.getArch()))
-    Opts.EmitCallSiteInfo = true;
-
-  if (!DebugOpts.EnableDIPreservationVerify &&
-      DebugOpts.DIBugsReportFilePath.size()) {
-    Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
-        << DebugOpts.DIBugsReportFilePath;
-    DebugOpts.DIBugsReportFilePath = "";
-  }
-
   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
                            Args.hasArg(OPT_new_struct_path_tbaa);
   Opts.OptimizeSize = getOptimizationLevelSize(Args);
@@ -1840,23 +1785,6 @@ bool CompilerInvocation::ParseCodeGenArgs(
   Opts.BinutilsVersion =
       std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
 
-  DebugOpts.DebugNameTable = static_cast<unsigned>(
-      Args.hasArg(OPT_ggnu_pubnames)
-          ? llvm::DICompileUnit::DebugNameTableKind::GNU
-      : Args.hasArg(OPT_gpubnames)
-          ? llvm::DICompileUnit::DebugNameTableKind::Default
-          : llvm::DICompileUnit::DebugNameTableKind::None);
-  if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
-    StringRef Value = A->getValue();
-    if (Value != "simple" && Value != "mangled")
-      Diags.Report(diag::err_drv_unsupported_option_argument)
-          << A->getSpelling() << A->getValue();
-    DebugOpts.setDebugSimpleTemplateNames(
-        StringRef(A->getValue()) == "simple"
-            ? llvm::debugoptions::DebugTemplateNamesKind::Simple
-            : llvm::debugoptions::DebugTemplateNamesKind::Mangled);
-  }
-
   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
     Opts.TimePasses = true;
 
@@ -2083,20 +2011,11 @@ bool CompilerInvocation::ParseCodeGenArgs(
         << A->getSpelling() << T.str();
   }
 
-  bool NeedLocTracking = false;
-
-  if (!Opts.OptRecordFile.empty())
-    NeedLocTracking = true;
-
-  if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
+  if (Arg *A = Args.getLastArg(OPT_opt_record_passes))
     Opts.OptRecordPasses = A->getValue();
-    NeedLocTracking = true;
-  }
 
-  if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
+  if (Arg *A = Args.getLastArg(OPT_opt_record_format))
     Opts.OptRecordFormat = A->getValue();
-    NeedLocTracking = true;
-  }
 
   Opts.OptimizationRemark =
       ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
@@ -2107,13 +2026,8 @@ bool CompilerInvocation::ParseCodeGenArgs(
   Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
       Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
 
-  NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
-                     Opts.OptimizationRemarkMissed.hasValidPattern() ||
-                     Opts.OptimizationRemarkAnalysis.hasValidPattern();
-
-  bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
   bool UsingProfile =
-      UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
+      !Opts.SampleProfileFile.empty() || !Opts.ProfileInstrumentUsePath.empty();
 
   if (Opts.DiagnosticsWithHotness && !UsingProfile &&
       // An IR file will contain PGO as metadata
@@ -2157,21 +2071,6 @@ bool CompilerInvocation::ParseCodeGenArgs(
     }
   }
 
-  // If the user requested to use a sample profile for PGO, then the
-  // backend will need to track source location information so the profile
-  // can be incorporated into the IR.
-  if (UsingSampleProfile)
-    NeedLocTracking = true;
-
-  if (!Opts.StackUsageOutput.empty())
-    NeedLocTracking = true;
-
-  // If the user requested a flag that requires source locations available in
-  // the backend, make sure that the backend tracks source location information.
-  if (NeedLocTracking &&
-      DebugOpts.getDebugInfo() == llvm::debugoptions::NoDebugInfo)
-    DebugOpts.setDebugInfo(llvm::debugoptions::LocTrackingOnly);
-
   // Parse -fsanitize-recover= arguments.
   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
   parseSanitizerKinds("-fsanitize-recover=",
@@ -2196,6 +2095,111 @@ bool CompilerInvocation::ParseCodeGenArgs(
   return Diags.getNumErrors() == NumErrorsBefore;
 }
 
+bool CompilerInvocation::ParseDebugArgs(DebugOptions &DebugOpts,
+                                        const CodeGenOptions &CodeGenOpts,
+                                        llvm::opt::ArgList &Args, InputKind IK,
+                                        DiagnosticsEngine &Diags) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
+#define DEBUG_OPTION_WITH_MARSHALLING(...)                                     \
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
+#include "clang/Driver/Options.inc"
+#undef DEBUG_OPTION_WITH_MARSHALLING
+
+  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
+    unsigned Val =
+        llvm::StringSwitch<unsigned>(A->getValue())
+            .Case("line-tables-only", llvm::debugoptions::DebugLineTablesOnly)
+            .Case("line-directives-only",
+                  llvm::debugoptions::DebugDirectivesOnly)
+            .Case("constructor", llvm::debugoptions::DebugInfoConstructor)
+            .Case("limited", llvm::debugoptions::LimitedDebugInfo)
+            .Case("standalone", llvm::debugoptions::FullDebugInfo)
+            .Case("unused-types", llvm::debugoptions::UnusedTypeInfo)
+            .Default(~0U);
+    if (Val == ~0U)
+      Diags.Report(diag::err_drv_invalid_value)
+          << A->getAsString(Args) << A->getValue();
+    else
+      DebugOpts.setDebugInfo(
+          static_cast<llvm::debugoptions::DebugInfoKind>(Val));
+  }
+
+  // If -fuse-ctor-homing is set and limited debug info is already on, then use
+  // constructor homing, and vice versa for -fno-use-ctor-homing.
+  if (const Arg *A =
+          Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
+    if (A->getOption().matches(OPT_fuse_ctor_homing) &&
+        DebugOpts.getDebugInfo() == llvm::debugoptions::LimitedDebugInfo)
+      DebugOpts.setDebugInfo(llvm::debugoptions::DebugInfoConstructor);
+    if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
+        DebugOpts.getDebugInfo() == llvm::debugoptions::DebugInfoConstructor)
+      DebugOpts.setDebugInfo(llvm::debugoptions::LimitedDebugInfo);
+  }
+
+  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
+    auto Split = StringRef(Arg).split('=');
+    DebugOpts.DebugPrefixMap.emplace_back(Split.first, Split.second);
+  }
+
+  if (!DebugOpts.EnableDIPreservationVerify &&
+      DebugOpts.DIBugsReportFilePath.size()) {
+    Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
+        << DebugOpts.DIBugsReportFilePath;
+    DebugOpts.DIBugsReportFilePath = "";
+  }
+
+  DebugOpts.DebugNameTable = static_cast<unsigned>(
+      Args.hasArg(OPT_ggnu_pubnames)
+          ? llvm::DICompileUnit::DebugNameTableKind::GNU
+      : Args.hasArg(OPT_gpubnames)
+          ? llvm::DICompileUnit::DebugNameTableKind::Default
+          : llvm::DICompileUnit::DebugNameTableKind::None);
+  if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
+    StringRef Value = A->getValue();
+    if (Value != "simple" && Value != "mangled")
+      Diags.Report(diag::err_drv_unsupported_option_argument)
+          << A->getSpelling() << A->getValue();
+    DebugOpts.setDebugSimpleTemplateNames(
+        StringRef(A->getValue()) == "simple"
+            ? llvm::debugoptions::DebugTemplateNamesKind::Simple
+            : llvm::debugoptions::DebugTemplateNamesKind::Mangled);
+  }
+
+  bool NeedLocTracking = false;
+
+  if (!CodeGenOpts.OptRecordFile.empty())
+    NeedLocTracking = true;
+
+  if (!CodeGenOpts.OptRecordPasses.empty())
+    NeedLocTracking = true;
+
+  if (!CodeGenOpts.OptRecordFormat.empty())
+    NeedLocTracking = true;
+
+  NeedLocTracking |= CodeGenOpts.OptimizationRemark.hasValidPattern() ||
+                     CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
+                     CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern();
+
+  // If the user requested to use a sample profile for PGO, then the
+  // backend will need to track source location information so the profile
+  // can be incorporated into the IR.
+  if (!CodeGenOpts.SampleProfileFile.empty())
+    NeedLocTracking = true;
+
+  if (!CodeGenOpts.StackUsageOutput.empty())
+    NeedLocTracking = true;
+
+  // // If the user requested a flag that requires source locations available in
+  // // the backend, make sure that the backend tracks source location
+  // information.
+  if (NeedLocTracking &&
+      DebugOpts.getDebugInfo() == llvm::debugoptions::NoDebugInfo)
+    DebugOpts.setDebugInfo(llvm::debugoptions::LocTrackingOnly);
+
+  return Diags.getNumErrors() == NumErrorsBefore;
+}
+
 static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
                                          ArgumentConsumer Consumer) {
   const DependencyOutputOptions &DependencyOutputOpts = Opts;
@@ -4667,8 +4671,20 @@ bool CompilerInvocation::CreateFromArgsImpl(
   if (LangOpts.OpenMPIsTargetDevice)
     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
 
-  ParseCodeGenArgs(Res.getCodeGenOpts(), Res.getDebugOpts(), Args, DashX, Diags,
-                   T, Res.getFrontendOpts().OutputFile, LangOpts);
+  ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
+                   Res.getFrontendOpts().OutputFile, LangOpts);
+
+  ParseDebugArgs(Res.getDebugOpts(), Res.getCodeGenOpts(), Args, DashX, Diags);
+
+  const llvm::Triple::ArchType DebugEntryValueArchs[] = {
+      llvm::Triple::x86,    llvm::Triple::x86_64, llvm::Triple::aarch64,
+      llvm::Triple::arm,    llvm::Triple::armeb,  llvm::Triple::mips,
+      llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
+
+  if (Res.getCodeGenOpts().OptimizationLevel > 0 &&
+      Res.getDebugOpts().hasReducedDebugInfo() &&
+      llvm::is_contained(DebugEntryValueArchs, T.getArch()))
+    Res.getCodeGenOpts().EmitCallSiteInfo = true;
 
   // FIXME: Override value name discarding when asan or msan is used because the
   // backend passes depend on the name of the alloca in order to print out

>From 17badf37c7901711593d70a04b6eed2a1a299df4 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka <juergen at ributzka.de>
Date: Tue, 23 Jan 2024 12:28:27 -0800
Subject: [PATCH 8/8] Fix after rebase.

---
 clang/lib/Frontend/InitPreprocessor.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/Frontend/InitPreprocessor.cpp b/clang/lib/Frontend/InitPreprocessor.cpp
index 1b91c86f91398cc..962ced13587bf35 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -10,6 +10,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "clang/Basic/CodeGenOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/HLSLRuntime.h"
 #include "clang/Basic/MacroBuilder.h"



More information about the cfe-commits mailing list