Skip to content

Optimize passive segments in memory-packing - #2426

Merged
tlively merged 26 commits into
WebAssembly:masterfrom
tlively:passive-memory-packing
Jan 15, 2020
Merged

tlively merged 26 commits into
WebAssembly:masterfrom
tlively:passive-memory-packing

Conversation

@tlively

@tlively tlively commented Nov 8, 2019

Copy link
Copy Markdown
Member

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.

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.
@tlively
tlively requested review from aheejin and kripken November 8, 2019 00:53

@kripken kripken left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some initial comments.

Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Outdated
// split segments.
using Replacement = std::pair<Index, std::vector<Range>>;

// Maps bulk memory operations to the replacement that must be applied to them.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

replacement should be plural i think?

Comment thread src/passes/MemoryPacking.cpp Outdated
std::vector<std::vector<Expression*>> referers(segments.size());

if (module->features.hasBulkMemory()) {
// Remove any references to active segments that might be invalidated.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

what does "invalidate an active segment" mean?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It's the references that might be invalidated by the segments being removed. I'll clarify.

Comment thread src/passes/MemoryPacking.cpp Outdated
} else {
// A single range covers the entire segment
ranges.push_back(
Range{.isZero = false, .start = 0, .end = segment.data.size()});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

oh when did we get the nice .x=y notation in c++? i thought only c had that...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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...

Comment thread src/passes/MemoryPacking.cpp Outdated
// A single range covers the entire segment
ranges.push_back(
Range{.isZero = false, .start = 0, .end = segment.data.size()});
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why can't the singleton Range case have .isZero = true?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah, maybe the name isZero confused me then - I assumed it meant it contained zeroes, and not that fill was used?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'll add a comment on the definition of Range clarifying this.

@tlively

tlively commented Nov 8, 2019

Copy link
Copy Markdown
Member Author

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?

@kripken

kripken commented Nov 11, 2019

Copy link
Copy Markdown
Member

"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.)

@tlively

tlively commented Nov 11, 2019

Copy link
Copy Markdown
Member Author

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.

@kripken

kripken commented Nov 12, 2019

Copy link
Copy Markdown
Member

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...)

@aheejin aheejin left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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, run calls two functions named handleActiveSegments and handlePassiveSegments)? This will remove many if (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)

Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
@tlively

tlively commented Nov 12, 2019

Copy link
Copy Markdown
Member Author

Thank you for your great comments, @aheejin!

tlively added a commit to tlively/binaryen that referenced this pull request Nov 13, 2019
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).
@tlively

tlively commented Jan 7, 2020

Copy link
Copy Markdown
Member Author

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?

Done.

  • 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, run calls two functions named handleActiveSegments and handlePassiveSegments)? This will remove many if (segment.isPassive)s and hopefully make code simpler. WDYT?

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.

  • 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)

Yes, this is done by dropUnusedSegments. It was relatively simple compared to everything else in the PR, so I believe this functionality has been there for a while.

@tlively

tlively commented Jan 7, 2020

Copy link
Copy Markdown
Member Author

@kripken @aheejin This should be good to go pending final review. I'm running the fuzzer locally as well.

writeSegment(1153, "Cw==");
writeSegment(1162, "EQAKChEREQAKAAACAAkLAAAACQALAAAL");
writeSegment(1072, "EQAKABEREQAAAAAFAAAAAAAACQAAAAALAAAAAAAAAAARAA8KERERAwoHAAETCQsLAAAJBgsAAAsABhEAAAARERE=");
writeSegment(1153, "CwAAAAAAAAAAEQAKChEREQAKAAACAAkLAAAACQALAAAL");

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread src/passes/pass.cpp Outdated
add("inlining-optimizing");
}
// optimizations show more functions as duplicate
add("memory-packing");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

How about putting this in the PrePasses instead of Post? As this affects code, earlier would allow more work potentially.

Comment thread src/passes/MemoryPacking.cpp Outdated
size_t end;
};

// A function that produces the transformed bulk memory op

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please explain in the comment why a Function is passed as a parameter.

Comment thread src/passes/MemoryPacking.cpp Outdated
// 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

There is both a segment index immediate and a memory index immediate. I will add a comment to that effect.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ah, nevermind, that's memory.init. You're right that memory.fill has only one immediate.

Comment thread src/passes/MemoryPacking.cpp Outdated

namespace {

Expression* makeMemorySize(Builder& builder) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

perhaps the name could reflect this is not just making a MemorySize but also shifting it (makeShiftedMemorySize?)

Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Outdated
bool isFunctionParallel() override { return true; }
Pass* create() override { return new Optimizer; }

bool needsRefinalizing = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this is initialized twice, one of them is not needed. i'd remove this one.

Comment thread src/passes/MemoryPacking.cpp Outdated
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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this might be clearer as func->imported() (which is used in other places)

Comment thread src/passes/MemoryPacking.cpp Outdated

void MemoryPacking::getSegmentReferrers(
Module* module, std::vector<std::vector<Expression*>>& referrers) {
using Referrers = std::vector<std::vector<Expression*>>;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

perhaps this Referrers could be in an earlier place, and help on things like the previous line?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I placed it at the top, but also changed the definition be be std::vector<Expression*>> because that more broadly useful.

@aheejin aheejin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment thread src/asm2wasm.h Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
}

// Handle zero-length memory.inits separately
if (start == end) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If start is past the end of the segment, shouldn't we have already removed that in MemoryPacking::optimizeBulkMemoryOps?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved
Comment thread src/passes/MemoryPacking.cpp Resolved

@aheejin aheejin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Had a look at tests and they look very exhaustive!

(i32.const 0)
)
(data.drop 3)
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What does this module test? All four test results look the same so not sure how they are different.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@tlively

tlively commented Jan 14, 2020

Copy link
Copy Markdown
Member Author

@kripken @aheejin I believe all feedback has now been addressed.

@kripken kripken left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, nice!

@aheejin aheejin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM!

}

// Handle zero-length memory.inits separately
if (start == end) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If start is past the end of the segment, shouldn't we have already removed that in MemoryPacking::optimizeBulkMemoryOps?

@aheejin

aheejin commented Jan 15, 2020

Copy link
Copy Markdown
Member

Oh and please try running the fuzzer for a while before landing.

@tlively

tlively commented Jan 15, 2020

Copy link
Copy Markdown
Member Author

The fuzzer cleanly ran just over 1700 iterations with bulk-memory enabled for all of them.

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