[clang] [llvm] Reapply "[RISCV][clang] Support XSfmm ABI attributes (#206260)" (PR #241642)

Brandon Wu via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 11 19:09:24 PST 2026


https://github.com/4vtomat updated https://github.com/llvm/llvm-project/pull/241642

>From 91da6b52d6cbfb306e31549534a172a7ac17d005 Mon Sep 17 00:00:00 2001
From: Brandon Wu <brandon.wu at sifive.com>
Date: Tue, 10 Nov 2026 22:23:59 -0800
Subject: [PATCH 1/4] Reapply "[RISCV][clang] Support XSfmm ABI attributes
 (#206260)"

This reverts commit b9c191f30c6a478c35f654764c90fafeed346f0f.
---
 clang/include/clang/AST/TypeBase.h            | 105 ++++++++++++-
 clang/include/clang/AST/TypeProperties.td     |   4 +
 clang/include/clang/Basic/Attr.td             |  35 +++++
 clang/include/clang/Basic/AttrDocs.td         |  67 ++++++++
 .../clang/Basic/DiagnosticSemaKinds.td        |   9 ++
 clang/include/clang/Sema/SemaRISCV.h          |   6 +
 clang/lib/AST/ASTContext.cpp                  |   6 +-
 clang/lib/AST/Type.cpp                        |  18 +++
 clang/lib/AST/TypePrinter.cpp                 |   5 +
 clang/lib/CodeGen/CGCall.cpp                  |  21 +++
 clang/lib/Sema/SemaChecking.cpp               |   4 +
 clang/lib/Sema/SemaRISCV.cpp                  | 105 +++++++++++++
 clang/lib/Sema/SemaType.cpp                   | 102 ++++++++++++
 clang/test/PCH/riscv-function-attributes.cpp  |  13 ++
 clang/test/Sema/sifive-xsfmm-func-attr.c      | 146 ++++++++++++++++++
 .../Target/RISCV/GISel/RISCVCallLowering.cpp  |   6 +
 llvm/lib/Target/RISCV/RISCV.h                 |   1 +
 llvm/lib/Target/RISCV/RISCVCallingConv.cpp    |  21 +++
 llvm/lib/Target/RISCV/RISCVCallingConv.h      |   4 +
 llvm/lib/Target/RISCV/RISCVISelLowering.cpp   |   5 +
 llvm/lib/Target/RISCV/RISCVInstrInfo.cpp      |   1 +
 llvm/lib/Target/RISCV/RISCVStateAttributes.h  |  29 ++++
 .../Target/RISCV/RISCVTargetTransformInfo.cpp |  12 ++
 .../Target/RISCV/RISCVTargetTransformInfo.h   |   3 +
 llvm/test/CodeGen/RISCV/riscv-state-check.ll  |  32 ++++
 25 files changed, 751 insertions(+), 9 deletions(-)
 create mode 100644 clang/test/PCH/riscv-function-attributes.cpp
 create mode 100644 clang/test/Sema/sifive-xsfmm-func-attr.c
 create mode 100644 llvm/lib/Target/RISCV/RISCVStateAttributes.h
 create mode 100644 llvm/test/CodeGen/RISCV/riscv-state-check.ll

diff --git a/clang/include/clang/AST/TypeBase.h b/clang/include/clang/AST/TypeBase.h
index 56e31f25c26d6d..35b427318f0dce 100644
--- a/clang/include/clang/AST/TypeBase.h
+++ b/clang/include/clang/AST/TypeBase.h
@@ -4993,14 +4993,17 @@ class FunctionType : public Type {
     LLVM_PREFERRED_TYPE(bool)
     unsigned HasArmTypeAttributes : 1;
 
+    LLVM_PREFERRED_TYPE(bool)
+    unsigned HasRISCVTypeAttributes : 1;
+
     LLVM_PREFERRED_TYPE(bool)
     unsigned EffectsHaveConditions : 1;
     unsigned NumFunctionEffects : 4;
 
     FunctionTypeExtraBitfields()
         : NumExceptionType(0), HasExtraAttributeInfo(false),
-          HasArmTypeAttributes(false), EffectsHaveConditions(false),
-          NumFunctionEffects(0) {}
+          HasArmTypeAttributes(false), HasRISCVTypeAttributes(false),
+          EffectsHaveConditions(false), NumFunctionEffects(0) {}
   };
 
   /// A holder for extra information from attributes which aren't part of an
@@ -5046,6 +5049,46 @@ class FunctionType : public Type {
     ARM_InOut = 4,
   };
 
+  /// RISC-V type attributes for states.
+  enum RISCVTypeAttributes : unsigned {
+    RISCVNormalFunction = 0,
+
+    // Describes the value of the xsfmm tile state using RISCVStateValue.
+    // Each tile gets 3 bits to store its state.
+    RISCVXsfmmShift = 0,
+    RISCVXsfmmMask = 0b111 << RISCVXsfmmShift,
+
+    // Currently using 3 bits for xsfmm
+    RISCVAttributeMask = 0b111
+  };
+
+  enum RISCVStateValue : unsigned {
+    RISCVNone = 0,
+    RISCVIn = 1,
+    RISCVOut = 2,
+    RISCVInOut = 3,
+    RISCVPreserves = 4,
+    RISCVNew = 5,
+  };
+
+  static const char *ToRISCVStateString(RISCVStateValue St) {
+    switch (St) {
+    case RISCVNone:
+      return "none";
+    case RISCVIn:
+      return "__riscv_in";
+    case RISCVOut:
+      return "__riscv_out";
+    case RISCVInOut:
+      return "__riscv_inout";
+    case RISCVPreserves:
+      return "__riscv_preserves";
+    case RISCVNew:
+      return "__riscv_new";
+    }
+    llvm_unreachable("Invalid RISC-V state value");
+  }
+
   static ArmStateValue getArmZAState(unsigned AttrBits) {
     return static_cast<ArmStateValue>((AttrBits & SME_ZAMask) >> SME_ZAShift);
   }
@@ -5054,6 +5097,11 @@ class FunctionType : public Type {
     return static_cast<ArmStateValue>((AttrBits & SME_ZT0Mask) >> SME_ZT0Shift);
   }
 
+  static RISCVStateValue getRISCVXsfmmState(unsigned AttrBits) {
+    return static_cast<RISCVStateValue>((AttrBits & RISCVXsfmmMask) >>
+                                        RISCVXsfmmShift);
+  }
+
   /// A holder for Arm type attributes as described in the Arm C/C++
   /// Language extensions which are not particularly common to all
   /// types and therefore accounted separately from FunctionTypeBitfields.
@@ -5066,6 +5114,13 @@ class FunctionType : public Type {
     FunctionTypeArmAttributes() : AArch64SMEAttributes(SME_NormalFunction) {}
   };
 
+  struct alignas(void *) FunctionTypeRISCVAttributes {
+    LLVM_PREFERRED_TYPE(RISCVTypeAttributes)
+    unsigned RISCVAttributes : 3;
+
+    FunctionTypeRISCVAttributes() : RISCVAttributes(RISCVNormalFunction) {}
+  };
+
 protected:
   FunctionType(TypeClass tc, QualType res, QualType Canonical,
                TypeDependence Dependence, ExtInfo Info)
@@ -5543,9 +5598,11 @@ class FunctionProtoType final
           FunctionProtoType, QualType, SourceLocation,
           FunctionType::FunctionTypeExtraBitfields,
           FunctionType::FunctionTypeExtraAttributeInfo,
-          FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
-          Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers,
-          FunctionEffect, EffectConditionExpr> {
+          FunctionType::FunctionTypeArmAttributes,
+          FunctionType::FunctionTypeRISCVAttributes,
+          FunctionType::ExceptionType, Expr *, FunctionDecl *,
+          FunctionType::ExtParameterInfo, Qualifiers, FunctionEffect,
+          EffectConditionExpr> {
   friend class ASTContext; // ASTContext creates these.
   friend TrailingObjects;
 
@@ -5648,14 +5705,18 @@ class FunctionProtoType final
     unsigned CFIUncheckedCallee : 1;
     LLVM_PREFERRED_TYPE(AArch64SMETypeAttributes)
     unsigned AArch64SMEAttributes : 9;
+    LLVM_PREFERRED_TYPE(RISCVTypeAttributes)
+    unsigned RISCVAttributes : 3;
 
     ExtProtoInfo()
         : Variadic(false), HasTrailingReturn(false), CFIUncheckedCallee(false),
-          AArch64SMEAttributes(SME_NormalFunction) {}
+          AArch64SMEAttributes(SME_NormalFunction),
+          RISCVAttributes(RISCVNormalFunction) {}
 
     ExtProtoInfo(CallingConv CC)
         : ExtInfo(CC), Variadic(false), HasTrailingReturn(false),
-          CFIUncheckedCallee(false), AArch64SMEAttributes(SME_NormalFunction) {}
+          CFIUncheckedCallee(false), AArch64SMEAttributes(SME_NormalFunction),
+          RISCVAttributes(RISCVNormalFunction) {}
 
     ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
       ExtProtoInfo Result(*this);
@@ -5672,6 +5733,7 @@ class FunctionProtoType final
     bool requiresFunctionProtoTypeExtraBitfields() const {
       return ExceptionSpec.Type == EST_Dynamic ||
              requiresFunctionProtoTypeArmAttributes() ||
+             requiresFunctionProtoTypeRISCVAttributes() ||
              requiresFunctionProtoTypeExtraAttributeInfo() ||
              !FunctionEffects.empty();
     }
@@ -5690,6 +5752,17 @@ class FunctionProtoType final
       else
         AArch64SMEAttributes &= ~Kind;
     }
+
+    bool requiresFunctionProtoTypeRISCVAttributes() const {
+      return RISCVAttributes != RISCVNormalFunction;
+    }
+
+    void setRISCVAttribute(RISCVTypeAttributes Kind, bool Enable = true) {
+      if (Enable)
+        RISCVAttributes |= Kind;
+      else
+        RISCVAttributes &= ~Kind;
+    }
   };
 
 private:
@@ -5705,6 +5778,11 @@ class FunctionProtoType final
     return hasArmTypeAttributes();
   }
 
+  unsigned
+  numTrailingObjects(OverloadToken<FunctionTypeRISCVAttributes>) const {
+    return hasRISCVTypeAttributes();
+  }
+
   unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
     return hasExtraBitfields();
   }
