Skip to content

Inefficient codegen for function returning String #34861

Closed
@jrmuizel

Description

@jrmuizel

The following code seems generate inefficient code compared to the C++ equivalent:

pub fn goo() -> String {
    let url_prefix = "https://".to_string();
    url_prefix
}

gives:

define void @_ZN8rust_out3goo17h4b78ef91328cd5a8E(%"3.std::string::String"* noalias nocapture sret dereferenceable(24)) unnamed_addr #0 personality i32 (i32, i32, i64, %"8.unwind::libunwind::_Unwind_Exception"*, %"8.unwind::libunwind::_Unwind_Context"*)* @rust_eh_personality {
_ZN19std..string..String9drop.734817h847d71ab7fd1dc50E.exit:
  %url_prefix = alloca %"3.std::string::String", align 8
  %1 = bitcast %"3.std::string::String"* %url_prefix to i8*
  call void @llvm.lifetime.start(i64 24, i8* %1)
  call void @"_ZN80_$LT$string..String$u20$as$u20$core..convert..From$LT$$RF$$u27$a$u20$str$GT$$GT$4from17hfac1f2dc216f571bE"(%"3.std::string::String"* noalias nocapture nonnull sret dereferenceable(24) %url_prefix, i8* noalias nonnull readonly getelementptr inbounds ([8 x i8], [8 x i8]* @str7345, i64 0, i64 0), i64 8)
  %2 = bitcast %"3.std::string::String"* %0 to i8*
  call void @llvm.memcpy.p0i8.p0i8.i64(i8* %2, i8* %1, i64 24, i32 8, i1 false)
  call void @llvm.lifetime.end(i64 24, i8* %1)
  ret void
}

vs.

define void @_Z3goov(%"class.std::__1::basic_string"* noalias sret %agg.result) #0 {
  tail call void @_ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm(%"class.std::__1::basic_string"* %agg.result, i8* getelementptr inbounds ([56 x i8]* @.str, i64 0, i64 0), i64 55)
  ret void
}

The rust code has an additional alloca and a memcpy

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions