[VM] Fail to compile functions that exceed the block limit of the bytecode format (#25244)

The bytecode encoder does not check the limits that the runtime enforces
when it loads a module. `iree-compile` exits with 0 and writes a `.vmfb`
that then fails to load:

- `block_count` is an `int16` in the function descriptor. A function
with more than 32767 blocks fails in `block_list.c`.
- The runtime verifier rounds the i32 and ref register counts up to a
power of two and compares them with the ISA maximum. A function over the
limit fails with `register count overflow`.

The encoder now reports an error with the count and the limit.

This does not make these modules loadable, it only moves the failure to
compile time. For example, `smollm2` compiled with runtime verification
from MLIR has 34406 blocks in one function and now fails with `function
has 34406 blocks; VM currently restricts functions to 32767 blocks`.

Related to #18923, which has the same runtime error for another model.

AI-assisted.

---------

Signed-off-by: Federico Bruzzone <federico.bruzzone.i@gmail.com>
diff --git a/compiler/src/iree/compiler/Dialect/VM/Target/Bytecode/BytecodeEncoder.cpp b/compiler/src/iree/compiler/Dialect/VM/Target/Bytecode/BytecodeEncoder.cpp
index 7c9ba7d..6a39e4d 100644
--- a/compiler/src/iree/compiler/Dialect/VM/Target/Bytecode/BytecodeEncoder.cpp
+++ b/compiler/src/iree/compiler/Dialect/VM/Target/Bytecode/BytecodeEncoder.cpp
@@ -6,6 +6,8 @@
 
 #include "iree/compiler/Dialect/VM/Target/Bytecode/BytecodeEncoder.h"
 
+#include <limits>
+
 #include "iree/compiler/Dialect/Util/IR/UtilTypes.h"
 #include "iree/compiler/Dialect/VM/Analysis/RegisterAllocation.h"
 #include "iree/compiler/Dialect/VM/IR/VMDialect.h"
@@ -481,9 +483,21 @@
   }
   result.bytecodeData = bytecodeData.value();
   result.bytecodeLength = finalLength;
-  result.blockCount = funcOp.getBlocks().size();
   result.i32RegisterCount = registerAllocation.getMaxI32RegisterOrdinal() + 1;
   result.refRegisterCount = registerAllocation.getMaxRefRegisterOrdinal() + 1;
+
+  // The descriptor stores the block count as an int16. Check the full count
+  // before it is narrowed into the result, and fail instead of silently
+  // truncating it into a module that the runtime misinterprets.
+  constexpr size_t kMaxBlockCount = std::numeric_limits<int16_t>::max();
+  size_t blockCount = funcOp.getBlocks().size();
+  if (blockCount > kMaxBlockCount) {
+    funcOp.emitError() << "function has " << blockCount
+                       << " blocks; VM currently restricts functions to "
+                       << kMaxBlockCount << " blocks";
+    return std::nullopt;
+  }
+  result.blockCount = blockCount;
   return result;
 }