@@ -5818,6 +5896,12 @@ class FunctionProtoType final
                ->HasArmTypeAttributes;
   }
 
+  bool hasRISCVTypeAttributes() const {
+    return FunctionTypeBits.HasExtraBitfields &&
+           getTrailingObjects<FunctionTypeExtraBitfields>()
+               ->HasRISCVTypeAttributes;
+  }
+
   bool hasExtQualifiers() const {
     return FunctionTypeBits.HasExtQuals;
   }
@@ -5847,6 +5931,7 @@ class FunctionProtoType final
     EPI.ExtParameterInfos = getExtParameterInfosOrNull();
     EPI.ExtraAttributeInfo = getExtraAttributeInfo();
     EPI.AArch64SMEAttributes = getAArch64SMEAttributes();
+    EPI.RISCVAttributes = getRISCVAttributes();
     EPI.FunctionEffects = getFunctionEffects();
     return EPI;
   }
@@ -6049,6 +6134,12 @@ class FunctionProtoType final
         ->AArch64SMEAttributes;
   }
 
+  unsigned getRISCVAttributes() const {
+    if (!hasRISCVTypeAttributes())
+      return RISCVNormalFunction;
+    return getTrailingObjects<FunctionTypeRISCVAttributes>()->RISCVAttributes;
+  }
+
   ExtParameterInfo getExtParameterInfo(unsigned I) const {
     assert(I < getNumParams() && "parameter index out of range");
     if (hasExtParameterInfos())
diff --git a/clang/include/clang/AST/TypeProperties.td b/clang/include/clang/AST/TypeProperties.td
index 1a2a3fda0dcff0..e5b7202d8193a4 100644
--- a/clang/include/clang/AST/TypeProperties.td
+++ b/clang/include/clang/AST/TypeProperties.td
@@ -349,6 +349,9 @@ let Class = FunctionProtoType in {
   def : Property<"AArch64SMEAttributes", UInt32> {
     let Read = [{ node->getAArch64SMEAttributes() }];
   }
+  def : Property<"RISCVAttributes", UInt32> {
+    let Read = [{ node->getRISCVAttributes() }];
+  }
   def : Property<"functionEffects", Array<FunctionEffect>> {
     let Read = [{ node->getFunctionEffectsWithoutConditions() }];
   }
@@ -372,6 +375,7 @@ let Class = FunctionProtoType in {
     epi.ExtParameterInfos =
       extParameterInfo.empty() ? nullptr : extParameterInfo.data();
     epi.AArch64SMEAttributes = AArch64SMEAttributes;
+    epi.RISCVAttributes = RISCVAttributes;
     epi.FunctionEffects = FunctionEffectsRef::create(functionEffects, functionEffectConds);
     return ctx.getFunctionType(returnType, parameters, epi);
   }]>;
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 24fd853a2384af..283b7834206de2 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3694,6 +3694,41 @@ def RISCVVLSCC: DeclOrTypeAttr, TargetSpecificAttr<TargetRISCV> {
  let Documentation = [RISCVVLSCCDocs];
 }
 
+def RISCVIn : TypeAttr, TargetSpecificAttr<TargetRISCV> {
+  let Spellings = [RegularKeyword<"__riscv_in">];
+  let Args = [VariadicStringArgument<"InArgs">];
+  let Subjects = SubjectList<[HasFunctionProto], ErrorDiag>;
+  let Documentation = [RISCVInDocs];
+}
+
+def RISCVOut : TypeAttr, TargetSpecificAttr<TargetRISCV> {
+  let Spellings = [RegularKeyword<"__riscv_out">];
+  let Args = [VariadicStringArgument<"OutArgs">];
+  let Subjects = SubjectList<[HasFunctionProto], ErrorDiag>;
+  let Documentation = [RISCVOutDocs];
+}
+
+def RISCVInOut : TypeAttr, TargetSpecificAttr<TargetRISCV> {
+  let Spellings = [RegularKeyword<"__riscv_inout">];
+  let Args = [VariadicStringArgument<"InOutArgs">];
+  let Subjects = SubjectList<[HasFunctionProto], ErrorDiag>;
+  let Documentation = [RISCVInOutDocs];
+}
+
+def RISCVPreserves : TypeAttr, TargetSpecificAttr<TargetRISCV> {
+  let Spellings = [RegularKeyword<"__riscv_preserves">];
+  let Args = [VariadicStringArgument<"PreserveArgs">];
+  let Subjects = SubjectList<[HasFunctionProto], ErrorDiag>;
+  let Documentation = [RISCVPreservesDocs];
+}
+
+def RISCVNew : TypeAttr, TargetSpecificAttr<TargetRISCV> {
+  let Spellings = [RegularKeyword<"__riscv_new">];
+  let Args = [VariadicStringArgument<"NewArgs">];
+  let Subjects = SubjectList<[HasFunctionProto], ErrorDiag>;
+  let Documentation = [RISCVNewDocs];
+}
+
 def Target : InheritableAttr {
   let Spellings = [GCC<"target">];
   let Args = [StringArgument<"featuresStr">];
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 2300c8456ef164..e1374d45754e31 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6963,6 +6963,73 @@ the ABI. This variant aims to pass fixed-length vectors via vector registers,
 if possible, rather than through general-purpose registers.}];
 }
 
+def RISCVInDocs : Documentation {
+  let Category = DocCatFunction;
+  let Heading = "__riscv_in";
+  let Content = [{
+The ``__riscv_in(S)`` attribute indicates that a function reads from state S.
+This attribute is usually used in RISC-V matrix extensions to specify that the
+function will read from a matrix state passed as arguments.
+This helps compiler checks to prevent common programming errors that could lead
+to undefined behavior, data corruption, or incorrect computation results when
+working with matrix operations.
+  }];
+}
+
+def RISCVOutDocs : Documentation {
+  let Category = DocCatFunction;
+  let Heading = "__riscv_out";
+  let Content = [{
+The ``__riscv_out(S)`` attribute indicates that a function writes to state S.
+This attribute is usually used in RISC-V matrix extensions to specify that the
+function will write to a matrix state passed as arguments.
+This helps compiler checks to prevent common programming errors that could lead
+to undefined behavior, data corruption, or incorrect computation results when
+working with matrix operations.
+  }];
+}
+
+def RISCVInOutDocs : Documentation {
+  let Category = DocCatFunction;
+  let Heading = "__riscv_inout";
+  let Content = [{
+The ``__riscv_inout(S)`` attribute indicates that a function reads from and
+writes to state S.
+This attribute is usually used in RISC-V matrix extensions to specify that the
+function will read from and write to a matrix state passed as arguments.
+This helps compiler checks to prevent common programming errors that could lead
+to undefined behavior, data corruption, or incorrect computation results when
+working with matrix operations.
+  }];
+}
+
+def RISCVPreservesDocs : Documentation {
+  let Category = DocCatFunction;
+  let Heading = "__riscv_preserves";
+  let Content = [{
+The ``__riscv_preserves(S)`` attribute indicates that a function neither reads
+from nor writes to state S.
+This attribute is usually used in RISC-V matrix extensions to specify that the
+function will not read from or write to a matrix state passed as arguments.
+This helps compiler checks to prevent common programming errors that could lead
+to undefined behavior, data corruption, or incorrect computation results when
+working with matrix operations.
+  }];
+}
+
+def RISCVNewDocs : Documentation {
+  let Category = DocCatFunction;
+  let Heading = "__riscv_new";
+  let Content = [{
+The ``__riscv_new(S)`` attribute indicates that a function initiates a new state.
+This attribute is usually used in RISC-V matrix extensions to specify that the
+function will initiate a new matrix state passed as arguments.
+This helps compiler checks to prevent common programming errors that could lead
+to undefined behavior, data corruption, or incorrect computation results when
+working with matrix operations.
+  }];
+}
+
 def PreferredNameDocs : Documentation {
   let Category = DocCatDecl;
   let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 2d73ebd4f8214f..34b29d3d474443 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13828,6 +13828,15 @@ def warn_riscv_attribute_interrupt_duplicate_type : Warning<
 def err_riscv_attribute_interrupt_invalid_combination : Error<
   "RISC-V 'interrupt' attribute contains invalid combination of interrupt types">;
 def err_riscv_builtin_invalid_twiden : Error<"RISC-V XSfmm twiden must be 1, 2 or 4">;
+// RISC-V errors
+def err_riscv_call_invalid_features : Error<
+  "call to an attributed function requires %0">;
+def err_missing_riscv_state : Error<"missing state for %0">;
+def err_unknown_riscv_state : Error<"unknown state '%0'">;
+def err_conflicting_attributes_riscv_state : Error<
+  "conflicting attribute. Description: %0">;
+def err_mutually_exclusive_attributes_riscv_state : Error<
+  "mutually exclusive attributes for state '%0'">;
 
 def err_std_source_location_impl_not_found : Error<
   "'std::source_location::__impl' was not found; it must be defined before '__builtin_source_location' is called">;
diff --git a/clang/include/clang/Sema/SemaRISCV.h b/clang/include/clang/Sema/SemaRISCV.h
index 49ac1d01b2b977..a0111f7e25b8c3 100644
--- a/clang/include/clang/Sema/SemaRISCV.h
+++ b/clang/include/clang/Sema/SemaRISCV.h
@@ -39,6 +39,12 @@ class SemaRISCV : public SemaBase {
   void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D,
                            const llvm::StringMap<bool> &FeatureMap);
 
+  /// Check for conflicting RISC-V architecture state attributes (e.g. XSfmm
+  /// matrix state) between a caller and callee.
+  void checkConflictingStateAttributes(
+      const FunctionDecl *CallerFD, const FunctionDecl *FD,
+      const FunctionProtoType::ExtProtoInfo &CalleeExtInfo, SourceLocation Loc);
+
   bool isValidRVVBitcast(QualType srcType, QualType destType);
 
   void handleInterruptAttr(Decl *D, const ParsedAttr &AL);
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 2bf3e08502d0a6..45ea34007c4401 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -5228,12 +5228,14 @@ QualType ASTContext::getFunctionTypeInternal(
   size_t Size = FunctionProtoType::totalSizeToAlloc<
       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
       FunctionType::FunctionTypeExtraAttributeInfo,
-      FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
+      FunctionType::FunctionTypeArmAttributes,
+      FunctionType::FunctionTypeRISCVAttributes, FunctionType::ExceptionType,
       Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
       FunctionEffect, EffectConditionExpr>(
       NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
       EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
-      EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
+      EPI.requiresFunctionProtoTypeArmAttributes(),
+      EPI.requiresFunctionProtoTypeRISCVAttributes(), ESH.NumExceptionType,
       ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
       EPI.ExtParameterInfos ? NumArgs : 0,
       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, EPI.FunctionEffects.size(),
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 9fc657168abe4a..55cb4c56fb1972 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -3960,6 +3960,15 @@ FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
     ExtraBits.HasArmTypeAttributes = true;
   }
 
+  if (epi.requiresFunctionProtoTypeRISCVAttributes()) {
+    auto &RISCVTypeAttrs = *getTrailingObjects<FunctionTypeRISCVAttributes>();
+    RISCVTypeAttrs = FunctionTypeRISCVAttributes();
+
+    // Also set the bit in FunctionTypeExtraBitfields
+    auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
+    ExtraBits.HasRISCVTypeAttributes = true;
+  }
+
   // Fill in the trailing argument array.
   auto *argSlot = getTrailingObjects<QualType>();
   for (unsigned i = 0; i != getNumParams(); ++i) {
@@ -3976,6 +3985,14 @@ FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
     ArmTypeAttrs.AArch64SMEAttributes = epi.AArch64SMEAttributes;
   }
 
+  // Propagate the RISC-V state attributes.
+  if (epi.RISCVAttributes != RISCVNormalFunction) {
+    auto &RISCVTypeAttrs = *getTrailingObjects<FunctionTypeRISCVAttributes>();
+    assert(epi.RISCVAttributes <= RISCVAttributeMask &&
+           "Not enough bits to encode RISC-V attributes");
+    RISCVTypeAttrs.RISCVAttributes = epi.RISCVAttributes;
+  }
+
   // Fill in the exception type array if present.
   if (getExceptionSpecType() == EST_Dynamic) {
     auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
@@ -4226,6 +4243,7 @@ void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
   ID.AddInteger((EffectCount << 3) | (HasConds << 2) |
                 (epi.AArch64SMEAttributes << 1) | epi.HasTrailingReturn);
   ID.AddInteger(epi.CFIUncheckedCallee);
+  ID.AddInteger(epi.RISCVAttributes);
 
   for (unsigned Idx = 0; Idx != EffectCount; ++Idx) {
     ID.AddInteger(epi.FunctionEffects.Effects[Idx].toOpaqueInt32());
diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index a90b2d2c0cb94d..1c9b0d7ce9f914 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2063,6 +2063,11 @@ void TypePrinter::printAttributedAfter(const AttributedType *T,
   case attr::ArmOut:
   case attr::ArmInOut:
   case attr::ArmPreserves:
+  case attr::RISCVIn:
+  case attr::RISCVOut:
+  case attr::RISCVInOut:
+  case attr::RISCVPreserves:
+  case attr::RISCVNew:
   case attr::NonBlocking:
   case attr::NonAllocating:
   case attr::Blocking:
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 1d7f9f742b87e9..5a05f8686b70b5 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2264,6 +2264,27 @@ static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
     FuncAttrs.addAttribute("aarch64_out_zt0");
   if (FunctionType::getArmZT0State(SMEBits) == FunctionType::ARM_InOut)
     FuncAttrs.addAttribute("aarch64_inout_zt0");
+
+  unsigned RISCVBits = FPT->getRISCVAttributes();
+  switch (FunctionType::getRISCVXsfmmState(RISCVBits)) {
+  case FunctionType::RISCVNone:
+    break;
+  case FunctionType::RISCVIn:
+    FuncAttrs.addAttribute("riscv_in");
+    break;
+  case FunctionType::RISCVOut:
+    FuncAttrs.addAttribute("riscv_out");
+    break;
+  case FunctionType::RISCVInOut:
+    FuncAttrs.addAttribute("riscv_inout");
+    break;
+  case FunctionType::RISCVPreserves:
+    FuncAttrs.addAttribute("riscv_preserves");
+    break;
+  case FunctionType::RISCVNew:
+    FuncAttrs.addAttribute("riscv_new");
+    break;
+  }
 }
 
 static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs,
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index a273eef3526d3c..ce822171155ddf 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4834,6 +4834,10 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
         Diag(Loc, diag::note_sme_use_preserves_za);
       }
     }
+
+    // Check for conflicting RISC-V architecture state attributes between the
+    // caller and callee.
+    RISCV().checkConflictingStateAttributes(CallerFD, FD, ExtInfo, Loc);
   }
 
   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
diff --git a/clang/lib/Sema/SemaRISCV.cpp b/clang/lib/Sema/SemaRISCV.cpp
index 907123cd6379c0..73f9dc8a7ab18e 100644
--- a/clang/lib/Sema/SemaRISCV.cpp
+++ b/clang/lib/Sema/SemaRISCV.cpp
@@ -1620,6 +1620,111 @@ void SemaRISCV::checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D,
     Diag(Loc, diag::err_riscv_type_requires_extension) << Ty << "zvfofp8min";
 }
 
+void SemaRISCV::checkConflictingStateAttributes(
+    const FunctionDecl *CallerFD, const FunctionDecl *FD,
+    const FunctionProtoType::ExtProtoInfo &CalleeExtInfo, SourceLocation Loc) {
+  ASTContext &Context = getASTContext();
+
+  // Check if there's any conflicting call for every state, it should not be
+  // any conflict if caller and callee are in different state.
+  if (!CallerFD ||
+      !(!FD || !FD->getBuiltinID() ||
+        Context.BuiltinInfo.isLibFunction(FD->getBuiltinID()) ||
+        Context.BuiltinInfo.isPredefinedLibFunction(FD->getBuiltinID())))
+    return;
+
+  QualType CallerType = CallerFD->getType();
+  if (CallerType.isNull())
+    return;
+
+  const auto *FPT = CallerType->getAs<FunctionProtoType>();
+  if (!FPT)
+    return;
+
+  FunctionProtoType::ExtProtoInfo CallerExtInfo = FPT->getExtProtoInfo();
+  llvm::StringMap<bool> CallerFeatureMap;
+  if (CallerExtInfo.RISCVAttributes & FunctionType::RISCVAttributeMask)
+    Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
+  // tuple(CallerAttr, CalleeAttr, required feature)
+  const std::tuple<FunctionType::RISCVStateValue, FunctionType::RISCVStateValue,
+                   StringRef>
+      RISCVStateInfo[] = {
+          {FunctionType::getRISCVXsfmmState(CallerExtInfo.RISCVAttributes),
+           FunctionType::getRISCVXsfmmState(CalleeExtInfo.RISCVAttributes),
+           "xsfmmbase"}};
+  for (auto [CallerAttr, CalleeAttr, RequiredFeature] : RISCVStateInfo) {
+    // If both caller and callee are not attributed, then we're fine.
+    if (CallerAttr == FunctionType::RISCVNone &&
+        CalleeAttr == FunctionType::RISCVNone)
+      continue;
+
+    if (!Context.getTargetInfo().hasFeature(RequiredFeature) &&
+        !CallerFeatureMap.lookup(RequiredFeature)) {
+      // check if corresponding attributes are enabled.
+      Diag(Loc, diag::err_riscv_call_invalid_features) << RequiredFeature;
+      continue;
+    }
+
+    switch (CallerAttr) {
+    case FunctionType::RISCVNone:
+      if (CalleeAttr != FunctionType::RISCVNew) {
+        // Check limitation:
+        // 1. Only __riscv_new function can be called in non-attributed
+        // function.
+        Diag(Loc, diag::err_conflicting_attributes_riscv_state)
+            << "Only __riscv_new function can be called in "
+               "non-attributed function.";
+      }
+      break;
+    case FunctionType::RISCVIn:
+      if (CalleeAttr != FunctionType::RISCVIn &&
+          CalleeAttr != FunctionType::RISCVPreserves) {
+        // 2. Function with __riscv_in can only call __riscv_in and
+        // __riscv_preserves function.
+        Diag(Loc, diag::err_conflicting_attributes_riscv_state)
+            << "Function with __riscv_in can only call __riscv_in and "
+               "__riscv_preserves function.";
+      }
+      break;
+    case FunctionType::RISCVOut:
+      if (CalleeAttr != FunctionType::RISCVIn &&
+          CalleeAttr != FunctionType::RISCVOut &&
+          CalleeAttr != FunctionType::RISCVPreserves) {
+        // 3. Function with __riscv_out can only call
+        // __riscv_in, __riscv_out and __riscv_preserves function.
+        Diag(Loc, diag::err_conflicting_attributes_riscv_state)
+            << "Function with __riscv_out can only call "
+               "__riscv_in, __riscv_out and __riscv_preserves "
+               "function.";
+      }
+      break;
+    case FunctionType::RISCVPreserves:
+      if (CalleeAttr != FunctionType::RISCVPreserves) {
+        // 4. Function with __riscv_preserves can only call
+        // __riscv_preserves function.
+        Diag(Loc, diag::err_conflicting_attributes_riscv_state)
+            << "Function with __riscv_preserves can only call "
+               "__riscv_preserves function.";
+      }
+      break;
+    case FunctionType::RISCVNew:
+    case FunctionType::RISCVInOut:
+      if (CalleeAttr == FunctionType::RISCVNone ||
+          CalleeAttr == FunctionType::RISCVNew) {
+        // Handle remainings: __riscv_new, __riscv_inout
+        // 5. Function with attribute can only call function with
+        // attribute(except for __riscv_new), i.e. __riscv_new and
+        // non-attributed function can not be called in attributed
+        // function.
+        Diag(Loc, diag::err_conflicting_attributes_riscv_state)
+            << "__riscv_new and non-attributed function can not be "
+               "called in attributed function.";
+      }
+      break;
+    }
+  }
+}
+
 /// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
 /// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
 /// VLS type) allowed?
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index e16630ce9cd844..d4b10fabc477a4 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -166,6 +166,11 @@ static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
   case ParsedAttr::AT_ArmAgnostic:                                             \
   case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:                            \
   case ParsedAttr::AT_AnyX86NoCfCheck:                                         \
+  case ParsedAttr::AT_RISCVIn:                                                 \
+  case ParsedAttr::AT_RISCVOut:                                                \
+  case ParsedAttr::AT_RISCVInOut:                                              \
+  case ParsedAttr::AT_RISCVPreserves:                                          \
+  case ParsedAttr::AT_RISCVNew:                                                \
     CALLING_CONV_ATTRS_CASELIST
 
 // Microsoft-specific type qualifiers.
@@ -8102,6 +8107,51 @@ static bool handleArmStateAttribute(Sema &S,
   return false;
 }
 
+static bool handleRISCVStateAttribute(Sema &S,
+                                      FunctionProtoType::ExtProtoInfo &EPI,
+                                      ParsedAttr &Attr,
+                                      FunctionType::RISCVStateValue State) {
+  if (!Attr.getNumArgs()) {
+    S.Diag(Attr.getLoc(), diag::err_missing_riscv_state) << Attr;
+    Attr.setInvalid();
+    return true;
+  }
+
+  for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
+    StringRef StateName;
+    SourceLocation LiteralLoc;
+    if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
+      return true;
+
+    unsigned Shift;
+    FunctionType::RISCVStateValue ExistingState;
+
+    // Determine which tile state this is and get its shift/mask
+    if (StateName == "xsfmm") {
+      Shift = FunctionType::RISCVXsfmmShift;
+      ExistingState = FunctionType::getRISCVXsfmmState(EPI.RISCVAttributes);
+    } else {
+      S.Diag(LiteralLoc, diag::err_unknown_riscv_state) << StateName;
+      Attr.setInvalid();
+      return true;
+    }
+
+    // __riscv_in, __riscv_out, __riscv_inout, __riscv_preserves, and
+    // __riscv_new are all mutually exclusive for the same state,
+    // so check if there are conflicting attributes.
+    if (ExistingState != FunctionType::RISCVNone && ExistingState != State) {
+      S.Diag(LiteralLoc, diag::err_mutually_exclusive_attributes_riscv_state)
+          << StateName;
+      Attr.setInvalid();
+      return true;
+    }
+
+    EPI.setRISCVAttribute(
+        (FunctionType::RISCVTypeAttributes)((State << Shift)));
+  }
+  return false;
+}
+
 /// Process an individual function attribute.  Returns true to
 /// indicate that the attribute was handled, false if it wasn't.
 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
@@ -8354,6 +8404,58 @@ static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
     return true;
   }
 
+  if (attr.getKind() == ParsedAttr::AT_RISCVIn ||
+      attr.getKind() == ParsedAttr::AT_RISCVOut ||
+      attr.getKind() == ParsedAttr::AT_RISCVInOut ||
+      attr.getKind() == ParsedAttr::AT_RISCVPreserves ||
+      attr.getKind() == ParsedAttr::AT_RISCVNew) {
+    if (S.CheckAttrTarget(attr))
+      return true;
+
+    if (!unwrapped.isFunctionType())
+      return false;
+
+    const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
+    if (!FnTy) {
+      S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
+          << attr << attr.isRegularKeywordAttribute()
+          << ExpectedFunctionWithProtoType;
+      attr.setInvalid();
+      return false;
+    }
+
+    FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
+    switch (attr.getKind()) {
+    case ParsedAttr::AT_RISCVIn:
+      if (handleRISCVStateAttribute(S, EPI, attr, FunctionType::RISCVIn))
+        return true;
+      break;
+    case ParsedAttr::AT_RISCVOut:
+      if (handleRISCVStateAttribute(S, EPI, attr, FunctionType::RISCVOut))
+        return true;
+      break;
+    case ParsedAttr::AT_RISCVInOut:
+      if (handleRISCVStateAttribute(S, EPI, attr, FunctionType::RISCVInOut))
+        return true;
+      break;
+    case ParsedAttr::AT_RISCVPreserves:
+      if (handleRISCVStateAttribute(S, EPI, attr, FunctionType::RISCVPreserves))
+        return true;
+      break;
+    case ParsedAttr::AT_RISCVNew:
+      if (handleRISCVStateAttribute(S, EPI, attr, FunctionType::RISCVNew))
+        return true;
+      break;
+    default:
+      llvm_unreachable("Unsupported attribute");
+    }
+
+    QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
+                                                 FnTy->getParamTypes(), EPI);
+    type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
+    return true;
+  }
+
   if (attr.getKind() == ParsedAttr::AT_NoThrow) {
     // Delay if this is not a function type.
     if (!unwrapped.isFunctionType())
diff --git a/clang/test/PCH/riscv-function-attributes.cpp b/clang/test/PCH/riscv-function-attributes.cpp
new file mode 100644
index 00000000000000..918de5ec45b96c
--- /dev/null
+++ b/clang/test/PCH/riscv-function-attributes.cpp
@@ -0,0 +1,13 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -triple riscv64 -emit-pch -o %t/header.pch %t/header.h -x c++
+// RUN: %clang_cc1 -triple riscv64 -include-pch %t/header.pch %t/main.cpp -fsyntax-only
+
+//--- header.h
+#pragma once
+
+typedef void (*kernel_t)(unsigned long, float *) __riscv_in("xsfmm");
+
+//--- main.cpp
+typedef void (*kernel_t)(unsigned long, float *) __riscv_in("xsfmm");
diff --git a/clang/test/Sema/sifive-xsfmm-func-attr.c b/clang/test/Sema/sifive-xsfmm-func-attr.c
new file mode 100644
index 00000000000000..218923c987d3c9
--- /dev/null
+++ b/clang/test/Sema/sifive-xsfmm-func-attr.c
@@ -0,0 +1,146 @@
+// RUN: %clang_cc1 -triple riscv64-none-linux-gnu -target-feature +xsfmmbase -Wno-error=implicit-function-declaration -fsyntax-only -verify %s
+// REQUIRES: riscv-registered-target
+
+#include <riscv_vector.h>
+
+int xsfmm_in_callee(void) __riscv_in("xsfmm");
+int xsfmm_out_callee(void) __riscv_out("xsfmm");
+int xsfmm_inout_callee(void) __riscv_inout("xsfmm");
+int xsfmm_preserves_callee(void) __riscv_preserves("xsfmm");
+int xsfmm_new_callee(void) __riscv_new("xsfmm");
+
+void valid_new(void) {
+  xsfmm_new_callee();
+}
+
+void valid_preserves_in_in(void) __riscv_in("xsfmm") {
+  xsfmm_preserves_callee();
+}
+
+void valid_in_in_in(void) __riscv_in("xsfmm") {
+  xsfmm_in_callee();
+}
+
+void valid_in_in_out(void) __riscv_out("xsfmm") {
+  xsfmm_in_callee();
+}
+
+void valid_out_in_out(void) __riscv_out("xsfmm") {
+  xsfmm_out_callee();
+}
+
+void valid_preserves_in_out(void) __riscv_out("xsfmm") {
+  xsfmm_preserves_callee();
+}
+
+void valid_preserves_in_preserves(void) __riscv_preserves("xsfmm") {
+  xsfmm_preserves_callee();
+}
+
+vint32m1_t valid_in_intrinsic(vint32m1_t v, unsigned vl) __riscv_in("xsfmm") {
+  unsigned avl = __riscv_vsetvl_e32m1(vl);
+  return __riscv_vadd(v, v, avl);
+}
+
+vint32m1_t valid_out_intrinsic(vint32m1_t v, unsigned vl) __riscv_out("xsfmm") {
+  unsigned avl = __riscv_vsetvl_e32m1(vl);
+  return __riscv_vadd(v, v, avl);
+}
+
+vint32m1_t valid_inout_intrinsic(vint32m1_t v, unsigned vl) __riscv_inout("xsfmm") {
+  unsigned avl = __riscv_vsetvl_e32m1(vl);
+  return __riscv_vadd(v, v, avl);
+}
+
+vint32m1_t valid_preserves_intrinsic(vint32m1_t v, unsigned vl) __riscv_preserves("xsfmm") {
+  unsigned avl = __riscv_vsetvl_e32m1(vl);
+  return __riscv_vadd(v, v, avl);
+}
+
+vint32m1_t valid_new_intrinsic(vint32m1_t v, unsigned vl) __riscv_new("xsfmm") {
+  unsigned avl = __riscv_vsetvl_e32m1(vl);
+  return __riscv_vadd(v, v, avl);
+}
+
+void invalid_mutual_exclusive1(void) __riscv_in("xsfmm") __riscv_out("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive2(void) __riscv_in("xsfmm") __riscv_inout("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive3(void) __riscv_in("xsfmm") __riscv_preserves("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive4(void) __riscv_in("xsfmm") __riscv_new("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive5(void) __riscv_out("xsfmm") __riscv_inout("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive6(void) __riscv_out("xsfmm") __riscv_preserves("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive7(void) __riscv_out("xsfmm") __riscv_new("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive8(void) __riscv_inout("xsfmm") __riscv_preserves("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive9(void) __riscv_inout("xsfmm") __riscv_new("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_mutual_exclusive10(void) __riscv_preserves("xsfmm") __riscv_new("xsfmm") { // expected-error {{mutually exclusive attributes for state 'xsfmm'}}
+}
+
+void invalid_in_in_preserves(void) __riscv_preserves("xsfmm") {
+  xsfmm_in_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_preserves can only call __riscv_preserves function.}}
+}
+
+void invalid_out_in_preserves(void) __riscv_preserves("xsfmm") {
+  xsfmm_out_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_preserves can only call __riscv_preserves function.}}
+}
+
+void invalid_inout_in_preserves(void) __riscv_preserves("xsfmm") {
+  xsfmm_inout_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_preserves can only call __riscv_preserves function.}}
+}
+
+void invalid_new_in_preserves(void) __riscv_preserves("xsfmm") {
+  xsfmm_new_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_preserves can only call __riscv_preserves function.}}
+}
+
+void invalid_out_in_in(void) __riscv_in("xsfmm") {
+  xsfmm_out_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_in can only call __riscv_in and __riscv_preserves function.}}
+}
+
+void invalid_inout_in_in(void) __riscv_in("xsfmm") {
+  xsfmm_inout_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_in can only call __riscv_in and __riscv_preserves function.}}
+}
+
+void invalid_new_in_in(void) __riscv_in("xsfmm") {
+  xsfmm_new_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_in can only call __riscv_in and __riscv_preserves function.}}
+}
+
+void invalid_inout_in_out(void) __riscv_out("xsfmm") {
+  xsfmm_inout_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_out can only call __riscv_in, __riscv_out and __riscv_preserves function.}}
+}
+
+void invalid_new_in_out(void) __riscv_out("xsfmm") {
+  xsfmm_new_callee(); // expected-error {{conflicting attribute. Description: Function with __riscv_out can only call __riscv_in, __riscv_out and __riscv_preserves function.}}
+}
+
+void invalid_new_in_new(void) __riscv_new("xsfmm") {
+  xsfmm_new_callee(); // expected-error {{conflicting attribute. Description: __riscv_new and non-attributed function can not be called in attributed function.}}
+}
+
+void invalid_lib_function_intrinsic(void) __riscv_in("xsfmm") {
+  __builtin_memcpy(NULL, NULL, 0); // expected-error {{conflicting attribute. Description: Function with __riscv_in can only call __riscv_in and __riscv_preserves function.}}
+}
+
+void invalid_predefined_lib_function(void) __riscv_in("xsfmm") {
+  memcpy(NULL, NULL, 0); // expected-error {{conflicting attribute. Description: Function with __riscv_in can only call __riscv_in and __riscv_preserves function.}}
+  // expected-warning at -1 {{call to undeclared library function 'memcpy' with type 'void *(void *, const void *, __size_t)' (aka 'void *(void *, const void *, unsigned long)'); ISO C99 and later do not support implicit function declarations}}
+  // expected-note at -2 {{include the header <string.h> or explicitly provide a declaration for 'memcpy'}}
+}
+
+void invalid_state(void) __riscv_new("12345") { // expected-error {{unknown state '12345'}}
+}
diff --git a/llvm/lib/Target/RISCV/GISel/RISCVCallLowering.cpp b/llvm/lib/Target/RISCV/GISel/RISCVCallLowering.cpp
index 07029d09dad7c5..75aacd65b8c274 100644
--- a/llvm/lib/Target/RISCV/GISel/RISCVCallLowering.cpp
+++ b/llvm/lib/Target/RISCV/GISel/RISCVCallLowering.cpp
@@ -590,6 +590,12 @@ bool RISCVCallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
 
   const RISCVSubtarget &Subtarget =
       MIRBuilder.getMF().getSubtarget<RISCVSubtarget>();
+
+  if (Info.Callee.isGlobal())
+    checkRISCVStateCall(MF.getFunction(), Info.Callee.getGlobal());
+  else if (Info.Callee.isSymbol())
+    checkRISCVStateCall(MF.getFunction(), Info.Callee.getSymbolName());
+
   for (auto &AInfo : Info.OrigArgs) {
     if (!isSupportedArgumentType(AInfo.Ty, Subtarget))
       return false;
diff --git a/llvm/lib/Target/RISCV/RISCV.h b/llvm/lib/Target/RISCV/RISCV.h
index 3788715a3da7f7..840cef5134f45e 100644
--- a/llvm/lib/Target/RISCV/RISCV.h
+++ b/llvm/lib/Target/RISCV/RISCV.h
@@ -372,6 +372,7 @@ FunctionPass *createRISCVQCRelaxMarkingLegacyPass();
 void initializeRISCVQCRelaxMarkingLegacyPass(PassRegistry &);
 
 void initializeRISCVAsmPrinterPass(PassRegistry &);
+
 } // namespace llvm
 
 #endif
diff --git a/llvm/lib/Target/RISCV/RISCVCallingConv.cpp b/llvm/lib/Target/RISCV/RISCVCallingConv.cpp
index 9a4bf8e3a64235..2bfd1a837cf5c9 100644
--- a/llvm/lib/Target/RISCV/RISCVCallingConv.cpp
+++ b/llvm/lib/Target/RISCV/RISCVCallingConv.cpp
@@ -12,12 +12,33 @@
 
 #include "RISCVCallingConv.h"
 #include "RISCVMachineFunctionInfo.h"
+#include "RISCVStateAttributes.h"
 #include "RISCVSubtarget.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/MC/MCRegister.h"
 
 using namespace llvm;
 
+void llvm::checkRISCVStateCall(const Function &Caller, StringRef CalleeName) {
+  if (!RISCVState::hasAttribute(Caller))
+    return;
+
+  std::string Message = (Caller.getName() + ": cannot emit call to '" +
+                         CalleeName + "' from a RISC-V attributed function.")
+                            .str();
+  Caller.getContext().diagnose(DiagnosticInfoGeneric(Message));
+}
+
+void llvm::checkRISCVStateCall(const Function &Caller,
+                               const GlobalValue *Callee) {
+  const auto *CalleeFn = dyn_cast_or_null<Function>(Callee);
+  if (CalleeFn && RISCVState::hasAttribute(*CalleeFn))
+    return;
+
+  if (Callee)
+    checkRISCVStateCall(Caller, Callee->getName());
+}
+
 // This does not have the regular `CCAssignFn` signature, it has an extra
 // `bool IsRet` parameter.
 static bool CC_RISCV_Impl(unsigned ValNo, MVT ValVT, MVT LocVT,
diff --git a/llvm/lib/Target/RISCV/RISCVCallingConv.h b/llvm/lib/Target/RISCV/RISCVCallingConv.h
index f5b7773b6f3848..45bde4b2c1c207 100644
--- a/llvm/lib/Target/RISCV/RISCVCallingConv.h
+++ b/llvm/lib/Target/RISCV/RISCVCallingConv.h
@@ -12,6 +12,7 @@
 
 #include "MCTargetDesc/RISCVBaseInfo.h"
 #include "llvm/CodeGen/CallingConvLower.h"
+#include "llvm/IR/Function.h"
 
 namespace llvm {
 
@@ -31,4 +32,7 @@ ArrayRef<MCPhysReg> getArgVRs(const RISCVSubtarget &STI);
 
 } // end namespace RISCV
 
+void checkRISCVStateCall(const Function &Caller, const GlobalValue *Callee);
+void checkRISCVStateCall(const Function &Caller, StringRef CalleeName);
+
 } // end namespace llvm
diff --git a/llvm/lib/Target/RISCV/RISCVISelLowering.cpp b/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
index 0d7be09555ed6e..eef8d5237af876 100644
--- a/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
+++ b/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
@@ -29103,6 +29103,11 @@ SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
   MachineFunction &MF = DAG.getMachineFunction();
   MachineFunction::CallSiteInfo CSInfo;
 
+  if (auto *GA = dyn_cast<GlobalAddressSDNode>(Callee))
+    checkRISCVStateCall(MF.getFunction(), GA->getGlobal());
+  else if (auto *ES = dyn_cast<ExternalSymbolSDNode>(Callee))
+    checkRISCVStateCall(MF.getFunction(), ES->getSymbol());
+
   // Set type id for call site info.
   setTypeIdForCallsiteInfo(CB, MF, CSInfo);
 
diff --git a/llvm/lib/Target/RISCV/RISCVInstrInfo.cpp b/llvm/lib/Target/RISCV/RISCVInstrInfo.cpp
index a81d876462f160..34340efa56b37a 100644
--- a/llvm/lib/Target/RISCV/RISCVInstrInfo.cpp
+++ b/llvm/lib/Target/RISCV/RISCVInstrInfo.cpp
@@ -15,6 +15,7 @@
 #include "MCTargetDesc/RISCVMatInt.h"
 #include "RISCV.h"
 #include "RISCVMachineFunctionInfo.h"
+#include "RISCVStateAttributes.h"
 #include "RISCVSubtarget.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
diff --git a/llvm/lib/Target/RISCV/RISCVStateAttributes.h b/llvm/lib/Target/RISCV/RISCVStateAttributes.h
new file mode 100644
index 00000000000000..e755190b341561
--- /dev/null
+++ b/llvm/lib/Target/RISCV/RISCVStateAttributes.h
@@ -0,0 +1,29 @@
+//=-- RISCVStateAttributes.h - Helper for interpreting RISC-V attributes -*-==//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIB_TARGET_RISCV_RISCVSTATEATTRIBUTES_H
+#define LLVM_LIB_TARGET_RISCV_RISCVSTATEATTRIBUTES_H
+
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/IR/Function.h"
+
+namespace llvm {
+namespace RISCVState {
+
+inline constexpr StringLiteral Attributes[] = {
+    "riscv_in", "riscv_out", "riscv_inout", "riscv_preserves", "riscv_new"};
+
+inline bool hasAttribute(const Function &F) {
+  return any_of(Attributes, [&F](StringRef A) { return F.hasFnAttribute(A); });
+}
+
+} // namespace RISCVState
+} // namespace llvm
+
+#endif // LLVM_LIB_TARGET_RISCV_RISCVSTATEATTRIBUTES_H
diff --git a/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.cpp b/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.cpp
index 55f0f56948dc84..833f1f0303d125 100644
--- a/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.cpp
+++ b/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.cpp
@@ -4048,6 +4048,18 @@ bool RISCVTTIImpl::shouldCopyAttributeWhenOutliningFrom(
   return BaseT::shouldCopyAttributeWhenOutliningFrom(Caller, Attr);
 }
 
+bool RISCVTTIImpl::areInlineCompatible(const Function *Caller,
+                                       const Function *Callee) const {
+  // riscv_new is the only function that can be called in an non-attributed
+  // function, we need to prevent inlining this kind of function in case any
+  // compiler generated non-attributed call in attributed function is inlined so
+  // it passes the check silently.
+  if (Callee->hasFnAttribute("riscv_new"))
+    return false;
+
+  return BaseT::areInlineCompatible(Caller, Callee);
+}
+
 std::optional<Instruction *>
 RISCVTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
   // Attach a range return attribute describing the result of vsetvli/vsetvlimax
diff --git a/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.h b/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.h
index 26f03c9e54e0af..7d29c59e169227 100644
--- a/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.h
+++ b/llvm/lib/Target/RISCV/RISCVTargetTransformInfo.h
@@ -587,6 +587,9 @@ class RISCVTTIImpl final : public BasicTTIImplBase<RISCVTTIImpl> {
   shouldCopyAttributeWhenOutliningFrom(const Function *Caller,
                                        const Attribute &Attr) const override;
 
+  bool areInlineCompatible(const Function *Caller,
+                           const Function *Callee) const override;
+
   std::optional<Instruction *>
   instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const override;
 };
diff --git a/llvm/test/CodeGen/RISCV/riscv-state-check.ll b/llvm/test/CodeGen/RISCV/riscv-state-check.ll
new file mode 100644
index 00000000000000..310c6dce91e5aa
--- /dev/null
+++ b/llvm/test/CodeGen/RISCV/riscv-state-check.ll
@@ -0,0 +1,32 @@
+; RUN: not llc -mtriple=riscv64 -mattr=+xsfmmbase -o /dev/null < %s 2>&1 \
+; RUN:   | FileCheck %s --implicit-check-not=error:
+; RUN: not llc -global-isel -mtriple=riscv64 -mattr=+xsfmmbase -o /dev/null < %s 2>&1 \
+; RUN:   | FileCheck %s --implicit-check-not=error:
+
+; CHECK: error: libgcc_call: cannot emit call to '__divdi3' from a RISC-V attributed function.
+define i64 @libgcc_call(i64 %a, i64 %b) "riscv_inout" {
+  %d = sdiv i64 %a, %b
+  ret i64 %d
+}
+
+declare void @llvm.memcpy.p0.p0.i64(ptr, ptr, i64, i1)
+; CHECK: error: memcpy_call: cannot emit call to 'memcpy' from a RISC-V attributed function.
+define void @memcpy_call(ptr %d, ptr %s) "riscv_in" {
+  call void @llvm.memcpy.p0.p0.i64(ptr %d, ptr %s, i64 1024, i1 false)
+  ret void
+}
+
+declare void @extern_func()
+; CHECK: error: extern_call: cannot emit call to 'extern_func' from a RISC-V attributed function.
+define void @extern_call() "riscv_in" {
+  tail call void @extern_func()
+  ret void
+}
+
+declare void @preserves(i64, i64, i64, i64, i64, i64, i64, i64, i64, i64, i64, i64) "riscv_preserves"
+; spill lib calls should be legal, e.g. __riscv_save_4, __riscv_save_5
+define void @legal(i64 %a) "riscv_in" {
+  call void @preserves(i64 %a, i64 1, i64 2, i64 3, i64 4, i64 5, i64 6, i64 7, i64 8, i64 9, i64 10, i64 11)
+  call void @preserves(i64 %a, i64 1, i64 2, i64 3, i64 4, i64 5, i64 6, i64 7, i64 8, i64 9, i64 10, i64 11)
+  ret void
+}

>From 8da109e8f0461f97ecfd9ecfeea504db85d9932a Mon Sep 17 00:00:00 2001
From: Brandon Wu <brandon.wu at sifive.com>
Date: Tue, 10 Nov 2026 20:57:35 -0800
Subject: [PATCH 2/4] Guard the check by target and try to prevent calling
 getExtProtoInfo

---
 clang/include/clang/Sema/SemaRISCV.h |  3 ++-
 clang/lib/Sema/SemaChecking.cpp      | 20 +++++++++++++++++++-
 clang/lib/Sema/SemaRISCV.cpp         | 25 +++++++------------------
 3 files changed, 28 insertions(+), 20 deletions(-)

diff --git a/clang/include/clang/Sema/SemaRISCV.h b/clang/include/clang/Sema/SemaRISCV.h
index a0111f7e25b8c3..63bb48b6788a8c 100644
--- a/clang/include/clang/Sema/SemaRISCV.h
+++ b/clang/include/clang/Sema/SemaRISCV.h
@@ -43,7 +43,8 @@ class SemaRISCV : public SemaBase {
   /// matrix state) between a caller and callee.
   void checkConflictingStateAttributes(
       const FunctionDecl *CallerFD, const FunctionDecl *FD,
-      const FunctionProtoType::ExtProtoInfo &CalleeExtInfo, SourceLocation Loc);
+      FunctionType::RISCVStateValue CallerState,
+      FunctionType::RISCVStateValue CalleeState, SourceLocation Loc);
 
   bool isValidRVVBitcast(QualType srcType, QualType destType);
 
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index ce822171155ddf..b32889a011fd2c 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4837,7 +4837,25 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
 
     // Check for conflicting RISC-V architecture state attributes between the
     // caller and callee.
-    RISCV().checkConflictingStateAttributes(CallerFD, FD, ExtInfo, Loc);
+    if (Context.getTargetInfo().getTriple().isRISCV()) {
+      auto CalleeRISCVState =
+          FunctionType::getRISCVXsfmmState(ExtInfo.RISCVAttributes);
+      auto CallerRISCVState = FunctionType::RISCVNone;
+      if (CallerFD) {
+        QualType CallerType = CallerFD->getType();
+        if (!CallerType.isNull()) {
+          if (const auto *CallerFPT =
+                  CallerType->getAs<FunctionProtoType>())
+            CallerRISCVState = FunctionType::getRISCVXsfmmState(
+                CallerFPT->getRISCVAttributes());
+
+          if (CallerRISCVState != FunctionType::RISCVNone ||
+              CalleeRISCVState != FunctionType::RISCVNone)
+            RISCV().checkConflictingStateAttributes(
+                CallerFD, FD, CallerRISCVState, CalleeRISCVState, Loc);
+        }
+      }
+    }
   }
 
   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
