diff --git a/gcc/config/riscv/riscv-target-attr.cc b/gcc/config/riscv/riscv-target-attr.cc
index 615f1b9c6ce1788174a6f67fe07598e3a955470a..1d968655f95d8c919ce202786ecf8a3da7a8493e 100644
--- a/gcc/config/riscv/riscv-target-attr.cc
+++ b/gcc/config/riscv/riscv-target-attr.cc
@@ -100,6 +100,20 @@ riscv_target_attr_parser::parse_arch (const char *str)
   /* Check if it's setting full arch string.  */
   if (strncmp ("rv", str, strlen ("rv")) == 0)
     {
+      if (TARGET_64BIT && strncmp ("32", str + 2, strlen ("32")) == 0)
+	{
+	  error_at (m_loc, "unexpected arch for %<target()%> attribute: "
+		    "must start with rv64 but found %qs", str);
+	  goto fail;
+	}
+
+      if (!TARGET_64BIT && strncmp ("64", str + 2, strlen ("64")) == 0)
+	{
+	  error_at (m_loc, "unexpected arch for %<target()%> attribute: "
+		    "must start with rv32 but found %qs", str);
+	  goto fail;
+	}
+
       m_subset_list = riscv_subset_list::parse (str, m_loc);
 
       if (m_subset_list == nullptr)
diff --git a/gcc/testsuite/gcc.target/riscv/rvv/base/pr118540-1.c b/gcc/testsuite/gcc.target/riscv/rvv/base/pr118540-1.c
new file mode 100644
index 0000000000000000000000000000000000000000..0b52a7b2ab55235792982207b110c95035054ef1
--- /dev/null
+++ b/gcc/testsuite/gcc.target/riscv/rvv/base/pr118540-1.c
@@ -0,0 +1,12 @@
+/* { dg-do compile { target { rv64 } } } */
+/* { dg-options "-march=rv64gc -mabi=lp64d -O3" { target { rv64 } } } */
+
+long foo (long a, long b)
+__attribute__((target("arch=rv32gcv_zbb")));
+
+long foo (long a, long b)
+{
+  return a + (b * 2);
+}
+
+/* { dg-error "must start with rv64 but found 'rv32gcv_zbb'" "" { target { rv64 } } 0 } */
diff --git a/gcc/testsuite/gcc.target/riscv/rvv/base/pr118540-2.c b/gcc/testsuite/gcc.target/riscv/rvv/base/pr118540-2.c
new file mode 100644
index 0000000000000000000000000000000000000000..d7c4e00cf4d5b15dbb245c66d24acdc32a458b06
--- /dev/null
+++ b/gcc/testsuite/gcc.target/riscv/rvv/base/pr118540-2.c
@@ -0,0 +1,12 @@
+/* { dg-do compile { target { rv32 } } } */
+/* { dg-options "-march=rv32gc -mabi=ilp32d -O3" { target { rv32 } } } */
+
+long foo (long a, long b)
+__attribute__((target("arch=rv64gcv_zbb")));
+
+long foo (long a, long b)
+{
+  return a + (b * 2);
+}
+
+/* { dg-error "must start with rv32 but found 'rv64gcv_zbb'" "" { target { rv32 } } 0 } */