[Mlir-commits] [mlir] [mlir]Add size check and skip serialization of large blobs. (PR #213920)
Mehdi Amini
llvmlistbot at llvm.org
Tue Aug 4 05:28:11 PDT 2026
================
@@ -3467,33 +3467,49 @@ class OperationPrinter : public AsmPrinter::Impl, private OpAsmPrinter {
class ResourceBuilder : public AsmResourceBuilder {
public:
using ValueFn = function_ref<void(raw_ostream &)>;
- using PrintFn = function_ref<void(StringRef, ValueFn)>;
+ // `sizeHint` is the exact number of characters `valueFn` will write, or -1
+ // if unknown, so the char limit can be applied before paying the cost of
+ // invoking `valueFn` (e.g. hex-encoding a large blob).
+ using PrintFn = function_ref<void(StringRef, ValueFn, int64_t sizeHint)>;
ResourceBuilder(PrintFn printFn) : printFn(printFn) {}
~ResourceBuilder() override = default;
void buildBool(StringRef key, bool data) final {
- printFn(key, [&](raw_ostream &os) { os << (data ? "true" : "false"); });
+ printFn(
+ key, [&](raw_ostream &os) { os << (data ? "true" : "false"); },
+ /*sizeHint=*/-1);
}
void buildString(StringRef key, StringRef data) final {
- printFn(key, [&](raw_ostream &os) {
- os << "\"";
- llvm::printEscapedString(data, os);
- os << "\"";
- });
+ printFn(
+ key,
+ [&](raw_ostream &os) {
+ os << "\"";
+ llvm::printEscapedString(data, os);
+ os << "\"";
+ },
+ /*sizeHint=*/-1);
}
void buildBlob(StringRef key, ArrayRef<char> data,
uint32_t dataAlignment) final {
- printFn(key, [&](raw_ostream &os) {
- // Store the blob in a hex string containing the alignment and the data.
- llvm::support::ulittle32_t dataAlignmentLE(dataAlignment);
- os << "\"0x"
- << llvm::toHex(StringRef(reinterpret_cast<char *>(&dataAlignmentLE),
- sizeof(dataAlignment)))
- << llvm::toHex(StringRef(data.data(), data.size())) << "\"";
- });
+ // Two hex chars per byte of the alignment word and the data, plus the
+ // `"0x`/`"` wrapping; exact, so the limit can be checked pre-encoding.
+ int64_t sizeHint = 2 * int64_t(sizeof(dataAlignment) + data.size()) + 4;
+ printFn(
+ key,
+ [&](raw_ostream &os) {
+ // Store the blob in a hex string containing the alignment and the
+ // data.
+ llvm::support::ulittle32_t dataAlignmentLE(dataAlignment);
+ os << "\"0x"
+ << llvm::toHex(
+ StringRef(reinterpret_cast<char *>(&dataAlignmentLE),
+ sizeof(dataAlignment)))
+ << llvm::toHex(StringRef(data.data(), data.size())) << "\"";
+ },
+ sizeHint);
}
----------------
joker-eph wrote:
Can you say a bit more on why is the change in this function related?
https://github.com/llvm/llvm-project/pull/213920
More information about the Mlir-commits
mailing list