diff --git a/clang/lib/Sema/SemaRISCV.cpp b/clang/lib/Sema/SemaRISCV.cpp
index 73f9dc8a7ab18e..0cffa3770d0c12 100644
--- a/clang/lib/Sema/SemaRISCV.cpp
+++ b/clang/lib/Sema/SemaRISCV.cpp
@@ -1622,36 +1622,25 @@ void SemaRISCV::checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D,
 
 void SemaRISCV::checkConflictingStateAttributes(
     const FunctionDecl *CallerFD, const FunctionDecl *FD,
-    const FunctionProtoType::ExtProtoInfo &CalleeExtInfo, SourceLocation Loc) {
+    FunctionType::RISCVStateValue CallerState,
+    FunctionType::RISCVStateValue CalleeState, SourceLocation Loc) {
   ASTContext &Context = getASTContext();
 
   // Check if there's any conflicting call for every state, it should not be
   // any conflict if caller and callee are in different state.
-  if (!CallerFD ||
-      !(!FD || !FD->getBuiltinID() ||
-        Context.BuiltinInfo.isLibFunction(FD->getBuiltinID()) ||
-        Context.BuiltinInfo.isPredefinedLibFunction(FD->getBuiltinID())))
+  if (FD && FD->getBuiltinID() &&
+      !Context.BuiltinInfo.isLibFunction(FD->getBuiltinID()) &&
+      !Context.BuiltinInfo.isPredefinedLibFunction(FD->getBuiltinID()))
     return;
 
-  QualType CallerType = CallerFD->getType();
-  if (CallerType.isNull())
-    return;
-
-  const auto *FPT = CallerType->getAs<FunctionProtoType>();
-  if (!FPT)
-    return;
-
-  FunctionProtoType::ExtProtoInfo CallerExtInfo = FPT->getExtProtoInfo();
   llvm::StringMap<bool> CallerFeatureMap;
-  if (CallerExtInfo.RISCVAttributes & FunctionType::RISCVAttributeMask)
+  if (CallerState != FunctionType::RISCVNone)
     Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
   // tuple(CallerAttr, CalleeAttr, required feature)
   const std::tuple<FunctionType::RISCVStateValue, FunctionType::RISCVStateValue,
                    StringRef>
       RISCVStateInfo[] = {
-          {FunctionType::getRISCVXsfmmState(CallerExtInfo.RISCVAttributes),
-           FunctionType::getRISCVXsfmmState(CalleeExtInfo.RISCVAttributes),
-           "xsfmmbase"}};
+          {CallerState, CalleeState, "xsfmmbase"}};
   for (auto [CallerAttr, CalleeAttr, RequiredFeature] : RISCVStateInfo) {
     // If both caller and callee are not attributed, then we're fine.
     if (CallerAttr == FunctionType::RISCVNone &&

>From a77c88a798b1595e14f970dac193e335db99fc1f Mon Sep 17 00:00:00 2001
From: Brandon Wu <brandon.wu at sifive.com>
Date: Wed, 11 Nov 2026 08:16:10 -0800
Subject: [PATCH 3/4] Consolidate trailing object

---
 clang/include/clang/AST/TypeBase.h | 29 +++++------------------------
 clang/lib/AST/ASTContext.cpp       |  6 ++----
 clang/lib/AST/Type.cpp             | 13 ++-----------
 3 files changed, 9 insertions(+), 39 deletions(-)

diff --git a/clang/include/clang/AST/TypeBase.h b/clang/include/clang/AST/TypeBase.h
index 35b427318f0dce..9f5c9c6caf7285 100644
--- a/clang/include/clang/AST/TypeBase.h
+++ b/clang/include/clang/AST/TypeBase.h
@@ -4993,8 +4993,8 @@ class FunctionType : public Type {
     LLVM_PREFERRED_TYPE(bool)
     unsigned HasArmTypeAttributes : 1;
 
-    LLVM_PREFERRED_TYPE(bool)
-    unsigned HasRISCVTypeAttributes : 1;
+    LLVM_PREFERRED_TYPE(unsigned)
+    unsigned RISCVAttributes : 3;
 
     LLVM_PREFERRED_TYPE(bool)
     unsigned EffectsHaveConditions : 1;
@@ -5002,7 +5002,7 @@ class FunctionType : public Type {
 
     FunctionTypeExtraBitfields()
         : NumExceptionType(0), HasExtraAttributeInfo(false),
-          HasArmTypeAttributes(false), HasRISCVTypeAttributes(false),
+          HasArmTypeAttributes(false), RISCVAttributes(0),
           EffectsHaveConditions(false), NumFunctionEffects(0) {}
   };
 
@@ -5114,13 +5114,6 @@ class FunctionType : public Type {
     FunctionTypeArmAttributes() : AArch64SMEAttributes(SME_NormalFunction) {}
   };
 
-  struct alignas(void *) FunctionTypeRISCVAttributes {
-    LLVM_PREFERRED_TYPE(RISCVTypeAttributes)
-    unsigned RISCVAttributes : 3;
-
-    FunctionTypeRISCVAttributes() : RISCVAttributes(RISCVNormalFunction) {}
-  };
-
 protected:
   FunctionType(TypeClass tc, QualType res, QualType Canonical,
                TypeDependence Dependence, ExtInfo Info)
@@ -5599,7 +5592,6 @@ class FunctionProtoType final
           FunctionType::FunctionTypeExtraBitfields,
           FunctionType::FunctionTypeExtraAttributeInfo,
           FunctionType::FunctionTypeArmAttributes,
-          FunctionType::FunctionTypeRISCVAttributes,
           FunctionType::ExceptionType, Expr *, FunctionDecl *,
           FunctionType::ExtParameterInfo, Qualifiers, FunctionEffect,
           EffectConditionExpr> {
@@ -5778,11 +5770,6 @@ class FunctionProtoType final
     return hasArmTypeAttributes();
   }
 
-  unsigned
-  numTrailingObjects(OverloadToken<FunctionTypeRISCVAttributes>) const {
-    return hasRISCVTypeAttributes();
-  }
-
   unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
     return hasExtraBitfields();
   }
@@ -5896,12 +5883,6 @@ class FunctionProtoType final
                ->HasArmTypeAttributes;
   }
 
-  bool hasRISCVTypeAttributes() const {
-    return FunctionTypeBits.HasExtraBitfields &&
-           getTrailingObjects<FunctionTypeExtraBitfields>()
-               ->HasRISCVTypeAttributes;
-  }
-
   bool hasExtQualifiers() const {
     return FunctionTypeBits.HasExtQuals;
   }
@@ -6135,9 +6116,9 @@ class FunctionProtoType final
   }
 
   unsigned getRISCVAttributes() const {
-    if (!hasRISCVTypeAttributes())
+    if (!hasExtraBitfields())
       return RISCVNormalFunction;
-    return getTrailingObjects<FunctionTypeRISCVAttributes>()->RISCVAttributes;
+    return getTrailingObjects<FunctionTypeExtraBitfields>()->RISCVAttributes;
   }
 
   ExtParameterInfo getExtParameterInfo(unsigned I) const {
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 45ea34007c4401..d334bcf07c370b 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -5228,15 +5228,13 @@ QualType ASTContext::getFunctionTypeInternal(
   size_t Size = FunctionProtoType::totalSizeToAlloc<
       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
       FunctionType::FunctionTypeExtraAttributeInfo,
-      FunctionType::FunctionTypeArmAttributes,
-      FunctionType::FunctionTypeRISCVAttributes, FunctionType::ExceptionType,
+      FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
       Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
       FunctionEffect, EffectConditionExpr>(
       NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
       EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
       EPI.requiresFunctionProtoTypeArmAttributes(),
-      EPI.requiresFunctionProtoTypeRISCVAttributes(), ESH.NumExceptionType,
-      ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
+      ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
       EPI.ExtParameterInfos ? NumArgs : 0,
       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, EPI.FunctionEffects.size(),
       EPI.FunctionEffects.conditions().size());
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 55cb4c56fb1972..073b57944baad9 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -3960,15 +3960,6 @@ FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
     ExtraBits.HasArmTypeAttributes = true;
   }
 
-  if (epi.requiresFunctionProtoTypeRISCVAttributes()) {
-    auto &RISCVTypeAttrs = *getTrailingObjects<FunctionTypeRISCVAttributes>();
-    RISCVTypeAttrs = FunctionTypeRISCVAttributes();
-
-    // Also set the bit in FunctionTypeExtraBitfields
-    auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
-    ExtraBits.HasRISCVTypeAttributes = true;
-  }
-
   // Fill in the trailing argument array.
   auto *argSlot = getTrailingObjects<QualType>();
   for (unsigned i = 0; i != getNumParams(); ++i) {
@@ -3987,10 +3978,10 @@ FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
 
   // Propagate the RISC-V state attributes.
   if (epi.RISCVAttributes != RISCVNormalFunction) {
-    auto &RISCVTypeAttrs = *getTrailingObjects<FunctionTypeRISCVAttributes>();
     assert(epi.RISCVAttributes <= RISCVAttributeMask &&
            "Not enough bits to encode RISC-V attributes");
-    RISCVTypeAttrs.RISCVAttributes = epi.RISCVAttributes;
+    auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
+    ExtraBits.RISCVAttributes = epi.RISCVAttributes;
   }
 
   // Fill in the exception type array if present.

>From 79ae5aa71d1baee07950f88c79077ff639097ee3 Mon Sep 17 00:00:00 2001
From: Brandon Wu <brandon.wu at sifive.com>
Date: Wed, 11 Nov 2026 19:09:04 -0800
Subject: [PATCH 4/4] fixup! clang-format

---
 clang/include/clang/AST/TypeBase.h | 7 +++----
 clang/lib/AST/ASTContext.cpp       | 4 ++--
 clang/lib/Sema/SemaChecking.cpp    | 3 +--
 clang/lib/Sema/SemaRISCV.cpp       | 3 +--
 4 files changed, 7 insertions(+), 10 deletions(-)

diff --git a/clang/include/clang/AST/TypeBase.h b/clang/include/clang/AST/TypeBase.h
index 9f5c9c6caf7285..b60f2bc16e1181 100644
--- a/clang/include/clang/AST/TypeBase.h
+++ b/clang/include/clang/AST/TypeBase.h
@@ -5591,10 +5591,9 @@ class FunctionProtoType final
           FunctionProtoType, QualType, SourceLocation,
           FunctionType::FunctionTypeExtraBitfields,
           FunctionType::FunctionTypeExtraAttributeInfo,
-          FunctionType::FunctionTypeArmAttributes,
-          FunctionType::ExceptionType, Expr *, FunctionDecl *,
-          FunctionType::ExtParameterInfo, Qualifiers, FunctionEffect,
-          EffectConditionExpr> {
+          FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
+          Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers,
+          FunctionEffect, EffectConditionExpr> {
   friend class ASTContext; // ASTContext creates these.
   friend TrailingObjects;
 
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index d334bcf07c370b..2bf3e08502d0a6 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -5233,8 +5233,8 @@ QualType ASTContext::getFunctionTypeInternal(
       FunctionEffect, EffectConditionExpr>(
       NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
       EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
-      EPI.requiresFunctionProtoTypeArmAttributes(),
-      ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
+      EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
+      ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
       EPI.ExtParameterInfos ? NumArgs : 0,
       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, EPI.FunctionEffects.size(),
       EPI.FunctionEffects.conditions().size());
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index b32889a011fd2c..77be48c0b59ea7 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4844,8 +4844,7 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
       if (CallerFD) {
         QualType CallerType = CallerFD->getType();
         if (!CallerType.isNull()) {
-          if (const auto *CallerFPT =
-                  CallerType->getAs<FunctionProtoType>())
+          if (const auto *CallerFPT = CallerType->getAs<FunctionProtoType>())
             CallerRISCVState = FunctionType::getRISCVXsfmmState(
                 CallerFPT->getRISCVAttributes());
 
diff --git a/clang/lib/Sema/SemaRISCV.cpp b/clang/lib/Sema/SemaRISCV.cpp
index 0cffa3770d0c12..605b8dd6bd1840 100644
--- a/clang/lib/Sema/SemaRISCV.cpp
+++ b/clang/lib/Sema/SemaRISCV.cpp
@@ -1639,8 +1639,7 @@ void SemaRISCV::checkConflictingStateAttributes(
   // tuple(CallerAttr, CalleeAttr, required feature)
   const std::tuple<FunctionType::RISCVStateValue, FunctionType::RISCVStateValue,
                    StringRef>
-      RISCVStateInfo[] = {
-          {CallerState, CalleeState, "xsfmmbase"}};
+      RISCVStateInfo[] = {{CallerState, CalleeState, "xsfmmbase"}};
   for (auto [CallerAttr, CalleeAttr, RequiredFeature] : RISCVStateInfo) {
     // If both caller and callee are not attributed, then we're fine.
     if (CallerAttr == FunctionType::RISCVNone &&



More information about the cfe-commits mailing list