[llvm] [MC][TableGen] Pack MCInstrDesc fields into 24 bytes (PR #202647)

David Zbarsky via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 15 07:24:45 PDT 2026


https://github.com/dzbarsky updated https://github.com/llvm/llvm-project/pull/202647

>From c918ca1b4218a5369ec4018b2126c18ebed4030b Mon Sep 17 00:00:00 2001
From: David Zbarsky <dzbarsky at gmail.com>
Date: Mon, 8 Jun 2026 20:45:49 -0400
Subject: [PATCH] [MC][TableGen] Pack MCInstrDesc fields into 24 bytes

Pack the generated MCInstrDesc fields after TSFlags into two uint64_t
allocation units. This reduces sizeof(MCInstrDesc) from 32 to 24 bytes.

Store NumOperands directly in eight bits. Store the smaller of NumDefs and
NumOperands - NumDefs in five bits plus a selector bit, and derive NumDefs in
getNumDefs(). Across all 24 targets, NumOperands reaches 131 of 255 and the
stored count reaches 8 of 31.

Store instruction sizes below 64 directly and larger sizes in four-byte units.
This supports sizes through 316; the current maximum is 252. The other current
maxima are 55,698 of 65,535 opcodes, 5,824 of 8,191 scheduling classes, 52 of
63 implicit uses and definitions, 22,084 of 32,768 operand-info entries, and an
implicit-list offset of 738 of 1,023. MCID currently uses all 41 flag bits.

TableGen diagnoses generated values outside the supported ranges. Static
assertions check the flag count, operand-info extent, and 24-byte layout. Make
the packed fields private and update LLVM, llvm-exegesis, and BOLT callers to
use MCInstrDesc accessors. Add boundary tests for the count and size encodings.

The 24-byte layout removes 8 bytes per retained descriptor. The measured arm64
release builds retain 111,454 descriptors in the multicall binary and 10,322 in
llvm-mca, reducing their descriptor-table payloads by 891,632 bytes and 82,576
bytes, respectively.

Rebuild llvm-tblgen, generate instruction descriptors for all 24 targets, and
compile every modified production and unit-test translation unit. The existing
alternating tramp3d and llvm-mca measurements changed mean user CPU by -0.11%
and +0.05%, respectively.
---
 bolt/lib/Core/MCPlusBuilder.cpp               |  2 +-
 bolt/lib/Target/X86/X86MCPlusBuilder.cpp      |  8 +-
 llvm/include/llvm/MC/MCInstrDesc.h            | 78 +++++++++++++++----
 llvm/lib/CodeGen/MachineInstr.cpp             |  8 +-
 llvm/lib/CodeGen/MachineVerifier.cpp          |  2 +-
 .../CodeGen/ScoreboardHazardRecognizer.cpp    |  2 +-
 llvm/lib/DWARFCFIChecker/DWARFCFIAnalysis.cpp |  5 +-
 llvm/lib/MC/MCInstrDesc.cpp                   |  4 +-
 .../AMDGPU/AsmParser/AMDGPUAsmParser.cpp      |  4 +-
 llvm/lib/Target/AMDGPU/SIInstrInfo.cpp        |  8 +-
 llvm/lib/Target/AMDGPU/SIInstrInfo.h          |  6 +-
 .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp    |  6 +-
 llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp      |  2 +-
 .../lib/Target/ARM/AsmParser/ARMAsmParser.cpp |  8 +-
 .../ARM/Disassembler/ARMDisassembler.cpp      |  4 +-
 .../ARM/MCTargetDesc/ARMMCTargetDesc.cpp      |  2 +-
 llvm/lib/Target/Mips/MipsSEInstrInfo.cpp      |  2 +-
 .../Target/RISCV/RISCVPushPopOptimizer.cpp    |  4 +-
 .../MCTargetDesc/WebAssemblyInstPrinter.cpp   |  2 +-
 .../WebAssembly/WebAssemblyMCInstLower.cpp    |  5 +-
 .../lib/Target/X86/MCTargetDesc/X86BaseInfo.h |  2 +-
 llvm/lib/Target/X86/X86InstrInfo.cpp          |  2 +-
 llvm/test/TableGen/InstrInfoEmitterErrors.td  | 20 +++++
 llvm/tools/llvm-exegesis/lib/CodeTemplate.cpp |  2 +-
 llvm/tools/llvm-exegesis/lib/X86/Target.cpp   | 12 +--
 llvm/unittests/CodeGen/LexicalScopesTest.cpp  | 24 +++---
 llvm/unittests/MC/CMakeLists.txt              |  2 +-
 llvm/unittests/MC/MCInstrDescTest.cpp         | 45 +++++++++++
 llvm/utils/TableGen/InstrInfoEmitter.cpp      | 39 +++++++++-
 29 files changed, 227 insertions(+), 83 deletions(-)
 create mode 100644 llvm/test/TableGen/InstrInfoEmitterErrors.td
 create mode 100644 llvm/unittests/MC/MCInstrDescTest.cpp

diff --git a/bolt/lib/Core/MCPlusBuilder.cpp b/bolt/lib/Core/MCPlusBuilder.cpp
index 0cb4ba1ebfbd7..fef918924e9b3 100644
--- a/bolt/lib/Core/MCPlusBuilder.cpp
+++ b/bolt/lib/Core/MCPlusBuilder.cpp
@@ -546,7 +546,7 @@ bool MCPlusBuilder::hasDefOfPhysReg(const MCInst &MI, unsigned Reg) const {
 
 bool MCPlusBuilder::hasUseOfPhysReg(const MCInst &MI, unsigned Reg) const {
   const MCInstrDesc &InstInfo = Info->get(MI.getOpcode());
-  for (int I = InstInfo.NumDefs; I < InstInfo.NumOperands; ++I)
+  for (unsigned I = InstInfo.getNumDefs(); I < InstInfo.getNumOperands(); ++I)
     if (MI.getOperand(I).isReg() && MI.getOperand(I).getReg() &&
         RegInfo->isSubRegisterEq(Reg, MI.getOperand(I).getReg()))
       return true;
diff --git a/bolt/lib/Target/X86/X86MCPlusBuilder.cpp b/bolt/lib/Target/X86/X86MCPlusBuilder.cpp
index 923de64be58c8..6b216590aac13 100644
--- a/bolt/lib/Target/X86/X86MCPlusBuilder.cpp
+++ b/bolt/lib/Target/X86/X86MCPlusBuilder.cpp
@@ -105,7 +105,7 @@ class X86MCPlusBuilder : public MCPlusBuilder {
   unsigned getCondCode(const MCInst &Inst) const override {
     unsigned Opcode = Inst.getOpcode();
     if (X86::isJCC(Opcode))
-      return Inst.getOperand(Info->get(Opcode).NumOperands - 1).getImm();
+      return Inst.getOperand(Info->get(Opcode).getNumOperands() - 1).getImm();
     return X86::COND_INVALID;
   }
 
@@ -2810,7 +2810,8 @@ class X86MCPlusBuilder : public MCPlusBuilder {
                               MCContext *Ctx) const override {
     unsigned InvCC = getInvertedCondCode(getCondCode(Inst));
     assert(InvCC != X86::COND_INVALID && "invalid branch instruction");
-    Inst.getOperand(Info->get(Inst.getOpcode()).NumOperands - 1).setImm(InvCC);
+    Inst.getOperand(Info->get(Inst.getOpcode()).getNumOperands() - 1)
+        .setImm(InvCC);
     Inst.getOperand(0) =
         MCOperand::createExpr(MCSymbolRefExpr::create(TBB, *Ctx));
   }
@@ -2819,7 +2820,8 @@ class X86MCPlusBuilder : public MCPlusBuilder {
                               unsigned CC) const override {
     if (CC == X86::COND_INVALID)
       return false;
-    Inst.getOperand(Info->get(Inst.getOpcode()).NumOperands - 1).setImm(CC);
+    Inst.getOperand(Info->get(Inst.getOpcode()).getNumOperands() - 1)
+        .setImm(CC);
     Inst.getOperand(0) =
         MCOperand::createExpr(MCSymbolRefExpr::create(TBB, *Ctx));
     return true;
diff --git a/llvm/include/llvm/MC/MCInstrDesc.h b/llvm/include/llvm/MC/MCInstrDesc.h
index da65487ce9c65..5bef4c1507a5e 100644
--- a/llvm/include/llvm/MC/MCInstrDesc.h
+++ b/llvm/include/llvm/MC/MCInstrDesc.h
@@ -188,6 +188,7 @@ enum Flag {
   Trap,
   VariadicOpsAreDefs,
   Authenticated,
+  NumFlags,
 };
 } // namespace MCID
 
@@ -203,23 +204,56 @@ class MCInstrDesc {
   // the <Target>Insts table because they rely on knowing their own address to
   // find other information elsewhere in the same table.
 
-  uint32_t Opcode;         // The opcode number.
-  uint16_t NumOperands;    // Num of args (may be more if variable_ops)
-  uint8_t NumDefs;         // Num of args that are definitions
-  uint8_t Size;            // Number of bytes in encoding.
-  uint16_t SchedClass;     // enum identifying instr sched class
-  uint8_t NumImplicitUses; // Num of regs implicitly used
-  uint8_t NumImplicitDefs; // Num of regs implicitly defined
-  uint16_t OpInfoOffset;   // Offset to info about operands
-  uint16_t ImplicitOffset; // Offset to start of implicit op list
-  uint64_t Flags;          // Flags identifying machine instr class
-  uint64_t TSFlags;        // Target Specific Flag values
+  uint64_t TSFlags; // Target-specific flag values.
+
+private:
+  static constexpr unsigned NumNonDefsFlag = 1U << 5;
+  static constexpr unsigned NumDefsCountMask = NumNonDefsFlag - 1;
+
+  static constexpr unsigned encodeNumDefs(unsigned NumOperands,
+                                          unsigned NumDefs) {
+    unsigned NumNonDefs = NumOperands - NumDefs;
+    return NumDefs <= NumNonDefs ? NumDefs : (NumNonDefsFlag | NumNonDefs);
+  }
+
+  // Store sizes below 64 directly and larger sizes in four-byte units.
+  static constexpr unsigned encodeSize(unsigned Size) {
+    return Size < 64 ? Size : 64 + (Size - 64) / 4;
+  }
+
+  uint64_t Flags : 41;      // Flags identifying machine instruction classes.
+  uint64_t Opcode : 16;     // The opcode number.
+  uint64_t EncodedSize : 7; // The encoded instruction size.
+
+  uint64_t NumOperands : 8;
+  // Store the smaller of the definition and non-definition counts. Bit 5 is
+  // set when bits 0 through 4 contain the non-definition count.
+  uint64_t EncodedNumDefs : 6;
+  uint64_t SchedClass : 13;     // enum identifying instr sched class
+  uint64_t NumImplicitUses : 6; // Num of regs implicitly used
+  uint64_t NumImplicitDefs : 6; // Num of regs implicitly defined
+  uint64_t OpInfoOffset : 15;   // Offset to info about operands
+  uint64_t ImplicitOffset : 10; // Offset to start of implicit op list
+
+public:
+  constexpr MCInstrDesc(uint32_t Opcode = 0, uint16_t NumOperands = 0,
+                        uint8_t NumDefs = 0, uint16_t Size = 0,
+                        uint16_t SchedClass = 0, uint8_t NumImplicitUses = 0,
+                        uint8_t NumImplicitDefs = 0, uint16_t OpInfoOffset = 0,
+                        uint16_t ImplicitOffset = 0, uint64_t Flags = 0,
+                        uint64_t TSFlags = 0)
+      : TSFlags(TSFlags), Flags(Flags), Opcode(Opcode),
+        EncodedSize(encodeSize(Size)), NumOperands(NumOperands),
+        EncodedNumDefs(encodeNumDefs(NumOperands, NumDefs)),
+        SchedClass(SchedClass), NumImplicitUses(NumImplicitUses),
+        NumImplicitDefs(NumImplicitDefs), OpInfoOffset(OpInfoOffset),
+        ImplicitOffset(ImplicitOffset) {}
 
   /// Returns the value of the specified operand constraint if
   /// it is present. Returns -1 if it is not present.
   int getOperandConstraint(unsigned OpNum,
                            MCOI::OperandConstraint Constraint) const {
-    if (OpNum < NumOperands &&
+    if (OpNum < getNumOperands() &&
         (operands()[OpNum].Constraints & (1 << Constraint))) {
       unsigned ValuePos = 4 + Constraint * 4;
       return (int)(operands()[OpNum].Constraints >> ValuePos) & 0x0f;
@@ -239,14 +273,23 @@ class MCInstrDesc {
 
   ArrayRef<MCOperandInfo> operands() const {
     auto OpInfo = reinterpret_cast<const MCOperandInfo *>(this + Opcode + 1);
-    return ArrayRef(OpInfo + OpInfoOffset, NumOperands);
+    return ArrayRef(OpInfo + OpInfoOffset, getNumOperands());
   }
 
   /// Return the number of MachineOperands that are register
   /// definitions.  Register definitions always occur at the start of the
   /// machine operand list.  This is the number of "outs" in the .td file,
   /// and does not include implicit defs.
-  unsigned getNumDefs() const { return NumDefs; }
+  unsigned getNumDefs() const {
+    unsigned Count = EncodedNumDefs & NumDefsCountMask;
+    return EncodedNumDefs & NumNonDefsFlag ? NumOperands - Count : Count;
+  }
+
+  /// Return the number of implicitly used registers.
+  unsigned getNumImplicitUses() const { return NumImplicitUses; }
+
+  /// Return the number of implicitly defined registers.
+  unsigned getNumImplicitDefs() const { return NumImplicitDefs; }
 
   /// Return flags of this instruction.
   uint64_t getFlags() const { return Flags; }
@@ -604,7 +647,9 @@ class MCInstrDesc {
 
   /// Return the number of bytes in the encoding of this instruction,
   /// or zero if the encoding size cannot be known from the opcode.
-  unsigned getSize() const { return Size; }
+  unsigned getSize() const {
+    return EncodedSize < 64 ? EncodedSize : 64 + (EncodedSize - 64) * 4;
+  }
 
   /// Find the index of the first operand in the
   /// operand list that is used to represent the predicate. It returns -1 if
@@ -629,6 +674,9 @@ class MCInstrDesc {
                                 const MCRegisterInfo &RI) const;
 };
 
+static_assert(MCID::NumFlags <= 41);
+static_assert(sizeof(MCInstrDesc) == 24);
+
 } // end namespace llvm
 
 #endif
diff --git a/llvm/lib/CodeGen/MachineInstr.cpp b/llvm/lib/CodeGen/MachineInstr.cpp
index 374c92241b9fb..32f1ffb8eee42 100644
--- a/llvm/lib/CodeGen/MachineInstr.cpp
+++ b/llvm/lib/CodeGen/MachineInstr.cpp
@@ -100,7 +100,7 @@ void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &TID,
                            DebugLoc DL, bool NoImp)
     : MCID(&TID), NumOperands(0), Flags(0), AsmPrinterFlags(0),
-      Opcode(TID.Opcode), DebugInstrNum(0), DbgLoc(std::move(DL)) {
+      Opcode(TID.getOpcode()), DebugInstrNum(0), DbgLoc(std::move(DL)) {
   // Reserve space for the expected number of operands.
   if (unsigned NumOps = MCID->getNumOperands() + MCID->implicit_defs().size() +
                         MCID->implicit_uses().size()) {
@@ -142,7 +142,7 @@ void MachineInstr::setDesc(const MCInstrDesc &TID) {
   if (getParent())
     getMF()->handleChangeDesc(*this, TID);
   MCID = &TID;
-  Opcode = TID.Opcode;
+  Opcode = TID.getOpcode();
 }
 
 void MachineInstr::moveBefore(MachineInstr *MovePos) {
@@ -1719,7 +1719,7 @@ void MachineInstr::copyImplicitOps(MachineFunction &MF,
 
 bool MachineInstr::hasComplexRegisterTies() const {
   const MCInstrDesc &MCID = getDesc();
-  if (MCID.Opcode == TargetOpcode::STATEPOINT)
+  if (MCID.getOpcode() == TargetOpcode::STATEPOINT)
     return true;
   for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
     const auto &Operand = getOperand(I);
@@ -2396,7 +2396,7 @@ MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
          "Expected inlined-at fields to agree");
-  if (MCID.Opcode == TargetOpcode::DBG_VALUE) {
+  if (MCID.getOpcode() == TargetOpcode::DBG_VALUE) {
     assert(DebugOps.size() == 1 &&
            "DBG_VALUE must contain exactly one debug operand");
     MachineOperand DebugOp = DebugOps[0];
diff --git a/llvm/lib/CodeGen/MachineVerifier.cpp b/llvm/lib/CodeGen/MachineVerifier.cpp
index c611b837a86b4..876ea5053a53f 100644
--- a/llvm/lib/CodeGen/MachineVerifier.cpp
+++ b/llvm/lib/CodeGen/MachineVerifier.cpp
@@ -2607,7 +2607,7 @@ MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
 
-  // The first MCID.NumDefs operands must be explicit register defines
+  // The first NumDefs operands must be explicit register definitions.
   if (MONum < NumDefs) {
     const MCOperandInfo &MCOI = MCID.operands()[MONum];
     if (!MO->isReg())
diff --git a/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp b/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp
index 209c6d81f6020..5bb9a28e7760c 100644
--- a/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp
+++ b/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp
@@ -176,7 +176,7 @@ void ScoreboardHazardRecognizer::EmitInstruction(SUnit *SU) {
   // in the scoreboard at the appropriate future cycles.
   const MCInstrDesc *MCID = DAG->getInstrDesc(SU);
   assert(MCID && "The scheduler must filter non-machineinstrs");
-  if (DAG->TII->isZeroCost(MCID->Opcode))
+  if (DAG->TII->isZeroCost(MCID->getOpcode()))
     return;
 
   ++IssueCount;
diff --git a/llvm/lib/DWARFCFIChecker/DWARFCFIAnalysis.cpp b/llvm/lib/DWARFCFIChecker/DWARFCFIAnalysis.cpp
index 24ae7c21098f9..09479c7e3e25b 100644
--- a/llvm/lib/DWARFCFIChecker/DWARFCFIAnalysis.cpp
+++ b/llvm/lib/DWARFCFIChecker/DWARFCFIAnalysis.cpp
@@ -135,9 +135,8 @@ void DWARFCFIAnalysis::update(const MCInst &Inst,
     State.update(Directive);
 
   SmallSet<DWARFRegNum, 4> Writes;
-  for (unsigned I = 0; I < MCInstInfo.NumImplicitDefs; I++)
-    Writes.insert(MCRI->getDwarfRegNum(
-        getSuperReg(MCRI, MCInstInfo.implicit_defs()[I]), IsEH));
+  for (MCPhysReg Reg : MCInstInfo.implicit_defs())
+    Writes.insert(MCRI->getDwarfRegNum(getSuperReg(MCRI, Reg), IsEH));
 
   for (unsigned I = 0; I < Inst.getNumOperands(); I++) {
     auto &&Op = Inst.getOperand(I);
diff --git a/llvm/lib/MC/MCInstrDesc.cpp b/llvm/lib/MC/MCInstrDesc.cpp
index 99cdb44168ec6..d6f8e61308a82 100644
--- a/llvm/lib/MC/MCInstrDesc.cpp
+++ b/llvm/lib/MC/MCInstrDesc.cpp
@@ -39,12 +39,12 @@ bool MCInstrDesc::hasImplicitDefOfPhysReg(MCRegister Reg,
 
 bool MCInstrDesc::hasExplicitDefOfPhysReg(const MCInst &MI, MCRegister Reg,
                                           const MCRegisterInfo &RI) const {
-  for (int i = 0, e = NumDefs; i != e; ++i)
+  for (int i = 0, e = getNumDefs(); i != e; ++i)
     if (MI.getOperand(i).isReg() && MI.getOperand(i).getReg() &&
         RI.isSubRegisterEq(Reg, MI.getOperand(i).getReg()))
       return true;
   if (variadicOpsAreDefs())
-    for (int i = NumOperands - 1, e = MI.getNumOperands(); i != e; ++i)
+    for (int i = getNumOperands() - 1, e = MI.getNumOperands(); i != e; ++i)
       if (MI.getOperand(i).isReg() &&
           RI.isSubRegisterEq(Reg, MI.getOperand(i).getReg()))
         return true;
diff --git a/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp b/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
index 2a9a31e732a6e..e2c3919da7370 100644
--- a/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
+++ b/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
@@ -1388,7 +1388,7 @@ class AMDGPUAsmParser : public MCTargetAsmParser {
 
   /// Get size of register operand
   unsigned getRegOperandSize(const MCInstrDesc &Desc, unsigned OpNo) const {
-    assert(OpNo < Desc.NumOperands);
+    assert(OpNo < Desc.getNumOperands());
     int16_t RCID = MII.getOpRegClassID(Desc.operands()[OpNo], HwMode);
     return getRegBitWidth(RCID) / 8;
   }
@@ -9497,7 +9497,7 @@ static bool isRegOrImmWithInputMods(const MCInstrDesc &Desc, unsigned OpNum) {
       // 1. This operand is input modifiers
       Desc.operands()[OpNum].OperandType == AMDGPU::OPERAND_INPUT_MODS
       // 2. This is not last operand
-      && Desc.NumOperands > (OpNum + 1)
+      && Desc.getNumOperands() > (OpNum + 1)
       // 3. Next operand is register class
       && Desc.operands()[OpNum + 1].RegClass != -1
       // 4. Next register is not tied to any other operand
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
index ef9d184555bd6..d8095259bb45f 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
@@ -257,8 +257,8 @@ bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
     // include the output in the operand list, but SDNodes don't, we need to
     // subtract the index by one.
-    Offset0Idx -= get(Opc0).NumDefs;
-    Offset1Idx -= get(Opc1).NumDefs;
+    Offset0Idx -= get(Opc0).getNumDefs();
+    Offset1Idx -= get(Opc1).getNumDefs();
     Offset0 = Load0->getConstantOperandVal(Offset0Idx);
     Offset1 = Load1->getConstantOperandVal(Offset1Idx);
     return true;
@@ -314,8 +314,8 @@ bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
     // include the output in the operand list, but SDNodes don't, we need to
     // subtract the index by one.
-    OffIdx0 -= get(Opc0).NumDefs;
-    OffIdx1 -= get(Opc1).NumDefs;
+    OffIdx0 -= get(Opc0).getNumDefs();
+    OffIdx1 -= get(Opc1).getNumDefs();
 
     SDValue Off0 = Load0->getOperand(OffIdx0);
     SDValue Off1 = Load1->getOperand(OffIdx1);
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.h b/llvm/lib/Target/AMDGPU/SIInstrInfo.h
index 831aa9ebb8435..cdf0853a43491 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.h
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.h
@@ -1316,8 +1316,8 @@ class SIInstrInfo final : public AMDGPUGenInstrInfo {
                         const MachineOperand &UseMO,
                         const MachineOperand &DefMO) const {
     assert(UseMO.getParent() == &MI);
-    int OpIdx = UseMO.getOperandNo();
-    if (OpIdx >= MI.getDesc().NumOperands)
+    unsigned OpIdx = UseMO.getOperandNo();
+    if (OpIdx >= MI.getDesc().getNumOperands())
       return false;
 
     return isInlineConstant(DefMO, MI.getDesc().operands()[OpIdx]);
@@ -1332,7 +1332,7 @@ class SIInstrInfo final : public AMDGPUGenInstrInfo {
 
   bool isInlineConstant(const MachineInstr &MI, unsigned OpIdx,
                         int64_t ImmVal) const {
-    if (OpIdx >= MI.getDesc().NumOperands)
+    if (OpIdx >= MI.getDesc().getNumOperands())
       return false;
 
     if (isCopyInstr(MI)) {
diff --git a/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp b/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp
index 33df51e8a7e07..e8915d1f331ef 100644
--- a/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp
@@ -2868,14 +2868,14 @@ bool isInlineValue(MCRegister Reg) {
 #undef MAP_REG2REG
 
 bool isKImmOperand(const MCInstrDesc &Desc, unsigned OpNo) {
-  assert(OpNo < Desc.NumOperands);
+  assert(OpNo < Desc.getNumOperands());
   unsigned OpType = Desc.operands()[OpNo].OperandType;
   return OpType >= AMDGPU::OPERAND_KIMM_FIRST &&
          OpType <= AMDGPU::OPERAND_KIMM_LAST;
 }
 
 bool isSISrcFPOperand(const MCInstrDesc &Desc, unsigned OpNo) {
-  assert(OpNo < Desc.NumOperands);
+  assert(OpNo < Desc.getNumOperands());
   unsigned OpType = Desc.operands()[OpNo].OperandType;
   switch (OpType) {
   case AMDGPU::OPERAND_REG_IMM_FP32:
@@ -2898,7 +2898,7 @@ bool isSISrcFPOperand(const MCInstrDesc &Desc, unsigned OpNo) {
 }
 
 bool isSISrcInlinableOperand(const MCInstrDesc &Desc, unsigned OpNo) {
-  assert(OpNo < Desc.NumOperands);
+  assert(OpNo < Desc.getNumOperands());
   unsigned OpType = Desc.operands()[OpNo].OperandType;
   return (OpType >= AMDGPU::OPERAND_REG_INLINE_C_FIRST &&
           OpType <= AMDGPU::OPERAND_REG_INLINE_C_LAST) ||
diff --git a/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp b/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp
index 3b1b8673e56a0..2a7573e9ff5fa 100644
--- a/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp
+++ b/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp
@@ -4282,7 +4282,7 @@ ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
 
   const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
 
-  if (isZeroCost(DefMCID.Opcode))
+  if (isZeroCost(DefMCID.getOpcode()))
     return 0;
 
   if (!ItinData || ItinData->isEmpty())
diff --git a/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp b/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
index a4ac7f61713e0..860dd924a3a20 100644
--- a/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
+++ b/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
@@ -7636,7 +7636,7 @@ bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
 }
 
 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
-  for (unsigned i = 0; i < MCID.NumOperands; ++i) {
+  for (unsigned i = 0; i < MCID.getNumOperands(); ++i) {
     if (ARM::isVpred(MCID.operands()[i].OperandType))
       return i;
   }
@@ -11199,11 +11199,11 @@ unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
     assert(MCID.hasOptionalDef() &&
            "optionally flag setting instruction missing optional def operand");
-    assert(MCID.NumOperands == Inst.getNumOperands() &&
+    assert(MCID.getNumOperands() == Inst.getNumOperands() &&
            "operand count mismatch!");
     bool IsCPSR = false;
     // Check if the instruction has CPSR set.
-    for (unsigned OpNo = 0; OpNo < MCID.NumOperands; ++OpNo) {
+    for (unsigned OpNo = 0; OpNo < MCID.getNumOperands(); ++OpNo) {
       if (MCID.operands()[OpNo].isOptionalDef() &&
           Inst.getOperand(OpNo).isReg() &&
           Inst.getOperand(OpNo).getReg() == ARM::CPSR)
@@ -11290,7 +11290,7 @@ unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
     break;
   }
 
-  for (unsigned I = 0; I < MCID.NumOperands; ++I)
+  for (unsigned I = 0; I < MCID.getNumOperands(); ++I)
     if (MCID.operands()[I].RegClass == ARM::rGPRRegClassID) {
       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
       const auto &Op = Inst.getOperand(I);
diff --git a/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp b/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp
index 2fa07ee611d49..45dd019a37f67 100644
--- a/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp
+++ b/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp
@@ -6242,7 +6242,7 @@ DecodeStatus ARMDisassembler::getARMInstruction(MCInst &MI, uint64_t &Size,
 
 bool ARMDisassembler::isVectorPredicable(const MCInst &MI) const {
   const MCInstrDesc &MCID = MCII->get(MI.getOpcode());
-  for (unsigned i = 0; i < MCID.NumOperands; ++i) {
+  for (unsigned i = 0; i < MCID.getNumOperands(); ++i) {
     if (ARM::isVpred(MCID.operands()[i].OperandType))
       return true;
   }
@@ -6332,7 +6332,7 @@ void ARMDisassembler::UpdateThumbPredicate(DecodeStatus &S, MCInst &MI) const {
   const MCInstrDesc &MCID = MCII->get(MI.getOpcode());
   ArrayRef<MCOperandInfo> OpInfo = MCID.operands();
   MCInst::iterator I = MI.begin();
-  unsigned short NumOps = MCID.NumOperands;
+  unsigned short NumOps = MCID.getNumOperands();
   for (unsigned i = 0; i < NumOps; ++i, ++I) {
     if (OpInfo[i].isPredicate() ) {
       if (CC != ARMCC::AL && !MCID.isPredicable())
diff --git a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp
index 467fdbfd0e05b..b9089814211d9 100644
--- a/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp
+++ b/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp
@@ -572,7 +572,7 @@ std::optional<uint64_t> ARMMCInstrAnalysis::evaluateMemoryOperandAddress(
     return std::nullopt;
 
   // Find the memory addressing operand in the instruction.
-  unsigned OpIndex = Desc.NumDefs;
+  unsigned OpIndex = Desc.getNumDefs();
   while (OpIndex < Desc.getNumOperands() &&
          Desc.operands()[OpIndex].OperandType != MCOI::OPERAND_MEMORY)
     ++OpIndex;
diff --git a/llvm/lib/Target/Mips/MipsSEInstrInfo.cpp b/llvm/lib/Target/Mips/MipsSEInstrInfo.cpp
index 6c59975a1b501..f8049a92deabd 100644
--- a/llvm/lib/Target/Mips/MipsSEInstrInfo.cpp
+++ b/llvm/lib/Target/Mips/MipsSEInstrInfo.cpp
@@ -772,7 +772,7 @@ std::pair<bool, bool>
 MipsSEInstrInfo::compareOpndSize(unsigned Opc,
                                  const MachineFunction &MF) const {
   const MCInstrDesc &Desc = get(Opc);
-  assert(Desc.NumOperands == 2 && "Unary instruction expected.");
+  assert(Desc.getNumOperands() == 2 && "Unary instruction expected.");
   const MipsRegisterInfo *RI = &getRegisterInfo();
   unsigned DstRegSize = RI->getRegSizeInBits(*getRegClass(Desc, 0));
   unsigned SrcRegSize = RI->getRegSizeInBits(*getRegClass(Desc, 1));
diff --git a/llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp b/llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp
index eae7e8697f0ad..79f655f79ec16 100644
--- a/llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp
+++ b/llvm/lib/Target/RISCV/RISCVPushPopOptimizer.cpp
@@ -86,8 +86,8 @@ bool RISCVPushPopOpt::usePopRet(MachineBasicBlock::iterator &MBBI,
   // on what register list has been picked during frame lowering.
   const MCInstrDesc &PopDesc = MBBI->getDesc();
   unsigned FirstNonDeclaredOp = PopDesc.getNumOperands() +
-                                PopDesc.NumImplicitUses +
-                                PopDesc.NumImplicitDefs;
+                                PopDesc.getNumImplicitUses() +
+                                PopDesc.getNumImplicitDefs();
   for (unsigned i = FirstNonDeclaredOp; i < MBBI->getNumOperands(); ++i)
     PopRetBuilder.add(MBBI->getOperand(i));
 
diff --git a/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp b/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp
index 8cee0788def0a..dd700ba965cdc 100644
--- a/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp
+++ b/llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp
@@ -280,7 +280,7 @@ void WebAssemblyInstPrinter::printInst(const MCInst *MI, uint64_t Address,
 
     // Annotate any control flow label references.
 
-    unsigned NumFixedOperands = Desc.NumOperands;
+    unsigned NumFixedOperands = Desc.getNumOperands();
     SmallSet<uint64_t, 8> Printed;
     for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
       // See if this operand denotes a basic block target.
diff --git a/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp b/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp
index e48283aadb437..faf43140e57cd 100644
--- a/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp
+++ b/llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp
@@ -234,7 +234,8 @@ void WebAssemblyMCInstLower::lower(const MachineInstr *MI,
       // Currently this is the only way that CImmediates show up so panic if we
       // get confused.
       unsigned DescIndex = I - NumVariadicDefs;
-      assert(DescIndex < Desc.NumOperands && "unexpected CImmediate operand");
+      assert(DescIndex < Desc.getNumOperands() &&
+             "unexpected CImmediate operand");
       auto Operands = Desc.operands();
       const MCOperandInfo &Info = Operands[DescIndex];
       assert(Info.OperandType == WebAssembly::OPERAND_TYPEINDEX &&
@@ -245,7 +246,7 @@ void WebAssemblyMCInstLower::lower(const MachineInstr *MI,
     }
     case MachineOperand::MO_Immediate: {
       unsigned DescIndex = I - NumVariadicDefs;
-      if (DescIndex < Desc.NumOperands) {
+      if (DescIndex < Desc.getNumOperands()) {
         auto Operands = Desc.operands();
         const MCOperandInfo &Info = Operands[DescIndex];
         // Replace type index placeholder with actual type index. The type index
diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h b/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h
index 06b13c0982d21..2eedb19664bb3 100644
--- a/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h
+++ b/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h
@@ -1264,7 +1264,7 @@ inline bool canUseApxExtendedReg(const MCInstrDesc &Desc) {
   if (Encoding == X86II::EVEX)
     return true;
 
-  unsigned Opcode = Desc.Opcode;
+  unsigned Opcode = Desc.getOpcode();
   if (isPseudo(TSFlags)) {
     switch (Opcode) {
     default:
diff --git a/llvm/lib/Target/X86/X86InstrInfo.cpp b/llvm/lib/Target/X86/X86InstrInfo.cpp
index 15d2e10aa0f08..c9f064a889542 100644
--- a/llvm/lib/Target/X86/X86InstrInfo.cpp
+++ b/llvm/lib/Target/X86/X86InstrInfo.cpp
@@ -8764,7 +8764,7 @@ bool X86InstrInfo::unfoldMemoryOperand(
   MachineFunction &MF = DAG.getMachineFunction();
   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
   const TargetRegisterClass *RC = getRegClass(MCID, Index);
-  unsigned NumDefs = MCID.NumDefs;
+  unsigned NumDefs = MCID.getNumDefs();
   std::vector<SDValue> AddrOps;
   std::vector<SDValue> BeforeOps;
   std::vector<SDValue> AfterOps;
diff --git a/llvm/test/TableGen/InstrInfoEmitterErrors.td b/llvm/test/TableGen/InstrInfoEmitterErrors.td
new file mode 100644
index 0000000000000..44aa8f8658d4a
--- /dev/null
+++ b/llvm/test/TableGen/InstrInfoEmitterErrors.td
@@ -0,0 +1,20 @@
+// RUN: not llvm-tblgen -gen-instr-info -I %p/../../include %s 2>&1 | FileCheck %s
+
+include "llvm/Target/Target.td"
+
+def Reg : Register<"reg">;
+def Regs : RegisterClass<"test", [i32], 0, (add Reg)>;
+
+def TestInstrInfo : InstrInfo;
+def TestTarget : Target {
+  let InstructionSet = TestInstrInfo;
+}
+
+// CHECK: error: instruction size cannot be encoded in 7 bits
+def InvalidSize : Instruction {
+  let Namespace = "Test";
+  let OutOperandList = (outs);
+  let InOperandList = (ins);
+  let AsmString = "";
+  let Size = 320;
+}
diff --git a/llvm/tools/llvm-exegesis/lib/CodeTemplate.cpp b/llvm/tools/llvm-exegesis/lib/CodeTemplate.cpp
index fd156ee01e7ce..3d0925d15a924 100644
--- a/llvm/tools/llvm-exegesis/lib/CodeTemplate.cpp
+++ b/llvm/tools/llvm-exegesis/lib/CodeTemplate.cpp
@@ -65,7 +65,7 @@ bool InstructionTemplate::hasImmediateVariables() const {
 
 MCInst InstructionTemplate::build() const {
   MCInst Result;
-  Result.setOpcode(Instr->Description.Opcode);
+  Result.setOpcode(Instr->getOpcode());
   for (const auto &Op : Instr->Operands)
     if (Op.isExplicit())
       Result.addOperand(getValueFor(Op));
diff --git a/llvm/tools/llvm-exegesis/lib/X86/Target.cpp b/llvm/tools/llvm-exegesis/lib/X86/Target.cpp
index 3f2b9112e5c76..f0b7374f75973 100644
--- a/llvm/tools/llvm-exegesis/lib/X86/Target.cpp
+++ b/llvm/tools/llvm-exegesis/lib/X86/Target.cpp
@@ -178,10 +178,10 @@ static const char *isInvalidMemoryInstr(const Instruction &Instr) {
   case X86II::RawFrmImm8:
     return nullptr;
   case X86II::AddRegFrm:
-    return (Instr.Description.Opcode == X86::POP16r ||
-            Instr.Description.Opcode == X86::POP32r ||
-            Instr.Description.Opcode == X86::PUSH16r ||
-            Instr.Description.Opcode == X86::PUSH32r)
+    return (Instr.getOpcode() == X86::POP16r ||
+            Instr.getOpcode() == X86::POP32r ||
+            Instr.getOpcode() == X86::PUSH16r ||
+            Instr.getOpcode() == X86::PUSH32r)
                ? "unsupported opcode: unsupported memory access"
                : nullptr;
   // These access memory and are handled.
@@ -221,7 +221,7 @@ static const char *isInvalidOpcode(const Instruction &Instr) {
       OpcodeName.starts_with("PUSH") ||
       OpcodeName.starts_with("ADJCALLSTACK") || OpcodeName.starts_with("LEAVE"))
     return "unsupported opcode: Push/Pop/AdjCallStack/Leave";
-  switch (Instr.Description.Opcode) {
+  switch (Instr.getOpcode()) {
   case X86::LFS16rm:
   case X86::LFS32rm:
   case X86::LFS64rm:
@@ -786,7 +786,7 @@ class ExegesisX86Target : public ExegesisTarget {
   }
 
   bool allowAsBackToBack(const Instruction &Instr) const override {
-    const unsigned Opcode = Instr.Description.Opcode;
+    const unsigned Opcode = Instr.getOpcode();
     return !isInvalidOpcode(Instr) && Opcode != X86::LEA64r &&
            Opcode != X86::LEA64_32r && Opcode != X86::LEA16r;
   }
diff --git a/llvm/unittests/CodeGen/LexicalScopesTest.cpp b/llvm/unittests/CodeGen/LexicalScopesTest.cpp
index 0c6b9326bcfd4..2285a3d2d1eba 100644
--- a/llvm/unittests/CodeGen/LexicalScopesTest.cpp
+++ b/llvm/unittests/CodeGen/LexicalScopesTest.cpp
@@ -60,19 +60,17 @@ class LexicalScopesTest : public testing::Test {
   // Some meaningless instructions -- the first is fully meaningless,
   // while the second is supposed to impersonate DBG_VALUEs through its
   // opcode.
-  MCInstrDesc BeanInst{};
-  MCInstrDesc DbgValueInst{};
-
-  LexicalScopesTest() : Ctx(), Mod("beehives", Ctx) {
-    memset(&BeanInst, 0, sizeof(BeanInst));
-    BeanInst.Opcode = 1;
-    BeanInst.Size = 1;
-
-    memset(&DbgValueInst, 0, sizeof(MCInstrDesc));
-    DbgValueInst.Opcode = TargetOpcode::DBG_VALUE;
-    DbgValueInst.Size = 1;
-    DbgValueInst.Flags = 1U << MCID::Meta;
-
+  MCInstrDesc BeanInst;
+  MCInstrDesc DbgValueInst;
+
+  LexicalScopesTest()
+      : Ctx(), Mod("beehives", Ctx), BeanInst(/*Opcode=*/1, /*NumOperands=*/0,
+                                              /*NumDefs=*/0, /*Size=*/1),
+        DbgValueInst(TargetOpcode::DBG_VALUE, /*NumOperands=*/0,
+                     /*NumDefs=*/0, /*Size=*/1, /*SchedClass=*/0,
+                     /*NumImplicitUses=*/0, /*NumImplicitDefs=*/0,
+                     /*OpInfoOffset=*/0, /*ImplicitOffset=*/0,
+                     /*Flags=*/1U << MCID::Meta) {
     // Boilerplate that creates a MachineFunction and associated blocks.
     MF = createMachineFunction(Ctx, Mod);
     llvm::Function &F = const_cast<llvm::Function &>(MF->getFunction());
diff --git a/llvm/unittests/MC/CMakeLists.txt b/llvm/unittests/MC/CMakeLists.txt
index 4881888f03742..4b133b57cfdae 100644
--- a/llvm/unittests/MC/CMakeLists.txt
+++ b/llvm/unittests/MC/CMakeLists.txt
@@ -20,8 +20,8 @@ add_llvm_unittest(MCTests
   DwarfLineTables.cpp
   DwarfLineTableHeaders.cpp
   MCInstPrinter.cpp
+  MCInstrDescTest.cpp
   StringTableBuilderTest.cpp
   TargetRegistry.cpp
   MCDisassemblerTest.cpp
   )
-
diff --git a/llvm/unittests/MC/MCInstrDescTest.cpp b/llvm/unittests/MC/MCInstrDescTest.cpp
new file mode 100644
index 0000000000000..b8c6a973bf69e
--- /dev/null
+++ b/llvm/unittests/MC/MCInstrDescTest.cpp
@@ -0,0 +1,45 @@
+//===- MCInstrDescTest.cpp - MCInstrDesc unit tests -----------------------===//
+//
+// 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 "llvm/MC/MCInstrDesc.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+
+namespace {
+
+TEST(MCInstrDescTest, PackedFields) {
+  struct OperandCounts {
+    unsigned NumOperands;
+    unsigned NumDefs;
+  };
+
+  constexpr OperandCounts TestCounts[] = {
+      {0, 0},   {1, 0},     {1, 1},    {33, 8},    {67, 65},
+      {130, 0}, {131, 129}, {255, 31}, {255, 224}, {255, 255}};
+  for (OperandCounts Counts : TestCounts) {
+    for (unsigned Size : {0U, 2U, 3U, 4U, 63U, 64U, 252U, 316U}) {
+      MCInstrDesc Desc(65535, Counts.NumOperands, Counts.NumDefs, Size, 8191,
+                       63, 63, 32767, 1023, (1ULL << MCID::Authenticated) | 1,
+                       UINT64_MAX);
+
+      EXPECT_EQ(Desc.getOpcode(), 65535U);
+      EXPECT_EQ(Desc.getNumOperands(), Counts.NumOperands);
+      EXPECT_EQ(Desc.getNumDefs(), Counts.NumDefs);
+      EXPECT_EQ(Desc.getSize(), Size);
+      EXPECT_EQ(Desc.getSchedClass(), 8191U);
+      EXPECT_EQ(Desc.getNumImplicitUses(), 63U);
+      EXPECT_EQ(Desc.getNumImplicitDefs(), 63U);
+      EXPECT_TRUE(Desc.isPreISelOpcode());
+      EXPECT_TRUE(Desc.isAuthenticated());
+      EXPECT_EQ(Desc.TSFlags, UINT64_MAX);
+    }
+  }
+}
+
+} // namespace
diff --git a/llvm/utils/TableGen/InstrInfoEmitter.cpp b/llvm/utils/TableGen/InstrInfoEmitter.cpp
index 08526cc2a72bf..64a8e485c4c85 100644
--- a/llvm/utils/TableGen/InstrInfoEmitter.cpp
+++ b/llvm/utils/TableGen/InstrInfoEmitter.cpp
@@ -34,6 +34,7 @@
 #include "llvm/TableGen/Record.h"
 #include "llvm/TableGen/TGTimer.h"
 #include "llvm/TableGen/TableGenBackend.h"
+#include <algorithm>
 #include <cassert>
 #include <cstdint>
 #include <iterator>
@@ -950,6 +951,8 @@ void InstrInfoEmitter::run(raw_ostream &OS) {
       ImplicitListSize += ImplicitOps.size();
     }
   }
+  if (!isUInt<10>(ImplicitListSize))
+    PrintFatalError("implicit operand table does not fit in 10-bit offsets");
 
   {
     IfGuardEmitter IfGuard(
@@ -1002,7 +1005,10 @@ void InstrInfoEmitter::run(raw_ostream &OS) {
        << "InstrTable::Padding) % sizeof(MCOperandInfo) == 0);\n";
     OS << "static constexpr unsigned " << TargetName << "OpInfoBase = (sizeof "
        << TargetName << "InstrTable::ImplicitOps + sizeof " << TargetName
-       << "InstrTable::Padding) / sizeof(MCOperandInfo);\n\n";
+       << "InstrTable::Padding) / sizeof(MCOperandInfo);\n";
+    OS << "static_assert(" << TargetName << "OpInfoBase + " << OperandInfoSize
+       << " <= (1U << 15), "
+          "\"operand info table does not fit in 15-bit offsets\");\n\n";
 
     OS << "extern const " << TargetName << "InstrTable " << TargetName
        << "Descs = {\n  {\n";
@@ -1295,10 +1301,35 @@ void InstrInfoEmitter::emitRecord(
     DefOperands = Opnd.MIOperandNo + Opnd.MINumOperands;
   }
 
+  int64_t Size = Inst.TheDef->getValueAsInt("Size");
+  unsigned SchedClass = SchedModels.getSchedClassIdx(Inst);
+  if (!isUInt<16>(Num))
+    PrintFatalError(Inst.TheDef, "instruction opcode does not fit in 16 bits");
+  if (!isUInt<8>(MinOperands))
+    PrintFatalError(Inst.TheDef,
+                    "instruction operand count does not fit in 8 bits");
+  if (DefOperands > MinOperands)
+    PrintFatalError(Inst.TheDef,
+                    "instruction definition count exceeds operand count");
+  if (!isUInt<5>(std::min(DefOperands, MinOperands - DefOperands)))
+    PrintFatalError(
+        Inst.TheDef,
+        "instruction must have at most 31 definitions or at most 31 "
+        "non-definitions");
+  if (Size < 0 || (Size >= 64 && (Size > 316 || Size % 4 != 0)))
+    PrintFatalError(Inst.TheDef,
+                    "instruction size cannot be encoded in 7 bits");
+  if (!isUInt<13>(SchedClass))
+    PrintFatalError(Inst.TheDef,
+                    "instruction scheduling class does not fit in 13 bits");
+  if (!isUInt<6>(Inst.ImplicitUses.size()) ||
+      !isUInt<6>(Inst.ImplicitDefs.size()))
+    PrintFatalError(Inst.TheDef,
+                    "implicit register count does not fit in 6 bits");
+
   OS << "    { ";
-  OS << Num << ",\t" << MinOperands << ",\t" << DefOperands << ",\t"
-     << Inst.TheDef->getValueAsInt("Size") << ",\t"
-     << SchedModels.getSchedClassIdx(Inst) << ",\t";
+  OS << Num << ",\t" << MinOperands << ",\t" << DefOperands << ",\t" << Size
+     << ",\t" << SchedClass << ",\t";
 
   const CodeGenTarget &Target = CDP.getTargetInfo();
 



More information about the llvm-commits mailing list