Skip to content

[RISC-V RVV] Prune redundant mempy and ensure max memcpy length#1921

Merged
Dead2 merged 1 commit intozlib-ng:developfrom
chLFF:rvv-optimize-chunkcopy
Jun 25, 2025
Merged

[RISC-V RVV] Prune redundant mempy and ensure max memcpy length#1921
Dead2 merged 1 commit intozlib-ng:developfrom
chLFF:rvv-optimize-chunkcopy

Conversation

@chLFF
Copy link
Copy Markdown

@chLFF chLFF commented Jun 7, 2025

Optimize chunkcopy_rvv:

  1. Skip aligning memcpy when dist >= len. Obviously aligning memcpy is redundant when dist >= len which contains extra very slow load&store instrutions. And I noticed that dist is way larger than len in most cases by adding printf in chunkcopy_rvv with apt install (very narrow situation but makes sense). So I tend to move the comparing before aligning memcpy since it is only needed by the overlap situation.

  2. Make the largest copy while len > dist. Chunkcopy_rvv only copies as much memory as possible once after aligning memcpy then uses sizeof(chunk_t) to finish the rest copying. However, we should do the largest copy as long as len < dist.

Summary by CodeRabbit

  • Refactor
    • Improved the internal logic for memory copying when source and destination buffers overlap, optimizing the copying process for better efficiency. No changes to visible functionality or public interfaces.

1. Skip aligning memcpy when dist >= len.
Obviously aligning memcpy is redundant when dist >= len which
contains extra very slow load&store instrutions. And I noticed
that dist is way larger than len in most cases by adding printf in
chunkcopy_rvv with apt install (very narrow situation but makes
sense). So I tend to move the comparing before aligning memcpy
since it is only needed by the overlap situation.

2. Make the largest copy while len > dist.
Chunkcopy_rvv only copies as much memory as possible once after
aligning memcpy then uses sizeof(chunk_t) to finish the rest
copying. However, we should do the largest copy as long as
len < dist.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 7, 2025

Walkthrough

The CHUNKCOPY function in the RISC-V vector chunkset implementation was refactored to change how overlapping memory regions are handled. The logic now uses a loop to copy chunk-sized blocks when overlap is detected, with alignment and tail copying adjusted accordingly. No public interfaces were changed.

Changes

File(s) Change Summary
arch/riscv/chunkset_rvv.c Refactored CHUNKCOPY function: revised overlap handling, replaced sequential memcpy with a loop, and adjusted alignment/tail copy logic. No signature changes.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant CHUNKCOPY

    Caller->>CHUNKCOPY: Call CHUNKCOPY(out, from, len)
    alt No overlap
        CHUNKCOPY->>CHUNKCOPY: memcpy(out, from, len)
    else Overlap detected
        CHUNKCOPY->>CHUNKCOPY: Calculate alignment (vl)
        CHUNKCOPY->>CHUNKCOPY: memcpy initial aligned chunk
        loop While len > distance
            CHUNKCOPY->>CHUNKCOPY: memcpy chunk of size vl
        end
        CHUNKCOPY->>CHUNKCOPY: memcpy remaining bytes
    end
    CHUNKCOPY-->>Caller: Return
Loading

Possibly related PRs

  • riscv: chunkset_rvv: fix SIGSEGV in CHUNKCOPY #1889: Both PRs modify the CHUNKCOPY function in arch/riscv/chunkset_rvv.c to improve handling of overlapping memory regions and pointer distance checks, with the main PR refactoring the copy logic flow and the retrieved PR fixing a SIGSEGV by adjusting the distance condition to handle negative values correctly.
  • Improve pipeling for AVX512 chunking #1821: The main PR refactors the overlap handling and copying loop logic in the CHUNKCOPY function for RISC-V vector extension, while the retrieved PR improves remainder handling and masked load/store operations in CHUNKCOPY for AVX512 on x86, so both modify CHUNKCOPY but in different architectures and with different focus areas.

Suggested labels

optimization, Architecture

Suggested reviewers

  • Dead2
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
arch/riscv/chunkset_rvv.c (1)

103-109: Consider recalculating copy size in each iteration for optimal performance.

The current implementation uses a fixed vl size throughout the loop. According to the PR objectives, you want to "ensure that the largest possible memory copy is performed while len is greater than dist." As len decreases in each iteration, the safe copy size might change.

Consider recalculating the maximum safe copy size in each iteration:

-    size_t vl = (dist / sizeof(chunk_t)) * sizeof(chunk_t);
-    while (len > dist) {
-        memcpy(out, from, vl);
-        out += vl;
-        from += vl;
-        len -= vl;
+    while (len > dist) {
+        size_t copy_size = (dist / sizeof(chunk_t)) * sizeof(chunk_t);
+        if (copy_size == 0) copy_size = dist;
+        memcpy(out, from, copy_size);
+        out += copy_size;
+        from += copy_size;
+        len -= copy_size;
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c98ece and babb60e.

📒 Files selected for processing (1)
  • arch/riscv/chunkset_rvv.c (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
arch/riscv/chunkset_rvv.c (2)
Learnt from: KungFuJesus
PR: zlib-ng/zlib-ng#1802
File: chunkset_tpl.h:92-108
Timestamp: 2024-10-07T22:00:02.180Z
Learning: In the `HALFCHUNKCOPY` function in `chunkset_tpl.h`, the `len` parameter is always bound to be small by the callers and will not exceed the limits of an `int32_t`.
Learnt from: KungFuJesus
PR: zlib-ng/zlib-ng#1802
File: chunkset_tpl.h:92-108
Timestamp: 2024-10-08T19:37:14.998Z
Learning: In the `HALFCHUNKCOPY` function in `chunkset_tpl.h`, the `len` parameter is always bound to be small by the callers and will not exceed the limits of an `int32_t`.

Comment on lines +103 to +104
size_t vl = (dist / sizeof(chunk_t)) * sizeof(chunk_t);
while (len > dist) {
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot Jun 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Ensure vl is non-zero to avoid ineffective loop.

When dist < sizeof(chunk_t), the calculation (dist / sizeof(chunk_t)) * sizeof(chunk_t) results in vl = 0, making the while loop ineffective. This could lead to performance degradation as no bytes would be copied in the loop.

Consider ensuring a minimum copy size:

-    size_t vl = (dist / sizeof(chunk_t)) * sizeof(chunk_t);
+    size_t vl = dist < sizeof(chunk_t) ? dist : (dist / sizeof(chunk_t)) * sizeof(chunk_t);
🤖 Prompt for AI Agents
In arch/riscv/chunkset_rvv.c around lines 103 to 104, the variable vl can be
zero when dist is less than sizeof(chunk_t), causing the while loop to be
ineffective and potentially degrade performance. Modify the calculation of vl to
ensure it is never zero by setting a minimum value of sizeof(chunk_t) when the
computed vl would be zero, so the loop copies at least one chunk each iteration.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When len is more than dist, it makes no sense to copy more than len bytes as the remaining bytes are undefined, thus the code falls back to using memcpy which can handle both overlapping copy and remaining bytes after reading full chunks worth of data. len must be at least as much as size of chunk_t type after aligning for chunked copy to work correctly and not cause buffer overrun.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mtl1979 Thank you for the clarification! You're absolutely right, and I apologize for the incorrect suggestion.

The behavior where vl = 0 when dist < sizeof(chunk_t) is indeed intentional and correct. When the distance is smaller than a chunk size, it's not safe to copy full chunks, so the while loop appropriately doesn't execute and the function falls back to using memcpy for the remaining bytes. This aligns with the existing learning about the deliberate alignment optimization in this function.

The logic is well-designed: the function only attempts to copy full chunk-sized blocks when it's safe to do so (when dist >= sizeof(chunk_t)), and otherwise relies on memcpy to handle the overlapping copy correctly.


✏️ Learnings added
Learnt from: mtl1979
PR: zlib-ng/zlib-ng#1921
File: arch/riscv/chunkset_rvv.c:103-104
Timestamp: 2025-06-10T07:38:03.285Z
Learning: In RISC-V chunkset_rvv.c CHUNKCOPY function, when dist < sizeof(chunk_t), the vl variable intentionally becomes 0, causing the while loop to not execute. This is correct behavior because copying full chunks is not safe when the distance is smaller than chunk size, and the function appropriately falls back to memcpy for handling remaining bytes.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: mtl1979
PR: zlib-ng/zlib-ng#1921
File: arch/riscv/chunkset_rvv.c:97-102
Timestamp: 2025-06-09T16:46:28.443Z
Learning: In RISC-V chunkset_rvv.c CHUNKCOPY function, the alignment logic intentionally copies sizeof(chunk_t) bytes but advances pointers by align bytes to avoid unaligned access. This "re-reading" technique is a deliberate optimization to maintain proper alignment for subsequent operations, not a bug.

Learnt from: KungFuJesus
PR: zlib-ng/zlib-ng#1802
File: chunkset_tpl.h:92-108
Timestamp: 2024-10-07T22:00:02.180Z
Learning: In the `HALFCHUNKCOPY` function in `chunkset_tpl.h`, the `len` parameter is always bound to be small by the callers and will not exceed the limits of an `int32_t`.

Learnt from: KungFuJesus
PR: zlib-ng/zlib-ng#1802
File: chunkset_tpl.h:92-108
Timestamp: 2024-10-08T19:37:14.998Z
Learning: In the `HALFCHUNKCOPY` function in `chunkset_tpl.h`, the `len` parameter is always bound to be small by the callers and will not exceed the limits of an `int32_t`.

Comment on lines +97 to +102
int32_t align = ((len - 1) % sizeof(chunk_t)) + 1;
memcpy(out, from, sizeof(chunk_t));
out += align;
from += align;
len -= align;

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot Jun 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the alignment logic to prevent buffer corruption.

The current implementation has a critical issue: it copies sizeof(chunk_t) bytes but advances the pointers by align bytes, which can be different values. This causes incorrect memory copying when align != sizeof(chunk_t).

For example, if len = 33 and sizeof(chunk_t) = 32:

  • align = ((33 - 1) % 32) + 1 = 1
  • The code copies 32 bytes but only advances pointers by 1 byte
  • This results in re-reading already copied data and potential buffer corruption

Consider this fix to ensure consistent copy size and pointer advancement:

-    int32_t align = ((len - 1) % sizeof(chunk_t)) + 1;
-    memcpy(out, from, sizeof(chunk_t));
-    out += align;
-    from += align;
-    len -= align;
+    size_t copy_size = (len < sizeof(chunk_t)) ? len : sizeof(chunk_t);
+    memcpy(out, from, copy_size);
+    out += copy_size;
+    from += copy_size;
+    len -= copy_size;
🤖 Prompt for AI Agents
In arch/riscv/chunkset_rvv.c around lines 97 to 102, the code copies
sizeof(chunk_t) bytes but advances the pointers by align bytes, causing buffer
corruption when align differs from sizeof(chunk_t). To fix this, ensure that the
number of bytes copied and the pointer increments are consistent by using the
same value for both operations, either copying and advancing by align bytes or
by sizeof(chunk_t) bytes, depending on the intended behavior.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reading is intended, it avoids unaligned access.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mtl1979 Thank you for the clarification! You're absolutely right - this is an intentional alignment optimization technique. I apologize for flagging this as a potential issue.

The code deliberately copies sizeof(chunk_t) bytes but advances pointers by only align bytes to ensure proper alignment for subsequent memory operations. This "re-reading" approach is a common optimization in high-performance memory copy functions, especially on architectures like RISC-V where unaligned access can be costly.

I appreciate you taking the time to explain the intent behind this implementation.


✏️ Learnings added
Learnt from: mtl1979
PR: zlib-ng/zlib-ng#1921
File: arch/riscv/chunkset_rvv.c:97-102
Timestamp: 2025-06-09T16:46:28.443Z
Learning: In RISC-V chunkset_rvv.c CHUNKCOPY function, the alignment logic intentionally copies sizeof(chunk_t) bytes but advances pointers by align bytes to avoid unaligned access. This "re-reading" technique is a deliberate optimization to maintain proper alignment for subsequent operations, not a bug.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@codecov
Copy link
Copy Markdown

codecov bot commented Jun 10, 2025

Codecov Report

Attention: Patch coverage is 91.66667% with 1 line in your changes missing coverage. Please review.

Project coverage is 81.77%. Comparing base (2c98ece) to head (babb60e).
Report is 4 commits behind head on develop.

Files with missing lines Patch % Lines
arch/riscv/chunkset_rvv.c 91.66% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1921      +/-   ##
===========================================
- Coverage    81.78%   81.77%   -0.01%     
===========================================
  Files          147      147              
  Lines        13321    13319       -2     
  Branches      2955     2954       -1     
===========================================
- Hits         10894    10892       -2     
+ Misses        1511     1499      -12     
- Partials       916      928      +12     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@mtl1979
Copy link
Copy Markdown
Collaborator

mtl1979 commented Jun 17, 2025

This most likely needs a rebase to rerun failed CI checks. At least those MSVC 2019 workflows should then pass as no relevant changes are in this PR.

Copy link
Copy Markdown
Member

@Dead2 Dead2 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Dead2 Dead2 merged commit 962ab42 into zlib-ng:develop Jun 25, 2025
137 of 146 checks passed
@Dead2 Dead2 mentioned this pull request Nov 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants