Skip to content

[mlir][spirv] Truncate Literal String size at max number words #142916

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions mlir/include/mlir/Target/SPIRV/SPIRVBinaryUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ constexpr uint32_t kMagicNumber = 0x07230203;
/// The serializer tool ID registered to the Khronos Group
constexpr uint32_t kGeneratorNumber = 22;

// Max number of words
constexpr uint32_t kMaxWordCount = 65535;

// Max number of words for literal
constexpr uint32_t kMaxLiteralWordCount = kMaxWordCount - 3;

/// Appends a SPRI-V module header to `header` with the given `version` and
/// `idBound`.
void appendModuleHeader(SmallVectorImpl<uint32_t> &header,
Expand Down
16 changes: 15 additions & 1 deletion mlir/lib/Target/SPIRV/SPIRVBinaryUtils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
#include "mlir/Target/SPIRV/SPIRVBinaryUtils.h"
#include "mlir/Dialect/SPIRV/IR/SPIRVTypes.h"
#include "llvm/Config/llvm-config.h" // for LLVM_VERSION_MAJOR
#include "llvm/Support/Debug.h"

#define DEBUG_TYPE "spirv-binary-utils"

using namespace mlir;

Expand Down Expand Up @@ -68,7 +71,18 @@ void spirv::encodeStringLiteralInto(SmallVectorImpl<uint32_t> &binary,
StringRef literal) {
// We need to encode the literal and the null termination.
auto encodingSize = literal.size() / 4 + 1;
auto sizeOfDataToCopy = literal.size();
if (encodingSize >= kMaxLiteralWordCount) {
// reserve one word for the null termination
encodingSize = kMaxLiteralWordCount - 1;
// do not override the last word (null termination) when copying
sizeOfDataToCopy = (encodingSize - 1) * 4;
LLVM_DEBUG(llvm::dbgs() << "Truncating string literal to max size ("
<< std::to_string(kMaxLiteralWordCount - 1)
<< "): " << literal << "\n");
}
auto bufferStartSize = binary.size();
binary.resize(bufferStartSize + encodingSize, 0);
std::memcpy(binary.data() + bufferStartSize, literal.data(), literal.size());
std::memcpy(binary.data() + bufferStartSize, literal.data(),
sizeOfDataToCopy);
}