Skip to content

Inefficient codegen when accessing a vector with literal indices #50759

@jethrogb

Description

@jethrogb
use std::fs::{read, write};

fn main() -> Result<(), std::io::Error> {
    let h = read("/tmp/test")?;
    let b = [h[0], h[1], h[ 2], h[ 3], h[ 4], h[ 5], h[ 6], h[ 7], h[8], h[9], h[10], h[11], h[12], h[13], h[14], h[15]];
    write("/tmp/test", &b)?;
    Ok(())
}

The let b = ... statement gets compiled to (1.26.0 stable, release mode):

	testq	%rdx, %rdx
	je	.LBB13_109
	cmpq	$1, %rdx
	je	.LBB13_110
	cmpq	$2, %rdx
	jbe	.LBB13_111
	cmpq	$3, %rdx
	je	.LBB13_112
	cmpq	$4, %rdx
	jbe	.LBB13_113
	cmpq	$5, %rdx
	je	.LBB13_114
	cmpq	$6, %rdx
	jbe	.LBB13_115
	cmpq	$7, %rdx
	je	.LBB13_116
	cmpq	$8, %rdx
	jbe	.LBB13_117
	cmpq	$9, %rdx
	je	.LBB13_118
	cmpq	$10, %rdx
	jbe	.LBB13_119
	cmpq	$11, %rdx
	je	.LBB13_120
	cmpq	$12, %rdx
	jbe	.LBB13_121
	cmpq	$13, %rdx
	je	.LBB13_122
	cmpq	$14, %rdx
	jbe	.LBB13_123
	movq	%rbp, 56(%rsp)
	cmpq	$15, %rdx
	je	.LBB13_124
	movq	208(%rsp), %r12
	movb	(%r12), %al
	movb	1(%r12), %cl
	movb	2(%r12), %dl
	movb	3(%r12), %bl
	movb	4(%r12), %sil
	movb	5(%r12), %dil
	movb	6(%r12), %r8b
	movb	7(%r12), %r9b
	movb	8(%r12), %r10b
	movb	9(%r12), %r11b
	movb	10(%r12), %bpl
	movb	11(%r12), %r14b
	movb	12(%r12), %r15b
	movb	13(%r12), %r13b
	movq	%r12, 128(%rsp)
	movzwl	14(%r12), %r12d
	movb	%al, 32(%rsp)
	movb	%cl, 33(%rsp)
	movb	%dl, 34(%rsp)
	movb	%bl, 35(%rsp)
	movb	%sil, 36(%rsp)
	movb	%dil, 37(%rsp)
	movb	%r8b, 38(%rsp)
	movb	%r9b, 39(%rsp)
	movb	%r10b, 40(%rsp)
	movb	%r11b, 41(%rsp)
	movb	%bpl, 42(%rsp)
	movb	%r14b, 43(%rsp)
	movb	%r15b, 44(%rsp)
	movb	%r13b, 45(%rsp)
	movw	%r12w, 46(%rsp)

I was really hoping the optimizer would be able to do a single length check followed by a the equivalent of a memcpy instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-codegenArea: Code generationC-enhancementCategory: An issue proposing an enhancement or a PR with one.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions