[llvm] Allow DWARF expressions to refer to variable values (PR #181028)

Tom Tromey via llvm-commits llvm-commits at lists.llvm.org
Thu Mar 5 08:45:09 PST 2026


https://github.com/tromey updated https://github.com/llvm/llvm-project/pull/181028

>From 97908f2e332d139fd2a01e85b13ebf87236bb573 Mon Sep 17 00:00:00 2001
From: Tom Tromey <tromey at adacore.com>
Date: Tue, 4 Nov 2025 10:01:28 -0700
Subject: [PATCH] Allow DWARF expressions to refer to variable values

In Ada, it is possible for a type to refer to the value of local
variables.  In many cases this can be described in the DWARF using
existing LLVM constructs.  However, in some cases, a DWARF expression
that uses multiple variables can be required.

This patch adds a mechanism to allow this.  It adds a new
DIVariableExpression class.  This class holds a DIExpression and a
list of variables.  When DWARF is emitted, each DW_OP_LLVM_arg in the
expression is changed to a DW_OP_GNU_variable_value referencing the
variable's DIE.

DW_OP_GNU_variable_value has been in use in GCC for years.  This has
also been proposed for DWARF 6, though unfortunately it seems to have
stalled:

    http://dwarfstd.org/ShowIssue.php?issue=161109.2

At present this feature is only supported for member offsets and
sizes, and the size of a DICompositeType.  These are just the spots
that I know are needed by gnat-llvm.
---
 llvm/docs/LangRef.rst                         | 14 ++++++
 llvm/include/llvm-c/DebugInfo.h               |  1 +
 llvm/include/llvm/BinaryFormat/Dwarf.def      |  4 ++
 llvm/include/llvm/Bitcode/LLVMBitCodes.h      |  1 +
 llvm/include/llvm/IR/DIBuilder.h              |  9 ++++
 llvm/include/llvm/IR/DebugInfoMetadata.h      | 48 +++++++++++++++++++
 llvm/include/llvm/IR/Metadata.def             |  1 +
 llvm/lib/AsmParser/LLParser.cpp               | 13 +++++
 llvm/lib/Bitcode/Reader/MetadataLoader.cpp    | 13 +++++
 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp     | 14 ++++++
 llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp    |  4 ++
 .../CodeGen/AsmPrinter/DwarfExpression.cpp    |  5 ++
 llvm/lib/CodeGen/AsmPrinter/DwarfExpression.h |  9 ++++
 llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp     | 41 ++++++++++++++++
 llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h       |  5 ++
 .../DWARF/LowLevel/DWARFExpression.cpp        |  1 +
 llvm/lib/IR/AsmWriter.cpp                     | 10 ++++
 llvm/lib/IR/DIBuilder.cpp                     |  8 ++++
 llvm/lib/IR/DebugInfoMetadata.cpp             | 10 ++++
 llvm/lib/IR/LLVMContextImpl.h                 | 16 +++++++
 llvm/lib/IR/Verifier.cpp                      | 22 +++++++--
 llvm/test/DebugInfo/variable-expression.ll    | 46 ++++++++++++++++++
 22 files changed, 291 insertions(+), 4 deletions(-)
 create mode 100644 llvm/test/DebugInfo/variable-expression.ll

diff --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index 28edd439b6900..f032b048b58af 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -6980,6 +6980,20 @@ Some examples of expressions:
     !DIExpression(DW_OP_constu, 2, DW_OP_swap, DW_OP_xderef)
     !DIExpression(DW_OP_constu, 42, DW_OP_stack_value)
 
+DIVariableExpression
+""""""""""""""""""""
+
+``DIVariableExpression`` holds a ``DIExpression`` and a list of
+references to other variables.  When DWARF is emitted for this sort of
+object, each instance of ``DW_OP_LLVM_arg`` in the expression is
+replaced with the DWARF extension operator
+``DW_OP_GNU_variable_value``.
+
+A ``DIVariableExpression`` is useful when a type depends on a
+variable's value.  Currently it can be used as the bit size or bit
+offset of a member of a type, or the bit size of a
+``DICompositeType``.
+
 DIAssignID
 """"""""""
 
diff --git a/llvm/include/llvm-c/DebugInfo.h b/llvm/include/llvm-c/DebugInfo.h
index 70da3a61a46d8..6fbc6d9e73d79 100644
--- a/llvm/include/llvm-c/DebugInfo.h
+++ b/llvm/include/llvm-c/DebugInfo.h
@@ -200,6 +200,7 @@ enum {
   LLVMDIAssignIDMetadataKind,
   LLVMDISubrangeTypeMetadataKind,
   LLVMDIFixedPointTypeMetadataKind,
+  LLVMDIVariableExpressionMetadataKind,
 };
 typedef unsigned LLVMMetadataKind;
 
diff --git a/llvm/include/llvm/BinaryFormat/Dwarf.def b/llvm/include/llvm/BinaryFormat/Dwarf.def
index fbf22cc6f760b..529d35a2c5d91 100644
--- a/llvm/include/llvm/BinaryFormat/Dwarf.def
+++ b/llvm/include/llvm/BinaryFormat/Dwarf.def
@@ -926,6 +926,10 @@ HANDLE_DW_OP(0xf8, PGI_omp_thread_num, -1, -1, 0, PGI)
 HANDLE_DW_OP(0xfb, GNU_addr_index, 1, 0, 0, GNU)
 HANDLE_DW_OP(0xfc, GNU_const_index, 1, 0, 0, GNU)
 
+// Allow an expression to use the value of a variable.
+// http://dwarfstd.org/ShowIssue.php?issue=161109.2
+HANDLE_DW_OP (0xfd, GNU_variable_value, 1, 0, 0, GNU)
+
 // DW_OP_LLVM_user has two operands:
 //   (1) An unsigned LEB128 "LLVM Vendor Extension Opcode".
 //   (2) Zero or more literal operands, the number and type of which are
diff --git a/llvm/include/llvm/Bitcode/LLVMBitCodes.h b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
index 811116a3e1756..aa8cfa81a0e2f 100644
--- a/llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -393,6 +393,7 @@ enum MetadataCodes {
   METADATA_ASSIGN_ID = 47,        // [distinct, ...]
   METADATA_SUBRANGE_TYPE = 48,    // [distinct, ...]
   METADATA_FIXED_POINT_TYPE = 49, // [distinct, ...]
+  METADATA_VARIABLE_EXPR = 50,    // [distinct, ...]
 };
 
 // The constants block (CONSTANTS_BLOCK_ID) describes emission for each
diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index 9753c363166d9..1c027c9b9ad85 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -942,6 +942,15 @@ namespace llvm {
           VMContext, {dwarf::DW_OP_constu, Val, dwarf::DW_OP_stack_value});
     }
 
+    /// Create an expression that involves the value of one or more
+    /// variables.  Each instance of DW_OP_LLVM_arg in \c Expr is
+    /// replaced with the appropriate variable from \c Vars.
+    /// \param Expr        The expression.
+    /// \param Vars        The variables to substitute.
+    DIVariableExpression *
+    createExpressionWithVariables(ArrayRef<uint64_t> Expr,
+                                  ArrayRef<Metadata *> Vars);
+
     /// Create a new descriptor for the specified subprogram.
     /// See comments in DISubprogram* for descriptions of these fields.
     /// \param Scope         Function scope.
diff --git a/llvm/include/llvm/IR/DebugInfoMetadata.h b/llvm/include/llvm/IR/DebugInfoMetadata.h
index 3ce899db66217..b3f4be56a3bd5 100644
--- a/llvm/include/llvm/IR/DebugInfoMetadata.h
+++ b/llvm/include/llvm/IR/DebugInfoMetadata.h
@@ -4681,6 +4681,54 @@ class DIArgList : public Metadata, ReplaceableMetadataImpl {
   LLVM_ABI void handleChangedOperand(void *Ref, Metadata *New);
 };
 
+/// This holds a DIExpression and a list of variables that are
+/// referenced by that expression.
+class DIVariableExpression : public MDNode {
+  friend class LLVMContextImpl;
+  friend class MDNode;
+
+  DIVariableExpression(LLVMContext &C, StorageType Storage,
+                       ArrayRef<Metadata *> Ops)
+      : MDNode(C, DIVariableExpressionKind, Storage, Ops) {}
+
+  static DIVariableExpression *getImpl(LLVMContext &Context, DIExpression *Expr,
+                                       DINodeArray VarArray,
+                                       StorageType Storage,
+                                       bool ShouldCreate = true) {
+    return getImpl(Context, static_cast<Metadata *>(Expr), VarArray.get(),
+                   Storage, ShouldCreate);
+  }
+  static DIVariableExpression *getImpl(LLVMContext &Context, Metadata *Expr,
+                                       Metadata *VarArray, StorageType Storage,
+                                       bool ShouldCreate = true);
+
+  TempDIVariableExpression cloneImpl() const {
+    return getTemporary(getContext(), getExpression(), getVariableArray());
+  }
+
+public:
+  DEFINE_MDNODE_GET(DIVariableExpression,
+                    (DIExpression * Expr, DINodeArray Vars), (Expr, Vars))
+  DEFINE_MDNODE_GET(DIVariableExpression, (Metadata * Expr, Metadata *Vars),
+                    (Expr, Vars))
+
+  DIExpression *getExpression() const {
+    return cast<DIExpression>(getRawExpression());
+  }
+
+  Metadata *getRawExpression() const { return getOperand(0); }
+
+  DINodeArray getVariableArray() const {
+    return cast_or_null<MDTuple>(getRawVariableArray());
+  }
+
+  Metadata *getRawVariableArray() const { return getOperand(1); }
+
+  static bool classof(const Metadata *MD) {
+    return MD->getMetadataID() == DIVariableExpressionKind;
+  }
+};
+
 /// Identifies a unique instance of a variable.
 ///
 /// Storage for identifying a potentially inlined instance of a variable,
diff --git a/llvm/include/llvm/IR/Metadata.def b/llvm/include/llvm/IR/Metadata.def
index 511bf48707f00..7417514c34134 100644
--- a/llvm/include/llvm/IR/Metadata.def
+++ b/llvm/include/llvm/IR/Metadata.def
@@ -120,6 +120,7 @@ HANDLE_SPECIALIZED_MDNODE_LEAF_UNIQUABLE(DIStringType)
 HANDLE_SPECIALIZED_MDNODE_LEAF_UNIQUABLE(DIGenericSubrange)
 HANDLE_SPECIALIZED_MDNODE_LEAF_UNIQUABLE(DISubrangeType)
 HANDLE_SPECIALIZED_MDNODE_LEAF_UNIQUABLE(DIFixedPointType)
+HANDLE_SPECIALIZED_MDNODE_LEAF_UNIQUABLE(DIVariableExpression)
 
 #undef HANDLE_METADATA
 #undef HANDLE_METADATA_LEAF
diff --git a/llvm/lib/AsmParser/LLParser.cpp b/llvm/lib/AsmParser/LLParser.cpp
index 5b916711690ec..dba2d5d02dc83 100644
--- a/llvm/lib/AsmParser/LLParser.cpp
+++ b/llvm/lib/AsmParser/LLParser.cpp
@@ -6477,6 +6477,19 @@ bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
   return false;
 }
 
+/// parseDIVariableExpression:
+///   ::= !DIVariableExpression(expr: !0, vars: !1)
+bool LLParser::parseDIVariableExpression(MDNode *&Result, bool IsDistinct) {
+#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
+  REQUIRED(expr, MDField, );                                                   \
+  REQUIRED(vars, MDField, );
+  PARSE_MD_FIELDS();
+#undef VISIT_MD_FIELDS
+
+  Result = GET_OR_DISTINCT(DIVariableExpression, (Context, expr.Val, vars.Val));
+  return false;
+}
+
 /// parseDIGlobalVariableExpression:
 ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
diff --git a/llvm/lib/Bitcode/Reader/MetadataLoader.cpp b/llvm/lib/Bitcode/Reader/MetadataLoader.cpp
index 4bc55232a6df6..3174b4a043abf 100644
--- a/llvm/lib/Bitcode/Reader/MetadataLoader.cpp
+++ b/llvm/lib/Bitcode/Reader/MetadataLoader.cpp
@@ -2367,6 +2367,19 @@ Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
     NextMetadataNo++;
     break;
   }
+  case bitc::METADATA_VARIABLE_EXPR: {
+    if (Record.size() != 3)
+      return error("Invalid record");
+
+    IsDistinct = Record[0];
+    Metadata *Expr = getMDOrNull(Record[1]);
+    Metadata *Vars = getMDOrNull(Record[2]);
+    MetadataList.assignValue(
+        GET_OR_DISTINCT(DIVariableExpression, (Context, Expr, Vars)),
+        NextMetadataNo);
+    NextMetadataNo++;
+    break;
+  }
   case bitc::METADATA_GLOBAL_VAR_EXPR: {
     if (Record.size() != 3)
       return error("Invalid record");
diff --git a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
index 2566b2a292300..11564c9d18c49 100644
--- a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -401,6 +401,9 @@ class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
                     SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
   void writeDIExpression(const DIExpression *N,
                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
+  void writeDIVariableExpression(const DIVariableExpression *N,
+                                 SmallVectorImpl<uint64_t> &Record,
+                                 unsigned Abbrev);
   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
                                        SmallVectorImpl<uint64_t> &Record,
                                        unsigned Abbrev);
@@ -2389,6 +2392,17 @@ void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
   Record.clear();
 }
 
+void ModuleBitcodeWriter::writeDIVariableExpression(
+    const DIVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
+    unsigned Abbrev) {
+  Record.push_back(N->isDistinct());
+  Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
+  Record.push_back(VE.getMetadataOrNullID(N->getVariableArray().get()));
+
+  Stream.EmitRecord(bitc::METADATA_VARIABLE_EXPR, Record, Abbrev);
+  Record.clear();
+}
+
 void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
     unsigned Abbrev) {
diff --git a/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp b/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
index f8c2c753b91ce..2ab2cbb535f34 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
@@ -199,6 +199,10 @@ void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
   getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
 }
 
+void DebugLocDwarfExpression::emitDIERef(DIE &Ref) {
+  getActiveStreamer().emitDIERef(Ref);
+}
+
 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
                                               llvm::Register MachineReg) {
   // This information is not available while emitting .debug_loc entries.
diff --git a/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.cpp b/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.cpp
index d6b06b83207c7..cfc3c1eb46ad4 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.cpp
@@ -40,6 +40,11 @@ void DwarfExpression::emitConstu(uint64_t Value) {
   }
 }
 
+void DwarfExpression::addVariableReference(DIE &Ref) {
+  emitOp(llvm::dwarf::DW_OP_GNU_variable_value);
+  emitDIERef(Ref);
+}
+
 void DwarfExpression::addReg(int64_t DwarfReg, const char *Comment) {
   assert(DwarfReg >= 0 && "invalid negative dwarf register number");
   assert((isUnknownLocation() || isRegisterLocation()) &&
diff --git a/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.h b/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.h
index c4929aed1c197..4de24343358fe 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.h
+++ b/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.h
@@ -134,6 +134,9 @@ class DwarfExpression {
 
   virtual void emitBaseTypeRef(uint64_t Idx) = 0;
 
+  /// Emit a reference to the given DIE.
+  virtual void emitDIERef(DIE &Ref) = 0;
+
   /// Start emitting data to the temporary buffer. The data stored in the
   /// temporary buffer can be committed to the main output using
   /// commitTemporaryBuffer().
@@ -270,6 +273,10 @@ class DwarfExpression {
                                llvm::Register MachineReg,
                                unsigned FragmentOffsetInBits = 0);
 
+  /// Add a reference to the variable indicated by the given DIE.  A
+  /// DW_OP_GNU_variable_value operation is emitted first.
+  void addVariableReference(DIE &);
+
   /// Begin emission of an entry value dwarf operation. The entry value's
   /// first operand is the size of the DWARF block (its second operand),
   /// which needs to be calculated at time of emission, so we don't emit
@@ -327,6 +334,7 @@ class DebugLocDwarfExpression final : public DwarfExpression {
   void emitUnsigned(uint64_t Value) override;
   void emitData1(uint8_t Value) override;
   void emitBaseTypeRef(uint64_t Idx) override;
+  void emitDIERef(DIE &Ref) override;
 
   void enableTemporaryBuffer() override;
   void disableTemporaryBuffer() override;
@@ -357,6 +365,7 @@ class DIEDwarfExpression final : public DwarfExpression {
   void emitUnsigned(uint64_t Value) override;
   void emitData1(uint8_t Value) override;
   void emitBaseTypeRef(uint64_t Idx) override;
+  void emitDIERef(DIE &Ref) override;
 
   void enableTemporaryBuffer() override;
   void disableTemporaryBuffer() override;
diff --git a/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp b/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
index baffd81b4f336..198c02afd61e6 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
@@ -61,6 +61,10 @@ void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
   CU.addBaseTypeRef(getActiveDIE(), Idx);
 }
 
+void DIEDwarfExpression::emitDIERef(DIE &Ref) {
+  CU.addDIEEntry(getActiveDIE(), dwarf::DW_FORM_ref_addr, Ref);
+}
+
 void DIEDwarfExpression::enableTemporaryBuffer() {
   assert(!IsBuffering && "Already buffering?");
   IsBuffering = true;
@@ -389,6 +393,10 @@ void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
   addDIEEntry(Die, Attribute, DIEEntry(Entry));
 }
 
+void DwarfUnit::addDIEEntry(DIEValueList &Die, dwarf::Form Form, DIE &Entry) {
+  addAttribute(Die, (dwarf::Attribute)0, Form, DIEEntry(Entry));
+}
+
 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
   // Flag the type unit reference as a declaration so that if it contains
   // members (implicit special members, static data member definitions, member
@@ -450,6 +458,30 @@ void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
   addBlock(Die, Attribute, DwarfExpr.finalize());
 }
 
+void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
+                         const DIVariableExpression *Expr) {
+  // Emitting a DIVariableExpression normally involves an extension
+  // operator, so just drop this in strict mode.
+  // See http://dwarfstd.org/ShowIssue.php?issue=161109.2.
+  if (Asm->TM.Options.DebugStrictDwarf)
+    return;
+
+  DIELoc *Loc = new (DIEValueAllocator) DIELoc;
+  DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
+  DwarfExpr.setMemoryLocationKind();
+  DINodeArray Vars = Expr->getVariableArray();
+  DwarfExpr.addExpression(
+      Expr->getExpression(),
+      [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
+        if (auto *VarDie = getDIE(Vars[Idx])) {
+          DwarfExpr.addVariableReference(*VarDie);
+          return true;
+        }
+        return false;
+      });
+  addBlock(Die, Attribute, DwarfExpr.finalize());
+}
+
 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, unsigned Column,
                               const DIFile *File) {
   if (Line == 0)
@@ -1208,6 +1240,9 @@ void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
     } else if (auto *Exp =
                    dyn_cast_or_null<DIExpression>(CTy->getRawSizeInBits())) {
       addBlock(Buffer, dwarf::DW_AT_bit_size, Exp);
+    } else if (auto *VarExp = dyn_cast_or_null<DIVariableExpression>(
+                   CTy->getRawSizeInBits())) {
+      addBlock(Buffer, dwarf::DW_AT_bit_size, VarExp);
     } else {
       uint64_t Size = CTy->getSizeInBits() >> 3;
       // Add size if non-zero (derived types might be zero-sized.)
@@ -1890,6 +1925,9 @@ DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
         addDIEEntry(MemberDie, dwarf::DW_AT_bit_size, *VarDIE);
     } else if (auto *Exp = dyn_cast<DIExpression>(DT->getRawSizeInBits())) {
       addBlock(MemberDie, dwarf::DW_AT_bit_size, Exp);
+    } else if (auto *VarExp = dyn_cast_or_null<DIVariableExpression>(
+                   DT->getRawSizeInBits())) {
+      addBlock(MemberDie, dwarf::DW_AT_bit_size, VarExp);
     } else {
       Size = DT->getSizeInBits();
       FieldSize = DD->getBaseTypeSize(DT);
@@ -1915,6 +1953,9 @@ DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
       if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 6) {
         addBlock(MemberDie, dwarf::DW_AT_data_bit_offset, Expr);
       }
+    } else if (auto *VarExp = dyn_cast_or_null<DIVariableExpression>(
+                   DT->getRawOffsetInBits())) {
+      addBlock(MemberDie, dwarf::DW_AT_data_bit_offset, VarExp);
     } else {
       uint32_t AlignInBytes = DT->getAlignInBytes();
       uint64_t OffsetInBytes;
diff --git a/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h b/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h
index 22eef85a1dffa..115cb960e0b90 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h
+++ b/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h
@@ -205,6 +205,9 @@ class DwarfUnit : public DIEUnit {
   /// Add a DIE attribute data and value.
   void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIEEntry Entry);
 
+  /// Add a reference to Entry using the indicated form.
+  void addDIEEntry(DIEValueList &Die, dwarf::Form Form, DIE &Entry);
+
   /// Add a type's DW_AT_signature and set the  declaration flag.
   void addDIETypeSignature(DIE &Die, uint64_t Signature);
 
@@ -218,6 +221,8 @@ class DwarfUnit : public DIEUnit {
 
   /// Add an expression as block data.
   void addBlock(DIE &Die, dwarf::Attribute Attribute, const DIExpression *Expr);
+  void addBlock(DIE &Die, dwarf::Attribute Attribute,
+                const DIVariableExpression *Expr);
 
   /// Add location information to specified debug information entry.
   void addSourceLine(DIE &Die, unsigned Line, unsigned Column,
diff --git a/llvm/lib/DebugInfo/DWARF/LowLevel/DWARFExpression.cpp b/llvm/lib/DebugInfo/DWARF/LowLevel/DWARFExpression.cpp
index 61bd6fcb65bfa..f154d0126b3c8 100644
--- a/llvm/lib/DebugInfo/DWARF/LowLevel/DWARFExpression.cpp
+++ b/llvm/lib/DebugInfo/DWARF/LowLevel/DWARFExpression.cpp
@@ -101,6 +101,7 @@ static std::vector<Desc> getOpDescriptions() {
   Descriptions[DW_OP_GNU_addr_index] = Desc(Op::Dwarf4, Op::SizeLEB);
   Descriptions[DW_OP_GNU_const_index] = Desc(Op::Dwarf4, Op::SizeLEB);
   Descriptions[DW_OP_GNU_entry_value] = Desc(Op::Dwarf4, Op::SizeLEB);
+  Descriptions[DW_OP_GNU_variable_value] = Desc(Op::Dwarf4, Op::SizeRefAddr);
   Descriptions[DW_OP_GNU_implicit_pointer] =
       Desc(Op::Dwarf4, Op::SizeRefAddr, Op::SignedSizeLEB);
   // This Description acts as a marker that getSubOpDesc must be called
diff --git a/llvm/lib/IR/AsmWriter.cpp b/llvm/lib/IR/AsmWriter.cpp
index b3e0323fd8633..565979cfc2f3d 100644
--- a/llvm/lib/IR/AsmWriter.cpp
+++ b/llvm/lib/IR/AsmWriter.cpp
@@ -2645,6 +2645,16 @@ static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
   Out << ")";
 }
 
+static void writeDIVariableExpression(raw_ostream &Out,
+                                      const DIVariableExpression *N,
+                                      AsmWriterContext &WriterCtx) {
+  Out << "!DIVariableExpression(";
+  MDFieldPrinter Printer(Out, WriterCtx);
+  Printer.printMetadata("expr", N->getRawExpression());
+  Printer.printMetadata("vars", N->getRawVariableArray());
+  Out << ")";
+}
+
 static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
                            AsmWriterContext &WriterCtx,
                            bool FromValue = false) {
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 38cf3f552b83d..327f794964618 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -918,6 +918,14 @@ static void checkGlobalVariableScope(DIScope *Context) {
 #endif
 }
 
+DIVariableExpression *
+DIBuilder::createExpressionWithVariables(ArrayRef<uint64_t> Expr,
+                                         ArrayRef<Metadata *> Vars) {
+  DIExpression *EX = DIExpression::get(VMContext, Expr);
+  DINodeArray Ary = MDNode::get(VMContext, Vars);
+  return DIVariableExpression::get(VMContext, EX, Ary);
+}
+
 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
     unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, bool isDefined,
diff --git a/llvm/lib/IR/DebugInfoMetadata.cpp b/llvm/lib/IR/DebugInfoMetadata.cpp
index 5db2c86aafc3d..c84a81fedec08 100644
--- a/llvm/lib/IR/DebugInfoMetadata.cpp
+++ b/llvm/lib/IR/DebugInfoMetadata.cpp
@@ -2604,6 +2604,16 @@ DIExpression *DIExpression::appendExt(const DIExpression *Expr,
   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
 }
 
+DIVariableExpression *DIVariableExpression::getImpl(LLVMContext &Context,
+                                                    Metadata *Expr,
+                                                    Metadata *VarArray,
+                                                    StorageType Storage,
+                                                    bool ShouldCreate) {
+  DEFINE_GETIMPL_LOOKUP(DIVariableExpression, (Expr, VarArray));
+  Metadata *Ops[] = {Expr, VarArray};
+  DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIVariableExpression, Ops);
+}
+
 DIGlobalVariableExpression *
 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
                                     Metadata *Expression, StorageType Storage,
diff --git a/llvm/lib/IR/LLVMContextImpl.h b/llvm/lib/IR/LLVMContextImpl.h
index 2c9921df0422e..3addc68ae4faa 100644
--- a/llvm/lib/IR/LLVMContextImpl.h
+++ b/llvm/lib/IR/LLVMContextImpl.h
@@ -1363,6 +1363,22 @@ template <> struct MDNodeKeyImpl<DIExpression> {
   unsigned getHashValue() const { return hash_combine_range(Elements); }
 };
 
+template <> struct MDNodeKeyImpl<DIVariableExpression> {
+  Metadata *Expr;
+  Metadata *Vars;
+
+  MDNodeKeyImpl(Metadata *Expr, Metadata *Vars) : Expr(Expr), Vars(Vars) {}
+  MDNodeKeyImpl(const DIVariableExpression *N)
+      : Expr(N->getRawExpression()), Vars(N->getRawVariableArray()) {}
+
+  bool isKeyOf(const DIVariableExpression *RHS) const {
+    return Expr == RHS->getRawExpression() &&
+           Vars == RHS->getRawVariableArray();
+  }
+
+  unsigned getHashValue() const { return hash_combine(Expr, Vars); }
+};
+
 template <> struct MDNodeKeyImpl<DIGlobalVariableExpression> {
   Metadata *Variable;
   Metadata *Expression;
diff --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp
index f986f5406b2b3..ae9e2cb3de831 100644
--- a/llvm/lib/IR/Verifier.cpp
+++ b/llvm/lib/IR/Verifier.cpp
@@ -1422,8 +1422,9 @@ void Verifier::visitDIDerivedType(const DIDerivedType &N) {
 
   auto *Size = N.getRawSizeInBits();
   CheckDI(!Size || isa<ConstantAsMetadata>(Size) || isa<DIVariable>(Size) ||
-              isa<DIExpression>(Size),
-          "SizeInBits must be a constant or DIVariable or DIExpression");
+              isa<DIExpression>(Size) || isa<DIVariableExpression>(Size),
+          "SizeInBits must be a constant or DIVariable or DIExpression or "
+          "DIVariableExpression");
 }
 
 /// Detect mutually exclusive flags.
@@ -1514,8 +1515,9 @@ void Verifier::visitDICompositeType(const DICompositeType &N) {
 
   auto *Size = N.getRawSizeInBits();
   CheckDI(!Size || isa<ConstantAsMetadata>(Size) || isa<DIVariable>(Size) ||
-              isa<DIExpression>(Size),
-          "SizeInBits must be a constant or DIVariable or DIExpression");
+              isa<DIExpression>(Size) || isa<DIVariableExpression>(Size),
+          "SizeInBits must be a constant or DIVariable or DIExpression or "
+          "DIVariableExpression");
 }
 
 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
@@ -1843,6 +1845,18 @@ void Verifier::visitDIGlobalVariableExpression(
   }
 }
 
+void Verifier::visitDIVariableExpression(const DIVariableExpression &N) {
+  CheckDI(N.getExpression(), "missing expression");
+  if (auto *Expr = N.getExpression())
+    visitDIExpression(*Expr);
+  if (auto *Vars = N.getRawVariableArray()) {
+    CheckDI(isa<MDTuple>(Vars), "invalid composite elements", &N, Vars);
+    for (Metadata *V : N.getVariableArray()->operands()) {
+      CheckDI(isa<DIVariable>(V), "invalid variable", &N);
+    }
+  }
+}
+
 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
   CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
   if (auto *T = N.getRawType())
diff --git a/llvm/test/DebugInfo/variable-expression.ll b/llvm/test/DebugInfo/variable-expression.ll
new file mode 100644
index 0000000000000..1a8f86c856adc
--- /dev/null
+++ b/llvm/test/DebugInfo/variable-expression.ll
@@ -0,0 +1,46 @@
+; RUN: llvm-as < %s | llvm-dis | llc -mtriple=x86_64 -O0 -filetype=obj -o - | llvm-dwarfdump -v -debug-info - | FileCheck %s
+
+; A test to verify that DIVariableExpression emits
+; DW_OP_GNU_variable_value.
+
+; CHECK: DW_TAG_structure_type
+; CHECK-NEXT: DW_AT_name [DW_FORM_strp] {{.*"pck__my_rec".*}}
+; CHECK-NEXT: DW_AT_bit_size {{.*DW_OP_GNU_variable_value}}
+
+; ModuleID = 'foo.adb'
+source_filename = "foo.adb"
+
+ at pck__my_length_LAST = external dso_local global i32, align 4
+
+!llvm.module.flags = !{!0, !1}
+!llvm.dbg.cu = !{!2}
+
+!0 = !{i32 2, !"Debug Info Version", i32 3}
+!1 = !{i32 2, !"Dwarf Version", i32 4}
+!2 = distinct !DICompileUnit(language: DW_LANG_Ada95, file: !3, producer: "GNAT/LLVM", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, globals: !4, imports: !9, splitDebugInlining: false, retainedTypes: !17)
+!3 = !DIFile(filename: "foo.adb", directory: "")
+!4 = !{!5}
+!5 = !DIGlobalVariableExpression(var: !6, expr: !DIExpression())
+!6 = distinct !DIGlobalVariable(name: "pck__my_length_LAST", scope: !2, file: !7, line: 23, type: !8, isLocal: false, isDefinition: false, align: 32)
+!7 = !DIFile(filename: "pck.ads", directory: "")
+!8 = !DIBasicType(name: "integer", size: 32, encoding: DW_ATE_signed)
+!9 = !{!10}
+!10 = !DIImportedEntity(tag: DW_TAG_imported_module, scope: !2, entity: !11, file: !3, line: 16)
+!11 = !DIModule(scope: null, name: "pck")
+!12 = distinct !DISubprogram(name: "foo", scope: !3, file: !3, line: 18, type: !13, scopeLine: 18, spFlags: DISPFlagDefinition, unit: !2, retainedNodes: !15)
+!13 = !DISubroutineType(types: !14)
+!14 = !{null}
+!15 = !{}
+!16 = !DILocation(line: 19, column: 4, scope: !12)
+!17 = !{!18}
+!18 = !DICompositeType(tag: DW_TAG_structure_type, name: "pck__my_rec", file: !7, line: 26, size: !19, align: 32, elements: !21, identifier: "pck__my_rec")
+!19 = !DIVariableExpression(expr: !DIExpression(DW_OP_LLVM_arg, 0, DW_OP_constu, 0, DW_OP_over, DW_OP_swap, DW_OP_over, DW_OP_over, DW_OP_lt, DW_OP_neg, DW_OP_rot, DW_OP_xor, DW_OP_and, DW_OP_xor, DW_OP_constu, 32, DW_OP_mul, DW_OP_constu, 32, DW_OP_plus), vars: !20)
+!20 = !{!6}
+!21 = !{!22, !23}
+!22 = !DIDerivedType(tag: DW_TAG_member, name: "x", file: !7, line: 27, baseType: !8, size: 32, align: 32)
+!23 = !DIDerivedType(tag: DW_TAG_member, name: "a", file: !7, line: 28, baseType: !24, offset: 32)
+!24 = !DICompositeType(tag: DW_TAG_array_type, name: "pck__my_array", file: !7, line: 24, baseType: !25, align: 32, elements: !27)
+!25 = !DISubrangeType(name: "natural", file: !26, line: 1, size: 32, align: 32, baseType: !8, lowerBound: i64 0, upperBound: i64 2147483647)
+!26 = !DIFile(filename: "system.ads", directory: "")
+!27 = !{!28}
+!28 = !DISubrangeType(baseType: !8, lowerBound: i64 1, upperBound: !6)



More information about the llvm-commits mailing list