Repository navigation
Optimize passive segments in memory-packing - #2426
Conversation
When memory is packed and there are passive segments, bulk memory operations that reference those segments by index need to be updated to reflect the new indices and possibly split into multiple instructions that reference multiple split segments. This PR rewrites the memory packing pass to compute and record the transformation scheme for each of the original segments then traverse the module updating bulk memory operations according to these schemes.
| // split segments. | ||
| using Replacement = std::pair<Index, std::vector<Range>>; | ||
|
|
||
| // Maps bulk memory operations to the replacement that must be applied to them. |
There was a problem hiding this comment.
replacement should be plural i think?
| std::vector<std::vector<Expression*>> referers(segments.size()); | ||
|
|
||
| if (module->features.hasBulkMemory()) { | ||
| // Remove any references to active segments that might be invalidated. |
There was a problem hiding this comment.
what does "invalidate an active segment" mean?
There was a problem hiding this comment.
It's the references that might be invalidated by the segments being removed. I'll clarify.
| } else { | ||
| // A single range covers the entire segment | ||
| ranges.push_back( | ||
| Range{.isZero = false, .start = 0, .end = segment.data.size()}); |
There was a problem hiding this comment.
oh when did we get the nice .x=y notation in c++? i thought only c had that...
There was a problem hiding this comment.
https://en.cppreference.com/w/cpp/language/aggregate_initialization Looks like we got it in the future from C++20? I guess clang just allows it as an extension. Maybe we don't want to use it if it's nonstandard.
There was a problem hiding this comment.
Ah, maybe that's why the appveyor build fails then, it's in clang but not msvc? If so I guess we can't use it for now, sadly...
| // A single range covers the entire segment | ||
| ranges.push_back( | ||
| Range{.isZero = false, .start = 0, .end = segment.data.size()}); | ||
| } |
There was a problem hiding this comment.
why can't the singleton Range case have .isZero = true?
There was a problem hiding this comment.
Ranges with .isZero = true are initialized with memory.fill instructions, but that has no benefit if the segment is not being split or eliminated. We therefore go with the more conservative option to use memory.init instructions as before.
There was a problem hiding this comment.
Ah, maybe the name isZero confused me then - I assumed it meant it contained zeroes, and not that fill was used?
There was a problem hiding this comment.
I'll add a comment on the definition of Range clarifying this.
|
This optimization will not be correct until WebAssembly/bulk-memory-operations#124 is resolved. It also won't (or shouldn't) pass the fuzzer until the interpreter is updated to reflect the latest changes from WebAssembly/bulk-memory-operations#123. These are very niche edge cases that should not appear in practice, so I'm not sure merging should be blocked on either or both of those. @kripken thoughts? |
|
"If they don't appear in practice" - what are those cases, specifically? (If it's just stuff like dropping a segment twice, then I think we might want to scan the wasm and abort the pass if we see more than one drop for a segment.) |
|
Unfortunately that’s not sufficient because the drop could be in a loop or in a function that is called twice or something like that. |
|
How important are optimizations that assume things like that don't happen, in your opinion? (If they matter significantly enough, maybe we want to add a flag for "assume reasonable memory usage". Otherwise, maybe not worth it...) |
There was a problem hiding this comment.
Nice! There are some parts I couldn't understand well, in which I asked some questions.
- How about adding a brief summary (maybe 2-3 lines) to the top of the file on what this pass does?
- I think active segments handling and passive segments handling don't share much code (and for small routines they share, we can extract as functions). Can we separate the handling of them in separate functions in the top level function (like,
runcalls two functions namedhandleActiveSegmentsandhandlePassiveSegments)? This will remove manyif (segment.isPassive)s and hopefully make code simpler. WDYT? - Can we remove passive segment ranges that are not referenced by any instructions? (Even if we can, it would better be a separate PR. I'm just asking about the possibility)
|
Thank you for your great comments, @aheejin! |
Binaryen generally tries to preserve program semantics, including traps, but this can complicate or inhibit some optimizations, such as in WebAssembly#2426. Since traps should never occur in a well-behaved program, this PR clarifies a policy of allowing implicit traps to be removed by optimizations.
Specifically, repeated data.drops and data.drops of active segments are now nops instead of traps. But we still need to solve the problem of data.init operations that observe data.drops by trapping being converted into memory.fill instructions that do not trap.
Also updates test that was due to an off-by-one change in how thesholds worked when merging segments. Fixing the behavior change would require using a threshold of 7 (weird) or updating the tests again (more work than is warranted).
Done.
I don't think this would make the code much simpler, but hopefully the decomposition into multiple smaller functions in the current version helps. The reason I don't think this would make the code simpler is that the code for active segments is almost strictly a subset of the code for passive segments, so there aren't many places that have to check the kind of segment to begin with. Separating them out would lead to more duplication than keeping them together.
Yes, this is done by |
| writeSegment(1153, "Cw=="); | ||
| writeSegment(1162, "EQAKChEREQAKAAACAAkLAAAACQALAAAL"); | ||
| writeSegment(1072, "EQAKABEREQAAAAAFAAAAAAAACQAAAAALAAAAAAAAAAARAA8KERERAwoHAAETCQsLAAAJBgsAAAsABhEAAAARERE="); | ||
| writeSegment(1153, "CwAAAAAAAAAAEQAKChEREQAKAAACAAkLAAAACQALAAAL"); |
There was a problem hiding this comment.
This change is due to a change in how the thesholds for merging are used. It used to be that if the number of zeroes was greater or equal to the threshold, they would be optimized out. Now the behavior is that the zeroes are only optimized out if their number is greater than the threshold. Restoring the old behavior and reverting the change to this test would certainly be possible, but would require tweaking almost all of the memory-packing tests, which is much more trouble than it's worth.
| add("inlining-optimizing"); | ||
| } | ||
| // optimizations show more functions as duplicate | ||
| add("memory-packing"); |
There was a problem hiding this comment.
How about putting this in the PrePasses instead of Post? As this affects code, earlier would allow more work potentially.
| size_t end; | ||
| }; | ||
|
|
||
| // A function that produces the transformed bulk memory op |
There was a problem hiding this comment.
Please explain in the comment why a Function is passed as a parameter.
| // Maps each bulk memory op to the replacement that must be applied to it. | ||
| using Replacements = std::unordered_map<Expression*, Replacement>; | ||
|
|
||
| // memory.fill: 2 byte opcode + ~2 immediate bytes + ~(3*2) byte operands |
There was a problem hiding this comment.
what immediate does MemoryFill have? from wasm.h it looks like it just has 3 expression children, and I guess in the binary format maybe it has an immediate for the memory index, but that's 1 byte?
There was a problem hiding this comment.
There is both a segment index immediate and a memory index immediate. I will add a comment to that effect.
There was a problem hiding this comment.
Ah, nevermind, that's memory.init. You're right that memory.fill has only one immediate.
|
|
||
| namespace { | ||
|
|
||
| Expression* makeMemorySize(Builder& builder) { |
There was a problem hiding this comment.
perhaps the name could reflect this is not just making a MemorySize but also shifting it (makeShiftedMemorySize?)
| bool isFunctionParallel() override { return true; } | ||
| Pass* create() override { return new Optimizer; } | ||
|
|
||
| bool needsRefinalizing = false; |
There was a problem hiding this comment.
this is initialized twice, one of them is not needed. i'd remove this one.
| Module* module, std::vector<std::vector<Expression*>>& referrers) { | ||
| using Referrers = std::vector<std::vector<Expression*>>; | ||
| auto collectReferrers = [&](Function* func, Referrers& referrers) { | ||
| if (func->body == nullptr) { |
There was a problem hiding this comment.
this might be clearer as func->imported() (which is used in other places)
|
|
||
| void MemoryPacking::getSegmentReferrers( | ||
| Module* module, std::vector<std::vector<Expression*>>& referrers) { | ||
| using Referrers = std::vector<std::vector<Expression*>>; |
There was a problem hiding this comment.
perhaps this Referrers could be in an earlier place, and help on things like the previous line?
There was a problem hiding this comment.
I placed it at the top, but also changed the definition be be std::vector<Expression*>> because that more broadly useful.
aheejin
left a comment
There was a problem hiding this comment.
Sorry for the delayed reply! I still don't understand some parts very well, so I've added questions. Haven't looked at the tests yet.
| } | ||
|
|
||
| // Handle zero-length memory.inits separately | ||
| if (start == end) { |
There was a problem hiding this comment.
Why does this case need special handling? Even if start != end, if either the segment is dropped or the dest is out of bounds, shouldn't we trap anyway?
There was a problem hiding this comment.
When the length is zero, the start may be one past the end of the segment and firstRangeIdx may be equal to ranges.size(). We handle this case separately so we can assume the start is in bounds and that some range will be intersected, which simplifies subsequent logic. I've updated the comment to reflect this rationale.
There was a problem hiding this comment.
If start is past the end of the segment, shouldn't we have already removed that in MemoryPacking::optimizeBulkMemoryOps?
There was a problem hiding this comment.
If start is more than one past the end, it will have been optimized. But if start is at the end (i.e. one past the end) and the size is zero, then whether or not it will trap depends on the drop state, so it cannot be optimized in optimizeBulkMemoryOps.
aheejin
left a comment
There was a problem hiding this comment.
Had a look at tests and they look very exhaustive!
| (i32.const 0) | ||
| ) | ||
| (data.drop 3) | ||
| ) |
There was a problem hiding this comment.
What does this module test? All four test results look the same so not sure how they are different.
There was a problem hiding this comment.
This module was more relevant before I added the special handling for zero-length segments. It tests that zero-length segments are handled correctly no matter where the offset falls and what the segment looks like.
| } | ||
|
|
||
| // Handle zero-length memory.inits separately | ||
| if (start == end) { |
There was a problem hiding this comment.
If start is past the end of the segment, shouldn't we have already removed that in MemoryPacking::optimizeBulkMemoryOps?
|
Oh and please try running the fuzzer for a while before landing. |
|
The fuzzer cleanly ran just over 1700 iterations with |
When memory is packed and there are passive segments, bulk memory
operations that reference those segments by index need to be updated
to reflect the new indices and possibly split into multiple
instructions that reference multiple split segments.
This PR rewrites the memory packing pass to compute and record the
transformation scheme for each of the original segments then traverse
the module updating bulk memory operations according to these schemes.