-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Reduce generated code size for Row Constructors #21299
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
pettyjamesm
merged 1 commit into
trinodb:master
from
Bhargavi-Sagi:rowconstructor-codegen-fix
Apr 10, 2024
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,30 +18,38 @@ | |
import io.airlift.bytecode.Scope; | ||
import io.airlift.bytecode.Variable; | ||
import io.airlift.bytecode.control.IfStatement; | ||
import io.trino.annotation.UsedByGeneratedCode; | ||
import io.trino.spi.block.Block; | ||
import io.trino.spi.block.BlockBuilder; | ||
import io.trino.spi.block.BlockBuilderStatus; | ||
import io.trino.spi.block.SqlRow; | ||
import io.trino.spi.type.RowType; | ||
import io.trino.spi.type.Type; | ||
import io.trino.sql.relational.RowExpression; | ||
import io.trino.sql.relational.SpecialForm; | ||
|
||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
|
||
import static io.airlift.bytecode.ParameterizedType.type; | ||
import static io.airlift.bytecode.expression.BytecodeExpressions.constantFalse; | ||
import static io.airlift.bytecode.expression.BytecodeExpressions.constantInt; | ||
import static io.airlift.bytecode.expression.BytecodeExpressions.constantNull; | ||
import static io.airlift.bytecode.expression.BytecodeExpressions.invokeStatic; | ||
import static io.airlift.bytecode.expression.BytecodeExpressions.newArray; | ||
import static io.airlift.bytecode.expression.BytecodeExpressions.newInstance; | ||
import static io.trino.sql.gen.SqlTypeBytecodeExpression.constantType; | ||
import static java.lang.String.format; | ||
import static java.util.Objects.requireNonNull; | ||
|
||
public class RowConstructorCodeGenerator | ||
implements BytecodeGenerator | ||
{ | ||
private final Type rowType; | ||
private final List<RowExpression> arguments; | ||
// Arbitrary value chosen to balance the code size vs performance trade off. Not perf tested. | ||
private static final int MEGAMORPHIC_FIELD_COUNT = 64; | ||
|
||
public RowConstructorCodeGenerator(SpecialForm specialForm) | ||
{ | ||
|
@@ -53,6 +61,10 @@ public RowConstructorCodeGenerator(SpecialForm specialForm) | |
@Override | ||
public BytecodeNode generateExpression(BytecodeGeneratorContext context) | ||
{ | ||
if (arguments.size() > MEGAMORPHIC_FIELD_COUNT) { | ||
return generateExpressionForLargeRows(context); | ||
} | ||
|
||
BytecodeBlock block = new BytecodeBlock().setDescription("Constructor for " + rowType); | ||
CallSiteBinder binder = context.getCallSiteBinder(); | ||
Scope scope = context.getScope(); | ||
|
@@ -88,4 +100,67 @@ public BytecodeNode generateExpression(BytecodeGeneratorContext context) | |
block.append(context.wasNull().set(constantFalse())); | ||
return block; | ||
} | ||
|
||
// Avoids inline BlockBuilder and Block creation logic for each field which reduces the generated code size | ||
// for RowTypes with many fields significantly, but does so at the cost of virtual method dispatch | ||
private BytecodeNode generateExpressionForLargeRows(BytecodeGeneratorContext context) | ||
{ | ||
BytecodeBlock block = new BytecodeBlock().setDescription("Constructor for " + rowType); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you add a comment on how this is different from the above code. Specifically touch on where we get less byte code and why the performance is not as good as above (otherwise we would use the same code for both). |
||
CallSiteBinder binder = context.getCallSiteBinder(); | ||
Scope scope = context.getScope(); | ||
List<Type> types = rowType.getTypeParameters(); | ||
|
||
Variable fieldBuilders = scope.createTempVariable(BlockBuilder[].class); | ||
block.append(fieldBuilders.set(invokeStatic(RowConstructorCodeGenerator.class, "createFieldBlockBuildersForSingleRow", BlockBuilder[].class, constantType(binder, rowType)))); | ||
|
||
// Cache local variable declarations per java type on stack for reuse | ||
Map<Class<?>, Variable> javaTypeTempVariables = new HashMap<>(); | ||
Variable blockBuilder = scope.createTempVariable(BlockBuilder.class); | ||
for (int i = 0; i < arguments.size(); ++i) { | ||
Type fieldType = types.get(i); | ||
Variable field = javaTypeTempVariables.computeIfAbsent(fieldType.getJavaType(), scope::createTempVariable); | ||
|
||
block.append(blockBuilder.set(fieldBuilders.getElement(constantInt(i)))); | ||
dain marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
block.comment("Clean wasNull and Generate + " + i + "-th field of row"); | ||
block.append(context.wasNull().set(constantFalse())); | ||
block.append(context.generate(arguments.get(i))); | ||
block.putVariable(field); | ||
block.append(new IfStatement() | ||
.condition(context.wasNull()) | ||
.ifTrue(blockBuilder.invoke("appendNull", BlockBuilder.class).pop()) | ||
.ifFalse(constantType(binder, fieldType).writeValue(blockBuilder, field).pop())); | ||
} | ||
|
||
block.append(invokeStatic(RowConstructorCodeGenerator.class, "createSqlRowFromFieldBuildersForSingleRow", SqlRow.class, fieldBuilders)); | ||
block.append(context.wasNull().set(constantFalse())); | ||
return block; | ||
} | ||
|
||
@UsedByGeneratedCode | ||
public static BlockBuilder[] createFieldBlockBuildersForSingleRow(Type rowType) | ||
{ | ||
if (!(rowType instanceof RowType)) { | ||
throw new IllegalArgumentException("Not a row type: " + rowType); | ||
} | ||
List<Type> fieldTypes = rowType.getTypeParameters(); | ||
BlockBuilder[] fieldBlockBuilders = new BlockBuilder[fieldTypes.size()]; | ||
for (int i = 0; i < fieldTypes.size(); i++) { | ||
fieldBlockBuilders[i] = fieldTypes.get(i).createBlockBuilder(null, 1); | ||
} | ||
return fieldBlockBuilders; | ||
} | ||
|
||
@UsedByGeneratedCode | ||
public static SqlRow createSqlRowFromFieldBuildersForSingleRow(BlockBuilder[] fieldBuilders) | ||
{ | ||
Block[] fieldBlocks = new Block[fieldBuilders.length]; | ||
for (int i = 0; i < fieldBuilders.length; i++) { | ||
fieldBlocks[i] = fieldBuilders[i].build(); | ||
if (fieldBlocks[i].getPositionCount() != 1) { | ||
throw new IllegalArgumentException(format("builder must only contain a single position, found: %s positions", fieldBlocks[i].getPositionCount())); | ||
} | ||
} | ||
return new SqlRow(0, fieldBlocks); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would assume this value is arbitrary and not perf tested. If so, we should comment here, so people don't assume 64 is the best value.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, the value is taken from a constant by the same name in
RowType
, but unlike that variation was not specifically arrived at by testing for performance but rather was chosen based on seeming reasonable to balance the code size vs performance trade off (ie: mostly arbitrary). We can add a comment to that effect.