wasm-emscripten-finalize: Allow optional running of memory-packing

This would normally run during wasm-opt but when we write out the
memory file during wasm-emscripten-finalize we loose the ability to
run this later.

Ideally the writing out of the memory file would be delayed until after
finalize has been run but that is a bigger change.
diff --git a/src/tools/wasm-emscripten-finalize.cpp b/src/tools/wasm-emscripten-finalize.cpp
index 99d03ce..d506341 100644
--- a/src/tools/wasm-emscripten-finalize.cpp
+++ b/src/tools/wasm-emscripten-finalize.cpp
@@ -59,6 +59,7 @@
   bool minimizeWasmChanges = false;
   bool noDynCalls = false;
   bool onlyI64DynCalls = false;
+  bool memoryPacking = false;
 
   const std::string WasmEmscriptenFinalizeOption =
     "wasm-emscripten-finalize options";
@@ -200,6 +201,14 @@
          [&onlyI64DynCalls](Options* o, const std::string&) {
            onlyI64DynCalls = true;
          })
+    .add("--pack-memory",
+         "",
+         "Pack memory segments before writing out memory file",
+         WasmEmscriptenFinalizeOption,
+         Options::Arguments::Zero,
+         [&memoryPacking](Options*, const std::string&) {
+           memoryPacking = true;
+         })
     .add_positional("INFILE",
                     Options::Arguments::One,
                     [&infile](Options* o, const std::string& argument) {
@@ -295,6 +304,16 @@
     passRunner.add("strip-dwarf");
   }
 
+  // If we are going to write out the memory to file, add
+  // `--zero-filled-memory` was passed then run the memory packing
+  // pass now, before we write out the file.
+  // TODO(sbc): Move the writing of the memory file to a later phase
+  // and remove this option.
+  if (!dataSegmentFile.empty() && memoryPacking) {
+    passRunner.options.zeroFilledMemory = true;
+    passRunner.add("memory-packing");
+  }
+
   passRunner.run();
 
   // Finally, separate out data segments if relevant
diff --git a/test/lit/help/wasm-emscripten-finalize.test b/test/lit/help/wasm-emscripten-finalize.test
index 5ca1c9c..ea42d02 100644
--- a/test/lit/help/wasm-emscripten-finalize.test
+++ b/test/lit/help/wasm-emscripten-finalize.test
@@ -61,6 +61,9 @@
 ;; CHECK-NEXT:
 ;; CHECK-NEXT:   --dyncalls-i64
 ;; CHECK-NEXT:
+;; CHECK-NEXT:   --pack-memory                       Pack memory segments before writing out
+;; CHECK-NEXT:                                       memory file
+;; CHECK-NEXT:
 ;; CHECK-NEXT:
 ;; CHECK-NEXT: Tool options:
 ;; CHECK-NEXT: -------------