@@ -604,23 +604,23 @@ struct StringConstantOpConv : public OpConversionPattern<StringConstantOp> {
604604 LogicalResult
605605 matchAndRewrite (moore::StringConstantOp op, OpAdaptor adaptor,
606606 ConversionPatternRewriter &rewriter) const override {
607- const auto str = op.getValue ();
608- const unsigned byteWidth = str.size () * 8 ;
609607 const auto resultType =
610608 typeConverter->convertType (op.getResult ().getType ());
611- if (const auto intType = mlir::dyn_cast<IntegerType>(resultType)) {
612- if (intType.getWidth () < byteWidth) {
613- return rewriter.notifyMatchFailure (op,
614- " invalid string constant type size" );
615- }
616- } else {
617- return rewriter.notifyMatchFailure (op, " invalid string constant type" );
618- }
609+ const auto intType = mlir::cast<IntegerType>(resultType);
610+
611+ const auto str = op.getValue ();
612+ const unsigned byteWidth = intType.getWidth ();
619613 APInt value (byteWidth, 0 );
620- for (size_t i = 0 ; i < str.size (); ++i) {
621- const auto asciiChar = static_cast <uint8_t >(str[i]);
622- value |= APInt (byteWidth, asciiChar) << (8 * (str.size () - 1 - i));
614+
615+ // Pack ascii chars from the end of the string, until it fits.
616+ const size_t maxChars =
617+ std::min (str.size (), static_cast <size_t >(byteWidth / 8 ));
618+ for (size_t i = 0 ; i < maxChars; i++) {
619+ const size_t pos = str.size () - 1 - i;
620+ const auto asciiChar = static_cast <uint8_t >(str[pos]);
621+ value |= APInt (byteWidth, asciiChar) << (8 * i);
623622 }
623+
624624 rewriter.replaceOpWithNewOp <hw::ConstantOp>(
625625 op, resultType, rewriter.getIntegerAttr (resultType, value));
626626 return success ();
0 commit comments