From 335e68d8bce5ad3f5d6471c0ec1423211c71c0f0 Mon Sep 17 00:00:00 2001 From: Jesse Huang Date: Tue, 29 Oct 2024 00:47:49 -0700 Subject: [PATCH] [Clang][RISCV] Support -fcf-protection=return for RISC-V (#112477) Enables the support of `-fcf-protection=return` on RISC-V, which requires Zicfiss. It also adds a string attribute "hw-shadow-stack" to every function if the option is set on RISC-V --- clang/lib/Basic/Targets/RISCV.h | 7 +++++++ clang/lib/CodeGen/Targets/RISCV.cpp | 7 +++++-- clang/test/CodeGen/RISCV/attr-hw-shadow-stack.c | 9 +++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 clang/test/CodeGen/RISCV/attr-hw-shadow-stack.c diff --git a/clang/lib/Basic/Targets/RISCV.h b/clang/lib/Basic/Targets/RISCV.h index bf40edb8683b3e..3b418585ab4a39 100644 --- a/clang/lib/Basic/Targets/RISCV.h +++ b/clang/lib/Basic/Targets/RISCV.h @@ -141,6 +141,13 @@ class RISCVTargetInfo : public TargetInfo { return true; } + bool + checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const override { + if (ISAInfo->hasExtension("zicfiss")) + return true; + return TargetInfo::checkCFProtectionReturnSupported(Diags); + } + CFBranchLabelSchemeKind getDefaultCFBranchLabelScheme() const override { return CFBranchLabelSchemeKind::FuncSig; } diff --git a/clang/lib/CodeGen/Targets/RISCV.cpp b/clang/lib/CodeGen/Targets/RISCV.cpp index fd72fe673b9b14..b04e436c665f52 100644 --- a/clang/lib/CodeGen/Targets/RISCV.cpp +++ b/clang/lib/CodeGen/Targets/RISCV.cpp @@ -594,6 +594,11 @@ class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { const auto *FD = dyn_cast_or_null(D); if (!FD) return; + auto *Fn = cast(GV); + + if (CGM.getCodeGenOpts().CFProtectionReturn) + Fn->addFnAttr("hw-shadow-stack"); + const auto *Attr = FD->getAttr(); if (!Attr) return; @@ -604,8 +609,6 @@ class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { case RISCVInterruptAttr::machine: Kind = "machine"; break; } - auto *Fn = cast(GV); - Fn->addFnAttr("interrupt", Kind); } }; diff --git a/clang/test/CodeGen/RISCV/attr-hw-shadow-stack.c b/clang/test/CodeGen/RISCV/attr-hw-shadow-stack.c new file mode 100644 index 00000000000000..cabff7e598eb02 --- /dev/null +++ b/clang/test/CodeGen/RISCV/attr-hw-shadow-stack.c @@ -0,0 +1,9 @@ +// RUN: %clang_cc1 -triple riscv64 -target-feature +experimental-zicfiss -emit-llvm -o - %s -fcf-protection=return | FileCheck %s +// RUN: %clang_cc1 -triple riscv64 -target-feature +experimental-zicfiss -emit-llvm -o - %s | FileCheck -check-prefix=NOSHADOWSTACK %s +// RUN: %clang_cc1 -triple riscv32 -target-feature +experimental-zicfiss -emit-llvm -o - %s -fcf-protection=return | FileCheck %s +// RUN: %clang_cc1 -triple riscv32 -target-feature +experimental-zicfiss -emit-llvm -o - %s | FileCheck -check-prefix=NOSHADOWSTACK %s + +int foo(int *a) { return *a; } + +// CHECK: attributes {{.*}}"hw-shadow-stack"{{.*}} +// NOSHADOWSTACK-NOT: attributes {{.*}}"hw-shadow-stack"{{.*}}