Author: Fangrui Song
Date: 2026-11-19T19:14:01-08:00
New Revision: 6183335b604e04d5562685f6317ffe4682ea0c51

URL: 
https://github.com/llvm/llvm-project/commit/6183335b604e04d5562685f6317ffe4682ea0c51
DIFF: 
https://github.com/llvm/llvm-project/commit/6183335b604e04d5562685f6317ffe4682ea0c51.diff

LOG: [CodeGen] Declare command line options of the machine scheduler in 
TableGen (#244327)

Renames, with the old spellings kept as aliases:

```
-enable-aa-sched-mi       -> -sched-mi-aa
-enable-store-sequencing  -> -store-sequencing
-use-tbaa-in-sched-mi     -> -sched-mi-tbaa
```

Renames without an alias, as the old spellings are generic or unused:

```
-check-early-avail       -> -vliw-misched-check-early-avail
-fast-cluster-threshold  -> -misched-fast-cluster-threshold
-force-fast-cluster      -> -misched-force-fast-cluster
-ignore-bb-reg-pressure  -> -vliw-misched-ignore-bb-reg-pressure
-misched-verbose-level   -> -vliw-misched-verbose-level
-use-newer-candidate     -> -vliw-misched-use-newer-candidate
-view-misched-cutoff     -> -misched-view-cutoff
-view-misched-dags       -> -misched-view-dags
```

Other changes:

* ViewMISchedDAGs and PrintDAGs are replaced with
  shouldViewMISchedDAGs(MF) and shouldPrintMISchedDAGs(MF), and
  getPreRADirection and shouldVerifyScheduling take a MachineFunction.
* MISched::Direction gets a fixed underlying type so that
  CodeGenOptions.h can forward-declare it.
* -misched-cluster=false and -misched-fusion=false are checked when the
  mutation is applied, so createLoadClusterDAGMutation,
  createStoreClusterDAGMutation and createMacroFusionDAGMutation no
  longer return null.
* ScheduleDAGInstrs.h declares llvm::CodeGenOptions, so
  BackendDiagnosticHandler.cpp, which reuses the CodeGen precompiled
  header, qualifies clang::CodeGenOptions.

LLM-aided

Added: 
    

Modified: 
    clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
    llvm/include/llvm/CodeGen/MachineScheduler.h
    llvm/include/llvm/CodeGen/ScheduleDAGInstrs.h
    llvm/lib/CodeGen/CodeGenOptions.cpp
    llvm/lib/CodeGen/CodeGenOptions.h
    llvm/lib/CodeGen/CodeGenOptions.td
    llvm/lib/CodeGen/DFAPacketizer.cpp
    llvm/lib/CodeGen/MachineScheduler.cpp
    llvm/lib/CodeGen/MacroFusion.cpp
    llvm/lib/CodeGen/ScheduleDAG.cpp
    llvm/lib/CodeGen/ScheduleDAGInstrs.cpp
    llvm/lib/CodeGen/VLIWMachineScheduler.cpp
    llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp
    llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
    llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp
    llvm/test/CodeGen/AArch64/aarch64-stp-cluster.ll

Removed: 
    


################################################################################
diff  --git a/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp 
b/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
index b8e391a760b89c..398ed4ed1747b9 100644
--- a/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
+++ b/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
@@ -28,7 +28,7 @@ namespace {
 /// Forwards llvm::DiagnosticHandler callbacks into a 
BackendDiagnosticConsumer.
 class BackendDiagnosticHandlerImpl final : public DiagnosticHandler {
 public:
-  BackendDiagnosticHandlerImpl(const CodeGenOptions &CGOpts,
+  BackendDiagnosticHandlerImpl(const clang::CodeGenOptions &CGOpts,
                                BackendDiagnosticConsumer *Consumer)
       : CodeGenOpts(CGOpts), Consumer(Consumer) {}
 
@@ -54,7 +54,7 @@ class BackendDiagnosticHandlerImpl final : public 
DiagnosticHandler {
   }
 
 private:
-  const CodeGenOptions &CodeGenOpts;
+  const clang::CodeGenOptions &CodeGenOpts;
   BackendDiagnosticConsumer *Consumer;
 };
 

diff  --git a/llvm/include/llvm/CodeGen/MachineScheduler.h 
b/llvm/include/llvm/CodeGen/MachineScheduler.h
index e5e675bc9792f2..f9be865656fa37 100644
--- a/llvm/include/llvm/CodeGen/MachineScheduler.h
+++ b/llvm/include/llvm/CodeGen/MachineScheduler.h
@@ -91,7 +91,6 @@
 #include "llvm/CodeGen/ScheduleDAGMutation.h"
 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
 #include "llvm/CodeGen/TargetSchedule.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <algorithm>
@@ -112,7 +111,7 @@ class PostMachineSchedulerImpl;
 } // namespace impl_detail
 
 namespace MISched {
-enum Direction {
+enum Direction : unsigned {
   Unspecified,
   TopDown,
   BottomUp,
@@ -121,19 +120,15 @@ enum Direction {
 } // namespace MISched
 
 /// Returns -misched-prera-direction.
-LLVM_ABI MISched::Direction getPreRADirection();
+LLVM_ABI MISched::Direction getPreRADirection(const MachineFunction &MF);
 /// Returns -misched-postra-break-antideps.
 LLVM_ABI TargetSubtargetInfo::AntiDepBreakMode getPostRABreakAntiDeps();
 /// Returns whether -verify-misched is set.
-LLVM_ABI bool shouldVerifyScheduling();
-
-#ifndef NDEBUG
-extern cl::opt<bool> ViewMISchedDAGs;
-extern cl::opt<bool> PrintDAGs;
-#else
-LLVM_ABI extern const bool ViewMISchedDAGs;
-LLVM_ABI extern const bool PrintDAGs;
-#endif
+LLVM_ABI bool shouldVerifyScheduling(const MachineFunction &MF);
+/// Return -misched-print-dags, which is false in a build without assertions.
+LLVM_ABI bool shouldPrintMISchedDAGs(const MachineFunction &MF);
+/// Return -misched-view-dags, which is false in a build without assertions.
+LLVM_ABI bool shouldViewMISchedDAGs(const MachineFunction &MF);
 
 class AAResults;
 class LiveIntervals;

diff  --git a/llvm/include/llvm/CodeGen/ScheduleDAGInstrs.h 
b/llvm/include/llvm/CodeGen/ScheduleDAGInstrs.h
index 7a080dccfb061e..ac16009168fe03 100644
--- a/llvm/include/llvm/CodeGen/ScheduleDAGInstrs.h
+++ b/llvm/include/llvm/CodeGen/ScheduleDAGInstrs.h
@@ -34,6 +34,7 @@
 namespace llvm {
 
   class AAResults;
+  struct CodeGenOptions;
   class LiveIntervals;
   class MachineFrameInfo;
   class MachineFunction;
@@ -107,6 +108,9 @@ namespace llvm {
 
   /// A ScheduleDAG for scheduling lists of MachineInstr.
   class LLVM_ABI ScheduleDAGInstrs : public ScheduleDAG {
+  public:
+    const CodeGenOptions &Opts;
+
   protected:
     const MachineLoopInfo *MLI = nullptr;
     const MachineFrameInfo &MFI;

diff  --git a/llvm/lib/CodeGen/CodeGenOptions.cpp 
b/llvm/lib/CodeGen/CodeGenOptions.cpp
index fc2f1b5086b5e8..ca8dfbe5f51e92 100644
--- a/llvm/lib/CodeGen/CodeGenOptions.cpp
+++ b/llvm/lib/CodeGen/CodeGenOptions.cpp
@@ -8,6 +8,7 @@
 
 #include "CodeGenOptions.h"
 #include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineScheduler.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"

diff  --git a/llvm/lib/CodeGen/CodeGenOptions.h 
b/llvm/lib/CodeGen/CodeGenOptions.h
index e423a93c3551e0..12a3da76d883d8 100644
--- a/llvm/lib/CodeGen/CodeGenOptions.h
+++ b/llvm/lib/CodeGen/CodeGenOptions.h
@@ -19,6 +19,10 @@ constexpr bool MachineCombinerVerifyPatternOrderDefault = 
true;
 #else
 constexpr bool MachineCombinerVerifyPatternOrderDefault = false;
 #endif
+
+namespace MISched {
+enum Direction : unsigned;
+} // namespace MISched
 } // namespace llvm
 
 #define OPTIONS_STRUCT_DECL

diff  --git a/llvm/lib/CodeGen/CodeGenOptions.td 
b/llvm/lib/CodeGen/CodeGenOptions.td
index dc2d091257cd5b..dfd838ce6d5ac9 100644
--- a/llvm/lib/CodeGen/CodeGenOptions.td
+++ b/llvm/lib/CodeGen/CodeGenOptions.td
@@ -109,6 +109,10 @@ defm : BoolField<"profile-unknown-in-special-section", 
"false",
   "In profiling mode like sampleFDO, if a function doesn't have profile, we 
cannot tell the function is cold for sure because it may be a function newly 
added without ever being sampled. "
   "With the flag enabled, compiler can put such profile unknown functions into 
a special section, so runtime system can choose to handle it in a 
diff erent way than .text section, to save RAM for example">;
 
+// DFAPacketizer.cpp
+defm : OptionalValueField<"dfa-instr-limit", "unsigned",
+  "If present, stops packetizing after N instructions">;
+
 // EarlyIfConversion.cpp
 defm : ValueField<"early-ifcvt-cold-edge-threshold", "unsigned", "1",
   "Cold edge probability threshold in percent for using no critical-path 
extension budget (0 disables the threshold)">;
@@ -258,6 +262,76 @@ defm : BoolField<"outliner-leaf-descendants", "true",
 // TODO: Remove the old spelling after 2027-05.
 def : AliasOf<"disable-global-outlining", "global-outlining=false">;
 
+// MachineScheduler.cpp
+defm : OptionalBoolField<"enable-misched",
+  "Enable the machine instruction scheduling pass">;
+defm : OptionalBoolField<"enable-post-misched",
+  "Enable the post-ra machine instruction scheduling pass">;
+defm : OptionalBoolField<"enable-ssa-misched",
+  "Enable the machine instruction scheduling pass in SSA">;
+defm : BoolField<"misched-cluster", "true",
+  "Enable memop clustering">;
+let Condition = AssertsOnly in
+defm : ValueField<"misched-cutoff", "unsigned", "~0U",
+  "Stop scheduling after N instructions">;
+defm : BoolField<"misched-cyclicpath", "true",
+  "Enable cyclic critical path analysis">;
+defm : BoolField<"misched-dcpl", "false",
+  "Print critical path length to stdout">;
+let Condition = AssertsOnly in {
+defm : BoolField<"misched-detail-resource-booking", "false",
+  "Show details of invoking getNextResoufceCycle">;
+defm : BoolField<"misched-dump-reserved-cycles", "false",
+  "Dump resource usage at schedule boundary">;
+defm : BoolField<"misched-dump-schedule-trace", "false",
+  "Dump resource usage at schedule boundary">;
+defm : ValueField<"misched-dump-schedule-trace-col-header-width", "unsigned", 
"19",
+  "Set width of the columns with the resources and schedule units">;
+defm : ValueField<"misched-dump-schedule-trace-col-width", "unsigned", "5",
+  "Set width of the columns showing resource booking">;
+}
+defm : ValueField<"misched-fast-cluster-threshold", "unsigned", "1000",
+  "The threshold for fast cluster">;
+defm : BoolField<"misched-force-fast-cluster", "false",
+  "Switch to fast cluster algorithm with the lost of some fusion 
opportunities">;
+// Avoid quadratic complexity in unusually large basic blocks by limiting the
+// size of the ready lists.
+defm : ValueField<"misched-limit", "unsigned", "256",
+  "Limit ready list to N instructions">;
+let Condition = AssertsOnly in {
+defm : OptionalValueField<"misched-only-block", "unsigned",
+  "Only schedule this MBB#">;
+defm : OptionalValueField<"misched-only-func", "StringRef",
+  "Only schedule this function">;
+}
+defm : EnumField<"misched-postra-direction", "MISched::Direction", "",
+  "topdown,bottomup,bidirectional",
+  ["MISched::TopDown", "MISched::BottomUp", "MISched::Bidirectional"],
+  "Post reg-alloc list scheduling direction">;
+defm : EnumField<"misched-prera-direction", "MISched::Direction", "",
+  "topdown,bottomup,bidirectional",
+  ["MISched::TopDown", "MISched::BottomUp", "MISched::Bidirectional"],
+  "Pre reg-alloc list scheduling direction">;
+let Condition = AssertsOnly in
+defm : BoolField<"misched-print-dags", "false",
+  "Print schedule DAGs">;
+defm : BoolField<"misched-regpressure", "true",
+  "Enable register pressure scheduling">;
+defm : ValueField<"misched-resource-cutoff", "unsigned", "10",
+  "Number of intervals to track">;
+let Condition = AssertsOnly in {
+defm : BoolField<"misched-sort-resources-in-trace", "true",
+  "Sort the resources printed in the dump trace">;
+// In some situations a few uninteresting nodes depend on nearly all other
+// nodes in the graph, provide a cutoff to hide them.
+defm : ValueField<"misched-view-cutoff", "unsigned", "0",
+  "Hide nodes with more predecessor/successor than cutoff">;
+defm : BoolField<"misched-view-dags", "false",
+  "Pop up a window to show MISched dags after they are processed">;
+}
+defm : BoolField<"verify-misched", "false",
+  "Verify machine instrs before and after machine scheduling">;
+
 // MachineSink.cpp
 defm : ValueField<"machine-sink-cycle-limit", "unsigned", "50",
   "The maximum number of instructions considered for cycle sinking">;
@@ -272,6 +346,10 @@ defm : 
ValueField<"machine-sink-split-probability-threshold", "unsigned", "40",
 defm : BoolField<"sink-insts-to-avoid-spills", "false",
   "Sink instructions into cycles to avoid register spills">;
 
+// MacroFusion.cpp
+defm : BoolField<"misched-fusion", "true",
+  "Enable scheduling for macro fusion">;
+
 // PHIElimination.cpp
 defm : BoolField<"phi-elim-edge-splitting", "true",
   "Enable critical edge splitting during PHI elimination">;
@@ -358,6 +436,42 @@ def : AliasOf<"safestack-use-pointer-address", 
"safe-stack-use-pointer-address">
 defm : BoolField<"safe-stack-layout", "true",
   "enable safe stack layout">;
 
+// ScheduleDAG.cpp
+let Condition = AssertsOnly in
+defm : BoolField<"stress-sched", "false",
+  "Stress test instruction scheduling">;
+
+// ScheduleDAGInstrs.cpp
+// Note: -dag-maps-huge-region and the -store-sequencing options might be used
+// in tuning compile time vs output quality. Setting -dag-maps-huge-region so
+// large that it will never be reached means best-effort, but may be slow.
+// FIXME(@cofibrant): Drop in favour of store-sequencing.
+// When the number of processed memops reaches this threshold, a reduction of
+// maps will be done.
+defm : ValueField<"dag-maps-huge-region", "unsigned", "500",
+  "The limit to use while constructing the DAG prior to scheduling, at which 
point a trade-off is made to avoid excessive compile time. Ignored when 
store-sequencing is enabled">;
+defm : OptionalBoolField<"sched-mi-aa",
+  "Enable use of AA during MI DAG construction">;
+defm : BoolField<"sched-mi-tbaa", "true",
+  "Enable use of TBAA during MI DAG construction">;
+let Condition = AssertsOnly in
+defm : BoolField<"sched-print-cycles", "false",
+  "Report top/bottom cycles when dumping SUnit instances">;
+defm : BoolField<"scheditins", "true",
+  "Use InstrItineraryData for latency lookup">;
+defm : BoolField<"schedmodel", "true",
+  "Use TargetSchedModel for latency lookup">;
+defm : BoolField<"store-sequencing", "false",
+  "Enable the store-sequencing DAG construction algorithm. This can eliminate 
a large number of redundant control dependencies and spurious alias analysis 
queries at the cost of some unnecessary dependencies">;
+defm : ValueField<"store-sequencing-max-frontier-size", "unsigned", "500",
+  "With store-sequencing DAG construction, after the number of memops in a 
frontier reaches this threshold, automatically promote the next store and clear 
the frontier">;
+defm : ValueField<"store-sequencing-max-memops-in-flight", "unsigned", "3000",
+  "With store-sequencing DAG construction, if the occupancy of all frontiers 
reaches this threshold, automatically promote the next memory operation to a 
global memory barrier and clear the frontiers">;
+// TODO: Remove the old spellings after 2027-05.
+def : AliasOf<"enable-aa-sched-mi", "sched-mi-aa">;
+def : AliasOf<"enable-store-sequencing", "store-sequencing">;
+def : AliasOf<"use-tbaa-in-sched-mi", "sched-mi-tbaa">;
+
 // SelectOptimize.cpp
 defm : ValueField<"cold-operand-max-cost-multiplier", "unsigned", "1",
   "Maximum cost multiplier of TCC_expensive for the dependence slice of a cold 
operand to be considered inexpensive">;
@@ -575,6 +689,19 @@ defm : ValueField<"twoaddr-dataflow-edge-limit", 
"unsigned", "10",
 defm : BoolField<"twoaddr-reschedule", "true",
   "Coalesce copies by rescheduling">;
 
+// VLIWMachineScheduler.cpp
+// Check if the scheduler should penalize instructions that are available to
+// early due to a zero-latency dependence.
+defm : BoolField<"vliw-misched-check-early-avail", "true", "">;
+defm : BoolField<"vliw-misched-ignore-bb-reg-pressure", "false", "">;
+// This value is used to determine if a register class is a high pressure set.
+// We compute the maximum number of registers needed and divided by the total
+// available. Then, we compare the result to this value.
+defm : ValueField<"vliw-misched-reg-pressure", "float", "0.75f",
+  "High register pressure threhold">;
+defm : BoolField<"vliw-misched-use-newer-candidate", "true", "">;
+defm : ValueField<"vliw-misched-verbose-level", "unsigned", "1", "">;
+
 // WinEHPrepare.cpp
 defm : BoolField<"win-eh-prepare-cleanups", "true",
   "Remove implausible terminators and do other similar cleanups">;

diff  --git a/llvm/lib/CodeGen/DFAPacketizer.cpp 
b/llvm/lib/CodeGen/DFAPacketizer.cpp
index edbd380eb827b2..21115bee634398 100644
--- a/llvm/lib/CodeGen/DFAPacketizer.cpp
+++ b/llvm/lib/CodeGen/DFAPacketizer.cpp
@@ -23,6 +23,7 @@
 
//===----------------------------------------------------------------------===//
 
 #include "llvm/CodeGen/DFAPacketizer.h"
+#include "CodeGenOptions.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/CodeGen/MachineFunction.h"
@@ -32,7 +33,6 @@
 #include "llvm/CodeGen/TargetInstrInfo.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/MC/MCInstrDesc.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 #include <algorithm>
@@ -44,9 +44,6 @@ using namespace llvm;
 
 #define DEBUG_TYPE "packets"
 
-static cl::opt<unsigned> InstrLimit("dfa-instr-limit", cl::Hidden,
-  cl::init(0), cl::desc("If present, stops packetizing after N instructions"));
-
 static unsigned InstrCount = 0;
 
 // Check if the resources occupied by a MCInstrDesc are available in the
@@ -169,12 +166,12 @@ void VLIWPacketizerList::PacketizeMIs(MachineBasicBlock 
*MBB,
   for (SUnit &SU : VLIWScheduler->SUnits)
     MIToSUnit[SU.getInstr()] = &SU;
 
-  bool LimitPresent = InstrLimit.getPosition();
+  std::optional<unsigned> InstrLimit = VLIWScheduler->Opts.dfa_instr_limit;
 
   // The main packetizer loop.
   for (; BeginItr != EndItr; ++BeginItr) {
-    if (LimitPresent) {
-      if (InstrCount >= InstrLimit) {
+    if (InstrLimit) {
+      if (InstrCount >= *InstrLimit) {
         EndItr = BeginItr;
         break;
       }

diff  --git a/llvm/lib/CodeGen/MachineScheduler.cpp 
b/llvm/lib/CodeGen/MachineScheduler.cpp
index 4eded9484cccf5..306a56e3fc3674 100644
--- a/llvm/lib/CodeGen/MachineScheduler.cpp
+++ b/llvm/lib/CodeGen/MachineScheduler.cpp
@@ -12,6 +12,7 @@
 
//===----------------------------------------------------------------------===//
 
 #include "llvm/CodeGen/MachineScheduler.h"
+#include "CodeGenOptions.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/DenseMap.h"
@@ -176,34 +177,6 @@ STATISTIC(NumNodeOrderPostRA,
 STATISTIC(NumFirstValidPostRA,
           "Number of scheduling units chosen for FirstValid heuristic 
post-RA");
 
-static cl::opt<MISched::Direction> PreRADirection(
-    "misched-prera-direction", cl::Hidden,
-    cl::desc("Pre reg-alloc list scheduling direction"),
-    cl::init(MISched::Unspecified),
-    cl::values(
-        clEnumValN(MISched::TopDown, "topdown",
-                   "Force top-down pre reg-alloc list scheduling"),
-        clEnumValN(MISched::BottomUp, "bottomup",
-                   "Force bottom-up pre reg-alloc list scheduling"),
-        clEnumValN(MISched::Bidirectional, "bidirectional",
-                   "Force bidirectional pre reg-alloc list scheduling")));
-
-static cl::opt<MISched::Direction> PostRADirection(
-    "misched-postra-direction", cl::Hidden,
-    cl::desc("Post reg-alloc list scheduling direction"),
-    cl::init(MISched::Unspecified),
-    cl::values(
-        clEnumValN(MISched::TopDown, "topdown",
-                   "Force top-down post reg-alloc list scheduling"),
-        clEnumValN(MISched::BottomUp, "bottomup",
-                   "Force bottom-up post reg-alloc list scheduling"),
-        clEnumValN(MISched::Bidirectional, "bidirectional",
-                   "Force bidirectional post reg-alloc list scheduling")));
-
-static cl::opt<bool>
-    DumpCriticalPathLength("misched-dcpl", cl::Hidden,
-                           cl::desc("Print critical path length to stdout"));
-
 static cl::opt<TargetSubtargetInfo::AntiDepBreakMode> PostRABreakAntiDeps(
     "misched-postra-break-antideps", cl::Hidden,
     cl::desc("Set the post-RA MISched anti-dependency break mode"),
@@ -215,97 +188,29 @@ static cl::opt<TargetSubtargetInfo::AntiDepBreakMode> 
PostRABreakAntiDeps(
                clEnumValN(TargetSubtargetInfo::ANTIDEP_ALL, "all",
                           "Break all anti-dependencies")));
 
-static cl::opt<bool> VerifyScheduling(
-    "verify-misched", cl::Hidden,
-    cl::desc("Verify machine instrs before and after machine scheduling"));
-
-MISched::Direction llvm::getPreRADirection() { return PreRADirection; }
+MISched::Direction llvm::getPreRADirection(const MachineFunction &MF) {
+  return getCodeGenOptions(MF).misched_prera_direction;
+}
 TargetSubtargetInfo::AntiDepBreakMode llvm::getPostRABreakAntiDeps() {
   return PostRABreakAntiDeps;
 }
-bool llvm::shouldVerifyScheduling() { return VerifyScheduling; }
-
+bool llvm::shouldVerifyScheduling(const MachineFunction &MF) {
+  return getCodeGenOptions(MF).verify_misched;
+}
+bool llvm::shouldPrintMISchedDAGs(const MachineFunction &MF) {
 #ifndef NDEBUG
-cl::opt<bool> llvm::ViewMISchedDAGs(
-    "view-misched-dags", cl::Hidden,
-    cl::desc("Pop up a window to show MISched dags after they are processed"));
-cl::opt<bool> llvm::PrintDAGs("misched-print-dags", cl::Hidden,
-                              cl::desc("Print schedule DAGs"));
-static cl::opt<bool> MISchedDumpReservedCycles(
-    "misched-dump-reserved-cycles", cl::Hidden, cl::init(false),
-    cl::desc("Dump resource usage at schedule boundary."));
-static cl::opt<bool> MischedDetailResourceBooking(
-    "misched-detail-resource-booking", cl::Hidden, cl::init(false),
-    cl::desc("Show details of invoking getNextResoufceCycle."));
+  return getCodeGenOptions(MF).misched_print_dags;
 #else
-const bool llvm::ViewMISchedDAGs = false;
-const bool llvm::PrintDAGs = false;
-static const bool MischedDetailResourceBooking = false;
-#ifdef LLVM_ENABLE_DUMP
-static const bool MISchedDumpReservedCycles = false;
-#endif // LLVM_ENABLE_DUMP
-#endif // NDEBUG
-
+  return false;
+#endif
+}
+bool llvm::shouldViewMISchedDAGs(const MachineFunction &MF) {
 #ifndef NDEBUG
-/// In some situations a few uninteresting nodes depend on nearly all other
-/// nodes in the graph, provide a cutoff to hide them.
-static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
-  cl::desc("Hide nodes with more predecessor/successor than cutoff"));
-
-static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
-  cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
-
-static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
-  cl::desc("Only schedule this function"));
-static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
-                                        cl::desc("Only schedule this MBB#"));
-#endif // NDEBUG
-
-/// Avoid quadratic complexity in unusually large basic blocks by limiting the
-/// size of the ready lists.
-static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
-  cl::desc("Limit ready list to N instructions"), cl::init(256));
-
-static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
-  cl::desc("Enable register pressure scheduling."), cl::init(true));
-
-static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
-  cl::desc("Enable cyclic critical path analysis."), cl::init(true));
-
-static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
-                                        cl::desc("Enable memop clustering."),
-                                        cl::init(true));
-static cl::opt<bool>
-    ForceFastCluster("force-fast-cluster", cl::Hidden,
-                     cl::desc("Switch to fast cluster algorithm with the lost "
-                              "of some fusion opportunities"),
-                     cl::init(false));
-static cl::opt<unsigned>
-    FastClusterThreshold("fast-cluster-threshold", cl::Hidden,
-                         cl::desc("The threshold for fast cluster"),
-                         cl::init(1000));
-
-#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
-static cl::opt<bool> MISchedDumpScheduleTrace(
-    "misched-dump-schedule-trace", cl::Hidden, cl::init(false),
-    cl::desc("Dump resource usage at schedule boundary."));
-static cl::opt<unsigned>
-    HeaderColWidth("misched-dump-schedule-trace-col-header-width", cl::Hidden,
-                   cl::desc("Set width of the columns with "
-                            "the resources and schedule units"),
-                   cl::init(19));
-static cl::opt<unsigned>
-    ColWidth("misched-dump-schedule-trace-col-width", cl::Hidden,
-             cl::desc("Set width of the columns showing resource booking."),
-             cl::init(5));
-static cl::opt<bool> MISchedSortResourcesInTrace(
-    "misched-sort-resources-in-trace", cl::Hidden, cl::init(true),
-    cl::desc("Sort the resources printed in the dump trace"));
+  return getCodeGenOptions(MF).misched_view_dags;
+#else
+  return false;
 #endif
-
-static cl::opt<unsigned>
-    MIResourceCutOff("misched-resource-cutoff", cl::Hidden,
-                     cl::desc("Number of intervals to track"), cl::init(10));
+}
 
 // DAG subtrees must have at least this many nodes.
 static const unsigned MinSubtreeSize = 8;
@@ -564,21 +469,6 @@ static MachineSchedRegistry
 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
                      useDefaultMachineSched);
 
-static cl::opt<bool> EnableMachineSched(
-    "enable-misched",
-    cl::desc("Enable the machine instruction scheduling pass."), 
cl::init(true),
-    cl::Hidden);
-
-static cl::opt<bool> EnableSSAMachineSched(
-    "enable-ssa-misched",
-    cl::desc("Enable the machine instruction scheduling pass in SSA."),
-    cl::init(false), cl::Hidden);
-
-static cl::opt<bool> EnablePostRAMachineSched(
-    "enable-post-misched",
-    cl::desc("Enable the post-ra machine instruction scheduling pass."),
-    cl::init(true), cl::Hidden);
-
 /// Decrement this iterator until reaching the top or a non-debug instr.
 static MachineBasicBlock::const_iterator
 priorNonDebug(MachineBasicBlock::const_iterator I,
@@ -645,7 +535,8 @@ bool MachineSchedulerImpl::run(MachineFunction &Func, const 
TargetMachine &TM,
   RegClassInfo = &Analyses.RegClassInfo;
   MBFI = &Analyses.MBFI;
 
-  if (VerifyScheduling) {
+  const CodeGenOptions &Opts = getCodeGenOptions(Func);
+  if (Opts.verify_misched) {
     LLVM_DEBUG(LIS->dump());
     const char *MSchedBanner = "Before machine scheduling.";
     if (P)
@@ -660,7 +551,7 @@ bool MachineSchedulerImpl::run(MachineFunction &Func, const 
TargetMachine &TM,
   scheduleRegions(*Scheduler, false);
 
   LLVM_DEBUG(LIS->dump());
-  if (VerifyScheduling) {
+  if (Opts.verify_misched) {
     const char *MSchedBanner = "After machine scheduling.";
     if (P)
       MF->verify(P, MSchedBanner, &errs());
@@ -692,7 +583,8 @@ bool SSAMachineSchedulerImpl::run(MachineFunction &Func,
   RegClassInfo = &Analyses.RegClassInfo;
   MBFI = &Analyses.MBFI;
 
-  if (VerifyScheduling) {
+  const CodeGenOptions &Opts = getCodeGenOptions(Func);
+  if (Opts.verify_misched) {
     LLVM_DEBUG(LIS->dump());
     const char *MSchedBanner = "Before machine scheduling.";
     if (P)
@@ -708,7 +600,7 @@ bool SSAMachineSchedulerImpl::run(MachineFunction &Func,
   scheduleRegions(*Scheduler, false);
 
   LLVM_DEBUG(LIS->dump());
-  if (VerifyScheduling) {
+  if (Opts.verify_misched) {
     const char *MSchedBanner = "After machine scheduling.";
     if (P)
       MF->verify(P, MSchedBanner, &errs());
@@ -740,7 +632,8 @@ bool PostMachineSchedulerImpl::run(MachineFunction &Func,
   AA = &Analyses.AA;
   RegClassInfo = &Analyses.RCI;
 
-  if (VerifyScheduling) {
+  const CodeGenOptions &Opts = getCodeGenOptions(Func);
+  if (Opts.verify_misched) {
     const char *PostMSchedBanner = "Before post machine scheduling.";
     if (P)
       MF->verify(P, PostMSchedBanner, &errs());
@@ -753,7 +646,7 @@ bool PostMachineSchedulerImpl::run(MachineFunction &Func,
   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
   scheduleRegions(*Scheduler, true);
 
-  if (VerifyScheduling) {
+  if (Opts.verify_misched) {
     const char *PostMSchedBanner = "After post machine scheduling.";
     if (P)
       MF->verify(P, PostMSchedBanner, &errs());
@@ -783,12 +676,9 @@ bool 
MachineSchedulerLegacy::runOnMachineFunction(MachineFunction &MF) {
   if (skipFunction(MF.getFunction()))
     return false;
 
-  if (EnableMachineSched.getNumOccurrences()) {
-    if (!EnableMachineSched)
-      return false;
-  } else if (!MF.getSubtarget().enableMachineScheduler()) {
+  if (!valueOr(getCodeGenOptions(MF).enable_misched,
+               MF.getSubtarget().enableMachineScheduler()))
     return false;
-  }
 
   LLVM_DEBUG(dbgs() << "Before MISched:\n"; MF.print(dbgs()));
 
@@ -808,12 +698,9 @@ bool 
SSAMachineSchedulerLegacy::runOnMachineFunction(MachineFunction &MF) {
   if (skipFunction(MF.getFunction()))
     return false;
 
-  if (EnableSSAMachineSched.getNumOccurrences()) {
-    if (!EnableSSAMachineSched)
-      return false;
-  } else if (!MF.getSubtarget().enableSSAMachineScheduler()) {
+  if (!valueOr(getCodeGenOptions(MF).enable_ssa_misched,
+               MF.getSubtarget().enableSSAMachineScheduler()))
     return false;
-  }
 
   auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
   auto &TM = getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
@@ -848,12 +735,9 @@ PostMachineSchedulerPass::~PostMachineSchedulerPass() = 
default;
 PreservedAnalyses
 MachineSchedulerPass::run(MachineFunction &MF,
                           MachineFunctionAnalysisManager &MFAM) {
-  if (EnableMachineSched.getNumOccurrences()) {
-    if (!EnableMachineSched)
-      return PreservedAnalyses::all();
-  } else if (!MF.getSubtarget().enableMachineScheduler()) {
+  if (!valueOr(getCodeGenOptions(MF).enable_misched,
+               MF.getSubtarget().enableMachineScheduler()))
     return PreservedAnalyses::all();
-  }
 
   LLVM_DEBUG(dbgs() << "Before MISched:\n"; MF.print(dbgs()));
   auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF);
@@ -878,8 +762,8 @@ MachineSchedulerPass::run(MachineFunction &MF,
 PreservedAnalyses
 SSAMachineSchedulerPass::run(MachineFunction &MF,
                              MachineFunctionAnalysisManager &MFAM) {
-  if (EnableSSAMachineSched.getNumOccurrences()) {
-    if (!EnableSSAMachineSched)
+  if (auto Enable = toOptional(getCodeGenOptions(MF).enable_ssa_misched)) {
+    if (!*Enable)
       return PreservedAnalyses::all();
   } else if (!MF.getSubtarget().enableSSAMachineScheduler()) {
     LLVM_DEBUG(dbgs() << "Subtarget disables ssa-MI-sched.\n");
@@ -908,8 +792,8 @@ bool 
PostMachineSchedulerLegacy::runOnMachineFunction(MachineFunction &MF) {
   if (skipFunction(MF.getFunction()))
     return false;
 
-  if (EnablePostRAMachineSched.getNumOccurrences()) {
-    if (!EnablePostRAMachineSched)
+  if (auto Enable = toOptional(getCodeGenOptions(MF).enable_post_misched)) {
+    if (!*Enable)
       return false;
   } else if (!MF.getSubtarget().enablePostRAMachineScheduler()) {
     LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
@@ -927,8 +811,8 @@ bool 
PostMachineSchedulerLegacy::runOnMachineFunction(MachineFunction &MF) {
 PreservedAnalyses
 PostMachineSchedulerPass::run(MachineFunction &MF,
                               MachineFunctionAnalysisManager &MFAM) {
-  if (EnablePostRAMachineSched.getNumOccurrences()) {
-    if (!EnablePostRAMachineSched)
+  if (auto Enable = toOptional(getCodeGenOptions(MF).enable_post_misched)) {
+    if (!*Enable)
       return PreservedAnalyses::all();
   } else if (!MF.getSubtarget().enablePostRAMachineScheduler()) {
     LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
@@ -1015,6 +899,8 @@ getSchedRegions(MachineBasicBlock *MBB,
 /// Main driver for both MachineScheduler and PostMachineScheduler.
 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
                                            bool FixKillFlags) {
+  const CodeGenOptions &Opts = Scheduler.Opts;
+
   // Visit all machine basic blocks.
   //
   // TODO: Visit blocks in global postorder or postorder within the bottom-up
@@ -1022,10 +908,10 @@ void 
MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
        MBB != MBBEnd; ++MBB) {
 #ifndef NDEBUG
-    if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
+    if (Opts.misched_only_func && *Opts.misched_only_func != MF->getName())
       continue;
-    if (SchedOnlyBlock.getNumOccurrences()
-        && (int)SchedOnlyBlock != MBB->getNumber())
+    if (Opts.misched_only_block &&
+        (int)*Opts.misched_only_block != MBB->getNumber())
       continue;
 #endif
 
@@ -1075,11 +961,11 @@ void 
MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
           dbgs() << "End\n";
         dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n';
       };
-      if (PrintDAGs)
+      if (shouldPrintMISchedDAGs(*MF))
         DumpRegionHeader();
       else
         LLVM_DEBUG(DumpRegionHeader());
-      if (DumpCriticalPathLength) {
+      if (Opts.misched_dcpl) {
         errs() << MF->getName();
         errs() << ":%bb. " << MBB->getNumber();
         errs() << " " << MBB->getName() << " \n";
@@ -1338,7 +1224,7 @@ void ScheduleDAGMI::moveInstruction(
 
 bool ScheduleDAGMI::checkSchedLimit() {
 #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
-  if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
+  if (NumInstrsScheduled == Opts.misched_cutoff && Opts.misched_cutoff != ~0U) 
{
     CurrentTop = CurrentBottom;
     return false;
   }
@@ -1372,8 +1258,10 @@ void ScheduleDAGMI::schedule() {
   findRootsAndBiasEdges(TopRoots, BotRoots);
 
   LLVM_DEBUG(dump());
-  if (PrintDAGs) dump();
-  if (ViewMISchedDAGs) viewGraph();
+  if (shouldPrintMISchedDAGs(MF))
+    dump();
+  if (shouldViewMISchedDAGs(MF))
+    viewGraph();
 
   // Initialize the strategy before modifying the DAG.
   // This may initialize a DFSResult to be used for queue priority.
@@ -1517,10 +1405,12 @@ void ScheduleDAGMI::placeDebugValues() {
   }
 }
 
-#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
+#ifndef NDEBUG
 static const char *scheduleTableLegend = "  i: issue\n  x: resource booked";
 
 LLVM_DUMP_METHOD void ScheduleDAGMI::dumpScheduleTraceTopDown() const {
+  unsigned HeaderColWidth = Opts.misched_dump_schedule_trace_col_header_width;
+  unsigned ColWidth = Opts.misched_dump_schedule_trace_col_width;
   // Bail off when there is no schedule model to query.
   if (!SchedModel.hasInstrSchedModel())
     return;
@@ -1574,7 +1464,7 @@ LLVM_DUMP_METHOD void 
ScheduleDAGMI::dumpScheduleTraceTopDown() const {
         make_range(SchedModel.getWriteProcResBegin(SC),
                    SchedModel.getWriteProcResEnd(SC)));
 
-    if (MISchedSortResourcesInTrace)
+    if (Opts.misched_sort_resources_in_trace)
       llvm::stable_sort(
           ResourcesIt,
           [](const MCWriteProcResEntry &LHS,
@@ -1602,6 +1492,8 @@ LLVM_DUMP_METHOD void 
ScheduleDAGMI::dumpScheduleTraceTopDown() const {
 }
 
 LLVM_DUMP_METHOD void ScheduleDAGMI::dumpScheduleTraceBottomUp() const {
+  unsigned HeaderColWidth = Opts.misched_dump_schedule_trace_col_header_width;
+  unsigned ColWidth = Opts.misched_dump_schedule_trace_col_width;
   // Bail off when there is no schedule model to query.
   if (!SchedModel.hasInstrSchedModel())
     return;
@@ -1655,7 +1547,7 @@ LLVM_DUMP_METHOD void 
ScheduleDAGMI::dumpScheduleTraceBottomUp() const {
         make_range(SchedModel.getWriteProcResBegin(SC),
                    SchedModel.getWriteProcResEnd(SC)));
 
-    if (MISchedSortResourcesInTrace)
+    if (Opts.misched_sort_resources_in_trace)
       llvm::stable_sort(
           ResourcesIt,
           [](const MCWriteProcResEntry &LHS,
@@ -1685,7 +1577,8 @@ LLVM_DUMP_METHOD void 
ScheduleDAGMI::dumpScheduleTraceBottomUp() const {
 
 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
 LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
-  if (MISchedDumpScheduleTrace) {
+#ifndef NDEBUG
+  if (Opts.misched_dump_schedule_trace) {
     if (DumpDir == DumpDirection::TopDown)
       dumpScheduleTraceTopDown();
     else if (DumpDir == DumpDirection::BottomUp)
@@ -1696,6 +1589,7 @@ LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const 
{
       dbgs() << "* Schedule table: DumpDirection not set.\n";
     }
   }
+#endif
 
   for (MachineInstr &MI : *this) {
     if (SUnit *SU = getSUnit(&MI))
@@ -2008,8 +1902,10 @@ void ScheduleDAGMILive::schedule() {
   SchedImpl->initialize(this);
 
   LLVM_DEBUG(dump());
-  if (PrintDAGs) dump();
-  if (ViewMISchedDAGs) viewGraph();
+  if (shouldPrintMISchedDAGs(MF))
+    dump();
+  if (shouldViewMISchedDAGs(MF))
+    viewGraph();
 
   // Initialize ready queues now that the DAG and priority data are finalized.
   initQueues(TopRoots, BotRoots);
@@ -2370,17 +2266,13 @@ class LoadClusterMutation : public 
BaseMemOpClusterMutation {
 std::unique_ptr<ScheduleDAGMutation>
 llvm::createLoadClusterDAGMutation(const TargetInstrInfo *TII,
                                    bool ReorderWhileClustering) {
-  return EnableMemOpCluster ? std::make_unique<LoadClusterMutation>(
-                                  TII, ReorderWhileClustering)
-                            : nullptr;
+  return std::make_unique<LoadClusterMutation>(TII, ReorderWhileClustering);
 }
 
 std::unique_ptr<ScheduleDAGMutation>
 llvm::createStoreClusterDAGMutation(const TargetInstrInfo *TII,
                                     bool ReorderWhileClustering) {
-  return EnableMemOpCluster ? std::make_unique<StoreClusterMutation>(
-                                  TII, ReorderWhileClustering)
-                            : nullptr;
+  return std::make_unique<StoreClusterMutation>(TII, ReorderWhileClustering);
 }
 
 // Sorting all the loads/stores first, then for each load/store, checking the
@@ -2530,9 +2422,9 @@ void BaseMemOpClusterMutation::collectMemOpRecords(
 bool BaseMemOpClusterMutation::groupMemOps(
     ArrayRef<MemOpInfo> MemOps, ScheduleDAGInstrs *DAG,
     DenseMap<unsigned, SmallVector<MemOpInfo, 32>> &Groups) {
-  bool FastCluster =
-      ForceFastCluster ||
-      MemOps.size() * DAG->SUnits.size() / 1000 > FastClusterThreshold;
+  bool FastCluster = DAG->Opts.misched_force_fast_cluster ||
+                     MemOps.size() * DAG->SUnits.size() / 1000 >
+                         DAG->Opts.misched_fast_cluster_threshold;
 
   for (const auto &MemOp : MemOps) {
     unsigned ChainPredID = DAG->SUnits.size();
@@ -2559,6 +2451,9 @@ bool BaseMemOpClusterMutation::groupMemOps(
 
 /// Callback from DAG postProcessing to create cluster edges for loads/stores.
 void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAG) {
+  if (!DAG->Opts.misched_cluster)
+    return;
+
   // Collect all the clusterable loads/stores
   SmallVector<MemOpInfo, 32> MemOpRecords;
   collectMemOpRecords(DAG->SUnits, MemOpRecords);
@@ -2930,11 +2825,11 @@ std::pair<unsigned, unsigned>
 SchedBoundary::getNextResourceCycle(const MCSchedClassDesc *SC, unsigned PIdx,
                                     unsigned ReleaseAtCycle,
                                     unsigned AcquireAtCycle) {
-  if (MischedDetailResourceBooking) {
-    LLVM_DEBUG(dbgs() << "  Resource booking (@" << CurrCycle << "c): \n");
-    LLVM_DEBUG(dumpReservedCycles());
-    LLVM_DEBUG(dbgs() << "  getNextResourceCycle (@" << CurrCycle << "c): \n");
-  }
+  LLVM_DEBUG(if (DAG->Opts.misched_detail_resource_booking) {
+    dbgs() << "  Resource booking (@" << CurrCycle << "c): \n";
+    dumpReservedCycles();
+    dbgs() << "  getNextResourceCycle (@" << CurrCycle << "c): \n";
+  });
   unsigned MinNextUnreserved = InvalidCycle;
   unsigned InstanceIdx = 0;
   unsigned StartIndex = ReservedCyclesIndex[PIdx];
@@ -2979,19 +2874,23 @@ SchedBoundary::getNextResourceCycle(const 
MCSchedClassDesc *SC, unsigned PIdx,
        ++I) {
     unsigned NextUnreserved =
         getNextResourceCycleByInstance(I, ReleaseAtCycle, AcquireAtCycle);
-    if (MischedDetailResourceBooking)
-      LLVM_DEBUG(dbgs() << "    Instance " << I - StartIndex << " available @"
-                        << NextUnreserved << "c\n");
+    LLVM_DEBUG({
+      if (DAG->Opts.misched_detail_resource_booking)
+        dbgs() << "    Instance " << I - StartIndex << " available @"
+               << NextUnreserved << "c\n";
+    });
     if (MinNextUnreserved > NextUnreserved) {
       InstanceIdx = I;
       MinNextUnreserved = NextUnreserved;
     }
   }
-  if (MischedDetailResourceBooking)
-    LLVM_DEBUG(dbgs() << "    selecting " << SchedModel->getResourceName(PIdx)
-                      << "[" << InstanceIdx - StartIndex << "]"
-                      << " available @" << MinNextUnreserved << "c"
-                      << "\n");
+  LLVM_DEBUG({
+    if (DAG->Opts.misched_detail_resource_booking)
+      dbgs() << "    selecting " << SchedModel->getResourceName(PIdx) << "["
+             << InstanceIdx - StartIndex << "]"
+             << " available @" << MinNextUnreserved << "c"
+             << "\n";
+  });
   return std::make_pair(MinNextUnreserved, InstanceIdx);
 }
 
@@ -3137,7 +3036,7 @@ void SchedBoundary::releaseNode(SUnit *SU, unsigned 
ReadyCycle, bool InPQueue,
   else
     HazardDetected = checkHazard(SU);
 
-  if (!HazardDetected && Available.size() >= ReadyListLimit) {
+  if (!HazardDetected && Available.size() >= DAG->Opts.misched_limit) {
     HazardDetected = true;
     LLVM_DEBUG(dbgs().indent(2) << "hazard: Available Q is full (size: "
                                 << Available.size() << ")\n");
@@ -3330,12 +3229,12 @@ void SchedBoundary::bumpNode(SUnit *SU) {
               ReservedResourceSegments[InstanceIdx].add(
                   ResourceSegments::getResourceIntervalTop(
                       NextCycle, PI->AcquireAtCycle, PI->ReleaseAtCycle),
-                  MIResourceCutOff);
+                  DAG->Opts.misched_resource_cutoff);
             } else {
               ReservedResourceSegments[InstanceIdx].add(
                   ResourceSegments::getResourceIntervalBottom(
                       NextCycle, PI->AcquireAtCycle, PI->ReleaseAtCycle),
-                  MIResourceCutOff);
+                  DAG->Opts.misched_resource_cutoff);
             }
           } else {
 
@@ -3430,7 +3329,7 @@ void SchedBoundary::releasePending() {
     if (ReadyCycle < MinReadyCycle)
       MinReadyCycle = ReadyCycle;
 
-    if (Available.size() >= ReadyListLimit)
+    if (Available.size() >= DAG->Opts.misched_limit)
       break;
 
     releaseNode(SU, ReadyCycle, true, I);
@@ -3536,8 +3435,10 @@ LLVM_DUMP_METHOD void 
SchedBoundary::dumpScheduledState() const {
          << "\n  ExpectedLatency: " << ExpectedLatency << "c\n"
          << (IsResourceLimited ? "  - Resource" : "  - Latency")
          << " limited.\n";
-  if (MISchedDumpReservedCycles)
+#ifndef NDEBUG
+  if (DAG->Opts.misched_dump_reserved_cycles)
     dumpReservedCycles();
+#endif
 }
 #endif
 
@@ -4008,7 +3909,9 @@ void 
GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
   MF.getSubtarget().overrideSchedPolicy(RegionPolicy, Region);
 
   // After subtarget overrides, apply command line options.
-  if (!EnableRegPressure) {
+  const CodeGenOptions &Opts = getCodeGenOptions(MF);
+  MISched::Direction PreRADirection = Opts.misched_prera_direction;
+  if (!Opts.misched_regpressure) {
     RegionPolicy.ShouldTrackPressure = false;
     RegionPolicy.ShouldTrackLaneMasks = false;
   }
@@ -4085,11 +3988,11 @@ void GenericScheduler::registerRoots() {
       Rem.CriticalPath = SU->getDepth();
   }
   LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
-  if (DumpCriticalPathLength) {
+  if (DAG->Opts.misched_dcpl) {
     errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
   }
 
-  if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
+  if (DAG->Opts.misched_cyclicpath && SchedModel->getMicroOpBufferSize() > 0) {
     Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
     checkAcyclicLatency();
   }
@@ -4221,7 +4124,7 @@ void GenericScheduler::initCandidate(SchedCandidate 
&Cand, SUnit *SU,
         DAG->getRegionCriticalPSets(),
         DAG->getRegPressure().MaxSetPressure);
     } else {
-      if (VerifyScheduling) {
+      if (DAG->Opts.verify_misched) {
         TempTracker.getMaxUpwardPressureDelta(
           Cand.SU->getInstr(),
           &DAG->getPressureDiff(Cand.SU),
@@ -4424,7 +4327,7 @@ SUnit *GenericScheduler::pickNodeBidirectional(bool 
&IsTopNode) {
   } else {
     LLVM_DEBUG(traceCandidate(BotCand));
 #ifndef NDEBUG
-    if (VerifyScheduling) {
+    if (DAG->Opts.verify_misched) {
       SchedCandidate TCand;
       TCand.reset(CandPolicy());
       pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
@@ -4444,7 +4347,7 @@ SUnit *GenericScheduler::pickNodeBidirectional(bool 
&IsTopNode) {
   } else {
     LLVM_DEBUG(traceCandidate(TopCand));
 #ifndef NDEBUG
-    if (VerifyScheduling) {
+    if (DAG->Opts.verify_misched) {
       SchedCandidate TCand;
       TCand.reset(CandPolicy());
       pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
@@ -4700,6 +4603,8 @@ void 
PostGenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
   MF.getSubtarget().overridePostRASchedPolicy(RegionPolicy, Region);
 
   // After subtarget overrides, apply command line options.
+  MISched::Direction PostRADirection =
+      getCodeGenOptions(MF).misched_postra_direction;
   if (PostRADirection == MISched::TopDown) {
     RegionPolicy.OnlyTopDown = true;
     RegionPolicy.OnlyBottomUp = false;
@@ -4724,7 +4629,7 @@ void PostGenericScheduler::registerRoots() {
       Rem.CriticalPath = SU->getDepth();
   }
   LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
-  if (DumpCriticalPathLength) {
+  if (DAG->Opts.misched_dcpl) {
     errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
   }
 }
@@ -4836,7 +4741,7 @@ SUnit *PostGenericScheduler::pickNodeBidirectional(bool 
&IsTopNode) {
   } else {
     LLVM_DEBUG(traceCandidate(BotCand));
 #ifndef NDEBUG
-    if (VerifyScheduling) {
+    if (DAG->Opts.verify_misched) {
       SchedCandidate TCand;
       TCand.reset(CandPolicy());
       pickNodeFromQueue(Bot, BotCand);
@@ -4856,7 +4761,7 @@ SUnit *PostGenericScheduler::pickNodeBidirectional(bool 
&IsTopNode) {
   } else {
     LLVM_DEBUG(traceCandidate(TopCand));
 #ifndef NDEBUG
-    if (VerifyScheduling) {
+    if (DAG->Opts.verify_misched) {
       SchedCandidate TCand;
       TCand.reset(CandPolicy());
       pickNodeFromQueue(Top, TopCand);
@@ -5159,6 +5064,8 @@ class InstructionShuffler : public MachineSchedStrategy {
 } // end anonymous namespace
 
 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
+  MISched::Direction PreRADirection =
+      getCodeGenOptions(*C->MF).misched_prera_direction;
   bool Alternate =
       PreRADirection != MISched::TopDown && PreRADirection != 
MISched::BottomUp;
   bool TopDown = PreRADirection != MISched::BottomUp;
@@ -5194,10 +5101,10 @@ struct llvm::DOTGraphTraits<ScheduleDAGMI *> : public 
DefaultDOTGraphTraits {
   }
 
   static bool isNodeHidden(const SUnit *Node, const ScheduleDAG *G) {
-    if (ViewMISchedCutoff == 0)
+    unsigned Cutoff = getCodeGenOptions(G->MF).misched_view_cutoff;
+    if (Cutoff == 0)
       return false;
-    return (Node->Preds.size() > ViewMISchedCutoff
-         || Node->Succs.size() > ViewMISchedCutoff);
+    return Node->Preds.size() > Cutoff || Node->Succs.size() > Cutoff;
   }
 
   /// If you want to override the dot attributes printed for a particular

diff  --git a/llvm/lib/CodeGen/MacroFusion.cpp 
b/llvm/lib/CodeGen/MacroFusion.cpp
index 3b1c15175acecd..dd3f04bf65b69a 100644
--- a/llvm/lib/CodeGen/MacroFusion.cpp
+++ b/llvm/lib/CodeGen/MacroFusion.cpp
@@ -12,13 +12,13 @@
 
//===----------------------------------------------------------------------===//
 
 #include "llvm/CodeGen/MacroFusion.h"
+#include "CodeGenOptions.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/CodeGen/MachineInstr.h"
 #include "llvm/CodeGen/ScheduleDAG.h"
 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
 #include "llvm/CodeGen/ScheduleDAGMutation.h"
 #include "llvm/CodeGen/TargetInstrInfo.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -31,9 +31,6 @@ STATISTIC(NumFusionConflicts,
 
 using namespace llvm;
 
-static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
-  cl::desc("Enable scheduling for macro fusion."), cl::init(true));
-
 static bool isHazard(const SDep &Dep) {
   return Dep.getKind() == SDep::Anti || Dep.getKind() == SDep::Output;
 }
@@ -189,6 +186,9 @@ bool MacroFusion::shouldScheduleAdjacent(const 
TargetInstrInfo &TII,
 }
 
 void MacroFusion::apply(ScheduleDAGInstrs *DAG) {
+  if (!DAG->Opts.misched_fusion)
+    return;
+
   if (FuseBlock)
     // For each of the SUnits in the scheduling block, try to fuse the instr in
     // it with one in its predecessors.
@@ -233,7 +233,5 @@ bool MacroFusion::scheduleAdjacentImpl(ScheduleDAGInstrs 
&DAG, SUnit &AnchorSU)
 std::unique_ptr<ScheduleDAGMutation>
 llvm::createMacroFusionDAGMutation(ArrayRef<MacroFusionPredTy> Predicates,
                                    bool BranchOnly) {
-  if (EnableMacroFusion)
-    return std::make_unique<MacroFusion>(Predicates, !BranchOnly);
-  return nullptr;
+  return std::make_unique<MacroFusion>(Predicates, !BranchOnly);
 }

diff  --git a/llvm/lib/CodeGen/ScheduleDAG.cpp 
b/llvm/lib/CodeGen/ScheduleDAG.cpp
index 4348153356d2ce..db752d193a246b 100644
--- a/llvm/lib/CodeGen/ScheduleDAG.cpp
+++ b/llvm/lib/CodeGen/ScheduleDAG.cpp
@@ -12,6 +12,7 @@
 
//===----------------------------------------------------------------------===//
 
 #include "llvm/CodeGen/ScheduleDAG.h"
+#include "CodeGenOptions.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
@@ -22,7 +23,6 @@
 #include "llvm/CodeGen/TargetRegisterInfo.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/Config/llvm-config.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -41,12 +41,6 @@ STATISTIC(NumNewPredsAdded, "Number of times a  single 
predecessor was added");
 STATISTIC(NumTopoInits,
           "Number of times the topological order has been recomputed");
 
-#ifndef NDEBUG
-static cl::opt<bool> StressSchedOpt(
-  "stress-sched", cl::Hidden, cl::init(false),
-  cl::desc("Stress test instruction scheduling"));
-#endif
-
 void SchedulingPriorityQueue::anchor() {}
 
 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
@@ -54,7 +48,7 @@ ScheduleDAG::ScheduleDAG(MachineFunction &mf)
       TRI(mf.getSubtarget().getRegisterInfo()), MF(mf),
       MRI(mf.getRegInfo()) {
 #ifndef NDEBUG
-  StressSched = StressSchedOpt;
+  StressSched = getCodeGenOptions(mf).stress_sched;
 #endif
 }
 

diff  --git a/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp 
b/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp
index b80f630931fa4a..420152f1a09ab8 100644
--- a/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp
+++ b/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp
@@ -12,6 +12,7 @@
 
//===----------------------------------------------------------------------===//
 
 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
+#include "CodeGenOptions.h"
 
 #include "llvm/ADT/IntEqClasses.h"
 #include "llvm/ADT/MapVector.h"
@@ -44,7 +45,6 @@
 #include "llvm/IR/Value.h"
 #include "llvm/MC/LaneBitmask.h"
 #include "llvm/MC/MCRegisterInfo.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -61,70 +61,16 @@ using namespace llvm;
 
 #define DEBUG_TYPE "machine-scheduler"
 
-static cl::opt<bool>
-    EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
-                    cl::desc("Enable use of AA during MI DAG construction"));
-
-static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
-    cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
-
-static cl::opt<bool>
-    EnableSchedModel("schedmodel", cl::Hidden, cl::init(true),
-                     cl::desc("Use TargetSchedModel for latency lookup"));
-
-static cl::opt<bool>
-    EnableSchedItins("scheditins", cl::Hidden, cl::init(true),
-                     cl::desc("Use InstrItineraryData for latency lookup"));
-
-// Note: the following options might be used in tuning compile time vs output
-// quality. Setting HugeRegion so large that it will never be reached means
-// best-effort, but may be slow.
-
-// FIXME(@cofibrant): Drop in favour of store-sequencing.
-// When the number of processed memops reaches this threshold, a reduction of
-// maps will be done.
-static cl::opt<unsigned>
-    HugeRegion("dag-maps-huge-region", cl::Hidden, cl::init(500),
-               cl::desc("The limit to use while constructing the DAG "
-                        "prior to scheduling, at which point a trade-off "
-                        "is made to avoid excessive compile time. Ignored when 
"
-                        "store-sequencing is enabled."));
-
-static cl::opt<bool> EnableStoreSequencing(
-    "enable-store-sequencing", cl::Hidden, cl::init(false),
-    cl::desc("Enable the store-sequencing DAG construction algorithm. This can 
"
-             "eliminate a large number of redundant control dependencies and "
-             "spurious alias analysis queries at the cost of some unnecessary "
-             "dependencies."));
-
-static cl::opt<unsigned> MaxFrontierSize(
-    "store-sequencing-max-frontier-size", cl::Hidden, cl::init(500),
-    cl::desc("With store-sequencing DAG construction, after the number of "
-             "memops in a frontier reaches this threshold, automatically "
-             "promote the next store and clear the frontier."));
-
-static cl::opt<unsigned> MaxMemopsInFlight(
-    "store-sequencing-max-memops-in-flight", cl::Hidden, cl::init(3000),
-    cl::desc("With store-sequencing DAG construction, if the occupancy of all "
-             "frontiers reaches this threshold, automatically promote the next 
"
-             "memory operation to a global memory barrier and clear the "
-             "frontiers."));
-
-#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
-static cl::opt<bool> SchedPrintCycles(
-    "sched-print-cycles", cl::Hidden, cl::init(false),
-    cl::desc("Report top/bottom cycles when dumping SUnit instances"));
-#endif
-
 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
                                      const MachineLoopInfo *mli,
                                      bool RemoveKillFlags)
-    : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
-      RemoveKillFlags(RemoveKillFlags), Topo(SUnits, &ExitSU) {
+    : ScheduleDAG(mf), Opts(getCodeGenOptions(mf)), MLI(mli),
+      MFI(mf.getFrameInfo()), RemoveKillFlags(RemoveKillFlags),
+      Topo(SUnits, &ExitSU) {
   DbgValues.clear();
 
   const TargetSubtargetInfo &ST = mf.getSubtarget();
-  SchedModel.init(&ST, EnableSchedModel, EnableSchedItins);
+  SchedModel.init(&ST, Opts.schedmodel, Opts.scheditins);
 }
 
 /// If this machine instruction has memory reference information, collect the
@@ -629,6 +575,7 @@ using SUList = std::list<SUnit *>;
 namespace llvm {
 class ScheduleDAGDependencyBuilder {
 private:
+  const CodeGenOptions &Opts;
   ScheduleDAGInstrs &DAG;
 
   BatchAAResults *AA;
@@ -667,10 +614,6 @@ class ScheduleDAGDependencyBuilder {
     /// The memory operations in the frontier.
     SUList Stores, Loads;
 
-    /// Returns true if the next store should be promoted to a sequencing store
-    /// and false otherwise.
-    bool shouldUpdate() const;
-
     /// The number of memops in the frontier, excluding the sequencing store.
     unsigned size() const;
 
@@ -715,11 +658,6 @@ class ScheduleDAGDependencyBuilder {
     /// #BaseObjects.
     bool SeenSequencingLoad = false;
 
-    /// Given a store instruction with underlying objects \p Objs, returns true
-    /// if the store should be promoted to a sequencing store and false
-    /// otherwise.
-    bool shouldUpdate(const UnderlyingObjectsVector &Objs) const;
-
     /// Returns true if any of \p Objs does not belong to #BaseObjects.
     bool escapesBaseObjects(const UnderlyingObjectsVector &Objs) const;
 
@@ -748,7 +686,8 @@ class ScheduleDAGDependencyBuilder {
   ScheduleDAGDependencyBuilder(ScheduleDAGInstrs &DAG, BatchAAResults *AA,
                                RegPressureTracker *RPTracker,
                                PressureDiffs *PDiffs, LiveIntervals *LIS)
-      : DAG(DAG), AA(AA), RPTracker(RPTracker), PDiffs(PDiffs), LIS(LIS) {}
+      : Opts(DAG.Opts), DAG(DAG), AA(AA), RPTracker(RPTracker), PDiffs(PDiffs),
+        LIS(LIS) {}
 
 private:
   /// Adds a chain edge between SUa and SUb, but only if both
@@ -768,6 +707,16 @@ class ScheduleDAGDependencyBuilder {
   /// and clear the memop frontiers.
   void addBarrierMemoryDeps();
 
+  /// Returns true if the next store should be promoted to a sequencing store
+  /// in the frontier \p F and false otherwise.
+  bool shouldUpdate(const MemopFrontier &F) const;
+
+  /// Given a store instruction with underlying objects \p Objs, returns true
+  /// if the store should be promoted to a sequencing store in the frontier
+  /// \p UF and false otherwise.
+  bool shouldUpdate(const UnanalyzableMemopFrontier &UF,
+                    const UnderlyingObjectsVector &Objs) const;
+
   /// Promote the store \p SU to be a new sequencing store in the frontier \p 
F.
   /// If \p PreserveNoAliasLoads is true, loads in the frontier that do not
   /// alias with \p SU will be retained after promotion.
@@ -794,18 +743,19 @@ void ScheduleDAGDependencyBuilder::MemopFrontier::clear() 
{
   Loads.clear();
 }
 
-bool ScheduleDAGDependencyBuilder::MemopFrontier::shouldUpdate() const {
-  if (!EnableStoreSequencing)
+bool ScheduleDAGDependencyBuilder::shouldUpdate(const MemopFrontier &F) const {
+  if (!Opts.store_sequencing)
     return false;
-  return size() >= MaxFrontierSize;
+  return F.size() >= Opts.store_sequencing_max_frontier_size;
 }
 
-bool ScheduleDAGDependencyBuilder::UnanalyzableMemopFrontier::shouldUpdate(
+bool ScheduleDAGDependencyBuilder::shouldUpdate(
+    const UnanalyzableMemopFrontier &UF,
     const UnderlyingObjectsVector &Objs) const {
-  if (!EnableStoreSequencing)
+  if (!Opts.store_sequencing)
     return false;
-  return Frontier.shouldUpdate() || !Frontier.SequencingStore ||
-         SeenSequencingLoad || escapesBaseObjects(Objs);
+  return shouldUpdate(UF.Frontier) || !UF.Frontier.SequencingStore ||
+         UF.SeenSequencingLoad || UF.escapesBaseObjects(Objs);
 }
 
 bool ScheduleDAGDependencyBuilder::UnanalyzableMemopFrontier::
@@ -826,7 +776,7 @@ void 
ScheduleDAGDependencyBuilder::UnanalyzableMemopFrontier::clear() {
 
 bool ScheduleDAGDependencyBuilder::addChainDependency(SUnit *SUa, SUnit *SUb,
                                                       unsigned Latency) {
-  if (!SUa->getInstr()->mayAlias(AA, *SUb->getInstr(), UseTBAA))
+  if (!SUa->getInstr()->mayAlias(AA, *SUb->getInstr(), Opts.sched_mi_tbaa))
     return false;
 
   SDep Dep(SUa, SDep::MayAliasMem);
@@ -941,7 +891,7 @@ void ScheduleDAGDependencyBuilder::updateSequencingStore(
          "Only store instructions should be used as sequencing stores");
   // If the underlying MemopFrontier wants updating, we're over size and
   // therefore shouldn't try to preserve no alias loads.
-  bool ShouldPreserveNoAliasLoads = !UF.Frontier.shouldUpdate();
+  bool ShouldPreserveNoAliasLoads = !shouldUpdate(UF.Frontier);
   updateSequencingStore(UF.Frontier, SU,
                         /*PreserveNoAliasLoads=*/ShouldPreserveNoAliasLoads);
   UF.BaseObjects = std::move(Objs);
@@ -1079,7 +1029,8 @@ void ScheduleDAGDependencyBuilder::buildDeps() {
       if (BarrierChain)
         BarrierChain->addPredBarrier(SU);
 
-      if (!EnableStoreSequencing && FPExceptions.size() + 1 >= HugeRegion) {
+      if (!Opts.store_sequencing &&
+          FPExceptions.size() + 1 >= Opts.dag_maps_huge_region) {
         LLVM_DEBUG(
             dbgs()
             << "Creating barrier chain and clearing FPExceptions map.\n");
@@ -1102,7 +1053,8 @@ void ScheduleDAGDependencyBuilder::buildDeps() {
       BarrierChain->addPredBarrier(SU);
 
     // Reduce maps if they grow huge.
-    if (!EnableStoreSequencing && MemOpsProcessed >= HugeRegion) {
+    if (!Opts.store_sequencing &&
+        MemOpsProcessed >= Opts.dag_maps_huge_region) {
       LLVM_DEBUG(dbgs() << "Creating barrier chain and clearing maps.\n");
 
       BarrierChain = SU;
@@ -1114,9 +1066,11 @@ void ScheduleDAGDependencyBuilder::buildDeps() {
 
     // If the frontier occupancy exceeds the maximum threshold, promote SU to a
     // global memory barrier and clear the frontiers.
-    if (EnableStoreSequencing && MemopsInFlight >= MaxMemopsInFlight) {
+    if (Opts.store_sequencing &&
+        MemopsInFlight >= Opts.store_sequencing_max_memops_in_flight) {
       LLVM_DEBUG(dbgs() << "Number of in-flight memory operations reached "
-                        << MaxMemopsInFlight << ", promoting " << *SU
+                        << Opts.store_sequencing_max_memops_in_flight
+                        << ", promoting " << *SU
                         << " to barrier chain and clearing maps.\n");
 
       BarrierChain = SU;
@@ -1137,7 +1091,7 @@ void ScheduleDAGDependencyBuilder::buildDeps() {
       for (auto &[_, AF] : AnalyzableFrontiers)
         addChainDependencies(SU, AF, IsStore);
 
-      if (IsStore && UnanalyzableFrontier.shouldUpdate(Objs)) {
+      if (IsStore && shouldUpdate(UnanalyzableFrontier, Objs)) {
         updateSequencingStore(UnanalyzableFrontier, SU, std::move(Objs));
       } else {
         if (!IsStore && UnanalyzableFrontier.escapesBaseObjects(Objs))
@@ -1159,7 +1113,7 @@ void ScheduleDAGDependencyBuilder::buildDeps() {
 
         MemopFrontier &Frontier = AnalyzableFrontiers[V];
 
-        if (IsStore && Frontier.shouldUpdate()) {
+        if (IsStore && shouldUpdate(Frontier)) {
           updateSequencingStore(Frontier, SU);
         } else {
           addChainDependencies(SU, Frontier, IsStore);
@@ -1183,8 +1137,7 @@ void ScheduleDAGInstrs::buildSchedGraph(AAResults *AA,
                                         LiveIntervals *LIS,
                                         bool TrackLaneMasks) {
   const TargetSubtargetInfo &ST = MF.getSubtarget();
-  bool UseAA =
-      EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI : ST.useAA();
+  bool UseAA = valueOr(Opts.sched_mi_aa, ST.useAA());
   this->TrackLaneMasks = TrackLaneMasks;
   MISUnitMap.clear();
   ScheduleDAG::clearDAG();
@@ -1306,9 +1259,11 @@ void ScheduleDAGInstrs::fixupKills(MachineBasicBlock 
&MBB) {
 void ScheduleDAGInstrs::dumpNode(const SUnit &SU) const {
 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
   dumpNodeName(SU);
-  if (SchedPrintCycles)
+#ifndef NDEBUG
+  if (Opts.sched_print_cycles)
     dbgs() << " [TopReadyCycle = " << SU.TopReadyCycle
            << ", BottomReadyCycle = " << SU.BotReadyCycle << "]";
+#endif
   dbgs() << ": ";
   SU.getInstr()->dump();
 #endif

diff  --git a/llvm/lib/CodeGen/VLIWMachineScheduler.cpp 
b/llvm/lib/CodeGen/VLIWMachineScheduler.cpp
index a9273e5d9eb59a..c4bd8575b366c8 100644
--- a/llvm/lib/CodeGen/VLIWMachineScheduler.cpp
+++ b/llvm/lib/CodeGen/VLIWMachineScheduler.cpp
@@ -12,6 +12,7 @@
 
//===----------------------------------------------------------------------===//
 
 #include "llvm/CodeGen/VLIWMachineScheduler.h"
+#include "CodeGenOptions.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/CodeGen/DFAPacketizer.h"
 #include "llvm/CodeGen/MachineBasicBlock.h"
@@ -27,7 +28,6 @@
 #include "llvm/CodeGen/TargetRegisterInfo.h"
 #include "llvm/CodeGen/TargetSchedule.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/raw_ostream.h"
@@ -41,27 +41,6 @@ using namespace llvm;
 
 #define DEBUG_TYPE "machine-scheduler"
 
-static cl::opt<bool> IgnoreBBRegPressure("ignore-bb-reg-pressure", cl::Hidden,
-                                         cl::init(false));
-
-static cl::opt<bool> UseNewerCandidate("use-newer-candidate", cl::Hidden,
-                                       cl::init(true));
-
-static cl::opt<unsigned> SchedDebugVerboseLevel("misched-verbose-level",
-                                                cl::Hidden, cl::init(1));
-
-// Check if the scheduler should penalize instructions that are available to
-// early due to a zero-latency dependence.
-static cl::opt<bool> CheckEarlyAvail("check-early-avail", cl::Hidden,
-                                     cl::init(true));
-
-// This value is used to determine if a register class is a high pressure set.
-// We compute the maximum number of registers needed and divided by the total
-// available. Then, we compare the result to this value.
-static cl::opt<float> RPThreshold("vliw-misched-reg-pressure", cl::Hidden,
-                                  cl::init(0.75f),
-                                  cl::desc("High register pressure 
threhold."));
-
 VLIWResourceModel::VLIWResourceModel(const TargetSubtargetInfo &STI,
                                      const TargetSchedModel *SM)
     : TII(STI.getInstrInfo()), SchedModel(SM) {
@@ -231,7 +210,7 @@ void VLIWMachineScheduler::schedule() {
     dbgs() << "Max Depth " << maxD << "\n";
   });
   LLVM_DEBUG(dump());
-  if (ViewMISchedDAGs)
+  if (shouldViewMISchedDAGs(MF))
     viewGraph();
 
   initQueues(TopRoots, BotRoots);
@@ -294,7 +273,8 @@ void ConvergingVLIWScheduler::initialize(ScheduleDAGMI 
*dag) {
   for (unsigned i = 0, e = MaxPressure.size(); i < e; ++i) {
     unsigned Limit = DAG->getRegClassInfo()->getRegPressureSetLimit(i);
     HighPressureSets[i] =
-        ((float)MaxPressure[i] > ((float)Limit * RPThreshold));
+        ((float)MaxPressure[i] >
+         ((float)Limit * DAG->Opts.vliw_misched_reg_pressure));
   }
 }
 
@@ -678,7 +658,7 @@ int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, 
SUnit *SU,
   });
 
   // Factor in reg pressure as a heuristic.
-  if (!IgnoreBBRegPressure) {
+  if (!DAG->Opts.vliw_misched_ignore_bb_reg_pressure) {
     // Decrease priority by the amount that register pressure exceeds the 
limit.
     ResCount -= (Delta.Excess.getUnitInc() * PriorityOne);
     // Decrease priority if register pressure exceeds the limit.
@@ -727,7 +707,7 @@ int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, 
SUnit *SU,
   // when the dependent instruction is scheduled in a new packet, so the
   // scheduler updates the current cycle and pending instructions become
   // available.
-  if (CheckEarlyAvail) {
+  if (DAG->Opts.vliw_misched_check_early_avail) {
     if (Q.getID() == TopQID) {
       for (const auto &PI : SU->Preds) {
         if (PI.getLatency() > 0 &&
@@ -766,7 +746,7 @@ 
ConvergingVLIWScheduler::pickNodeFromQueue(VLIWSchedBoundary &Zone,
                                            const RegPressureTracker &RPTracker,
                                            SchedCandidate &Candidate) {
   ReadyQueue &Q = Zone.Available;
-  LLVM_DEBUG(if (SchedDebugVerboseLevel > 1)
+  LLVM_DEBUG(if (DAG->Opts.vliw_misched_verbose_level > 1)
                  readyQueueVerboseDump(RPTracker, Candidate, Q);
              else Q.dump(););
 
@@ -856,7 +836,8 @@ 
ConvergingVLIWScheduler::pickNodeFromQueue(VLIWSchedBoundary &Zone,
     // Tie breaker.
     // To avoid scheduling indeterminism, we need a tie breaker
     // for the case when cost is identical for two nodes.
-    if (UseNewerCandidate && CurrentCost == Candidate.SCost) {
+    if (DAG->Opts.vliw_misched_use_newer_candidate &&
+        CurrentCost == Candidate.SCost) {
       if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum) ||
           (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
         LLVM_DEBUG(traceCandidate("TCAND", Q, *I, CurrentCost));
@@ -950,7 +931,7 @@ SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
     return nullptr;
   }
   SUnit *SU;
-  if (getPreRADirection() == MISched::TopDown) {
+  if (DAG->Opts.misched_prera_direction == MISched::TopDown) {
     SU = Top.pickOnlyChoice();
     if (!SU) {
       SchedCandidate TopCand;
@@ -961,7 +942,7 @@ SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
       SU = TopCand.SU;
     }
     IsTopNode = true;
-  } else if (getPreRADirection() == MISched::BottomUp) {
+  } else if (DAG->Opts.misched_prera_direction == MISched::BottomUp) {
     SU = Bot.pickOnlyChoice();
     if (!SU) {
       SchedCandidate BotCand;

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp
index d08b98a132fa73..e9695a7c9425e2 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUCoExecSchedStrategy.cpp
@@ -1119,8 +1119,8 @@ void 
AMDGPUCoExecSchedStrategy::initPolicy(MachineBasicBlock::iterator Begin,
                                            MachineBasicBlock::iterator End,
                                            unsigned NumRegionInstrs) {
   GCNSchedStrategy::initPolicy(Begin, End, NumRegionInstrs);
-  if (getPreRADirection() == MISched::BottomUp ||
-      getPreRADirection() == MISched::Bidirectional)
+  MISched::Direction Direction = getPreRADirection(*Context->MF);
+  if (Direction == MISched::BottomUp || Direction == MISched::Bidirectional)
     report_fatal_error("CoExecSchedStrategy only support TopDown scheduling.");
   RegionPolicy.OnlyTopDown = true;
   RegionPolicy.OnlyBottomUp = false;

diff  --git a/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp 
b/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
index 7302f18c77aa2e..eaeb3ca966de33 100644
--- a/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
+++ b/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
@@ -569,7 +569,7 @@ SUnit *GCNSchedStrategy::pickNodeBidirectional(bool 
&IsTopNode,
   } else {
     LLVM_DEBUG(traceCandidate(BotCand));
 #ifndef NDEBUG
-    if (shouldVerifyScheduling()) {
+    if (shouldVerifyScheduling(DAG->MF)) {
       SchedCandidate TCand;
       TCand.reset(CandPolicy());
       pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand,
@@ -594,7 +594,7 @@ SUnit *GCNSchedStrategy::pickNodeBidirectional(bool 
&IsTopNode,
   } else {
     LLVM_DEBUG(traceCandidate(TopCand));
 #ifndef NDEBUG
-    if (shouldVerifyScheduling()) {
+    if (shouldVerifyScheduling(DAG->MF)) {
       SchedCandidate TCand;
       TCand.reset(CandPolicy());
       pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand,

diff  --git a/llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp 
b/llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp
index 71dfe0a54df264..02fefe27916006 100644
--- a/llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp
+++ b/llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp
@@ -1811,9 +1811,9 @@ void SIScheduleDAGMI::schedule()
   postProcessDAG();
 
   LLVM_DEBUG(dump());
-  if (PrintDAGs)
+  if (shouldPrintMISchedDAGs(MF))
     dump();
-  if (ViewMISchedDAGs)
+  if (shouldViewMISchedDAGs(MF))
     viewGraph();
 
   topologicalSort();

diff  --git a/llvm/test/CodeGen/AArch64/aarch64-stp-cluster.ll 
b/llvm/test/CodeGen/AArch64/aarch64-stp-cluster.ll
index 517e71483e7957..f68e214809da44 100644
--- a/llvm/test/CodeGen/AArch64/aarch64-stp-cluster.ll
+++ b/llvm/test/CodeGen/AArch64/aarch64-stp-cluster.ll
@@ -1,6 +1,6 @@
 ; REQUIRES: asserts
 ; RUN: llc < %s -mtriple=arm64-linux-gnu -mcpu=cortex-a57 -verify-misched 
-debug-only=machine-scheduler -aarch64-enable-stp-suppress=false -o - 2>&1 > 
/dev/null | FileCheck %s
-; RUN: llc < %s -mtriple=arm64-linux-gnu -mcpu=cortex-a57 -force-fast-cluster 
-verify-misched -debug-only=machine-scheduler 
-aarch64-enable-stp-suppress=false -o - 2>&1 > /dev/null | FileCheck %s 
--check-prefix=CHECK-FAST
+; RUN: llc < %s -mtriple=arm64-linux-gnu -mcpu=cortex-a57 
-misched-force-fast-cluster -verify-misched -debug-only=machine-scheduler 
-aarch64-enable-stp-suppress=false -o - 2>&1 > /dev/null | FileCheck %s 
--check-prefix=CHECK-FAST
 
 ; CHECK: Current Schedule Region
 ; CHECK-LABEL: stp_i64_scale:%bb.0


        
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to