Skip to content

Destroy for-loop body locals before the increment - #681

Merged
nunoplopes merged 2 commits into
Cpp2Rust:masterfrom
perfloop-oss:perfloop-pr-open-352mmwgskb
Nov 25, 2026
Merged

nunoplopes merged 2 commits into
Cpp2Rust:masterfrom
perfloop-oss:perfloop-pr-open-352mmwgskb

Conversation

@perfloop-agent

Copy link
Copy Markdown
Contributor

Programs with RAII objects in a for-loop body run the increment before those objects’ destructors in both translation models. This reverses observable side effects and can keep guards alive longer than in C++. The body now has its own drop scope, including when it exits through continue.

In the two-guard loop in tests/unit/for_body_destructor.cpp, destructors print 2 1 and the increment prints 9. Previously each iteration printed 9 2 1; it now prints 2 1 9, for both fallthrough and continue.

A labeled body block lets continue leave the body before reaching the single increment expression. Loop breaks remain directed at the loop, while switch breaks keep their existing targets. Condition variables stay outside the body block and remain alive through the increment; initializer objects retain the enclosing loop scope. Loops without an increment need no extra block. Generated expectations are updated for both models.

This changes the order of emitted destructor guards, not cases where temporary destructors are already missing.

Local reduced-loop timings (rustc -C opt-level=3, 15 interleaved pairs): guard/continue before→after medians were 607.207→579.908 ms (refcount, 20M iterations) and 217.026→61.854 ms (unsafe, 100M). Unsafe guards without continue instead took 124.090→127.997 ms. Destructor-free results were inconclusive; these constructed workloads do not establish application speedups. For the exact 40M-iteration body-local destructor/continue program, 15 interleaved whole-process pairs per model gave local before→after medians of 1,388.633→1,409.003 ms (refcount) and 31.608→32.200 ms (unsafe); both medians increased, but the paired comparisons were inconclusive.

Testing

Linux lit checks of the affected fixtures and control-flow/destructor consumers report 132 passed and 2 expected failures in each of Release and Debug. The changed C++ files pass clang-format 23.

tests/unit/socket_recvfrom_name.c does not pass natively on either revision and is left to target CI. The full check target is left to target CI.

Case and evidence


Made by Perfloop. Human sponsor: Tomás Senart.

Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
@nunoplopes
nunoplopes merged commit a7d4cc9 into Cpp2Rust:master Nov 25, 2026
9 checks passed
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.

2 participants