[llvm] [Exegesis][RISCV] Add RISCV support for llvm-exegesis (PR #89047)

Keeran Rothenfusser via llvm-commits llvm-commits at lists.llvm.org
Thu Jul 11 06:25:05 PDT 2024


================
@@ -0,0 +1,100 @@
+//===-- RISCVCounters.cpp ---------------------------------------*- C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines RISC-V perf counters.
+//
+//===----------------------------------------------------------------------===//
+
+#include "RISCVCounters.h"
+
+namespace llvm {
+namespace exegesis {
+
+// This implementation of RISCV target for Exegesis doesn't use libpfm
+// and provides manual implementation of performance counters.
+
+inline uint64_t getRISCVCpuCyclesCount() {
+#if defined(__riscv) && defined(__linux__)
+#if __riscv_xlen == 32
+  uint32_t cycles_lo, cycles_hi0, cycles_hi1;
+  asm volatile("rdcycleh %0\n"
+               "rdcycle %1\n"
+               "rdcycleh %2\n"
+               "sub %0, %0, %2\n"
+               "seqz %0, %0\n"
+               "sub %0, zero, %0\n"
+               "and %1, %1, %0\n"
----------------
keeranroth wrote:

rdcycle can't be used from userspace https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=cc4c07c89aada16229084eeb93895c95b7eabaa3

Also, the code doesn't return the value on low-address overflow

This code does the following:
```
cycles_hi_diff = cycles_hi - cycles_hi1
cycles_hi_same = (cycles_diff == 0) ? 1 : 0
mask = -cycles_hi_same // = -1 if we have read the same hi cycles, otherwise zero
cycles_hi1 &= mask // = cycles_hi1 if we have read the same hi cycles, otherwise zero
```
so if there is an overflow in the low cycles, the hi cycles are zeroed, which means that we assume overflow of the hi part, which isn't the case. The spec (for rv32i) suggests the following:
```
again:
    rdcycleh x3
    rdcycle   x2
    rdcycleh x4
    bne x3, x4, again
```
to read the counter.

https://github.com/llvm/llvm-project/pull/89047


More information about the llvm-commits mailing list