سؤال

When allocating space on the stack using alloca(), is it necessary to clear the memory or is it guaranteed to contain only zeros?

I came up with the following LLVM code. Although it compiles, it leads to a core dump.

In the code I was trying to implement the instantiation of an object and then assigning it to a "member variable".

%Main = type { %A*, i32 }
%A = type { %String, %String }
%String = type { i32, i8* }

define i32 @main() {
body:
  %Main = alloca %Main
  %0 = bitcast %Main* %Main to i8*
  call void @llvm.memset.p0i8.i32(i8* %0, i8 0, i32 4, i32 4, i1 false)
  call void @test(%Main* %Main)
  ret i32 0
}

define void @test(%Main* %self) {
body:
  %0 = load %Main* %self
  %1 = extractvalue %Main %0, 0

  ; Overwrite the object A in Main by a new instance.
  %A = alloca %A

  ; Set to zero.
  %2 = bitcast %A* %A to i8*
  call void @llvm.memset.p0i8.i32(i8* %2, i8 0, i32 4, i32 4, i1 false)

  ; ... execute the constructor of A ...

  ; Set the new instance in Main.
  %3 = load %A* %A
  store %A %3, %A* %1

  br label %return

return:                                           ; preds = %body
  ret void
}

; Function Attrs: nounwind
declare void @llvm.memset.p0i8.i32(i8* nocapture, i8, i32, i32, i1) #0

declare i32 @printf(i8*, ...)
هل كانت مفيدة؟

المحلول

No, memory created with alloca is not 0-initialized - it's up to you to initialize it.

As for the next question, I strongly recommend using Clang to compile C code snippets to LLVM IR instead of hand-crafting the latter. Here's an example:

#include <memory.h>

struct Foo {
  int a, b;
};

void test() {
  Foo f;
  memset(&f, 0, sizeof(f));
}

Compiled (without optimizations) this produces:

%struct.Foo = type { i32, i32 }

; Function Attrs: nounwind uwtable
define void @_Z4testv() #0 {
entry:
  %f = alloca %struct.Foo, align 4
  %0 = bitcast %struct.Foo* %f to i8*
  call void @llvm.memset.p0i8.i64(i8* %0, i8 0, i64 8, i32 4, i1 false)
  ret void
}

; Function Attrs: nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture, i8, i64, i32, i1) #1

attributes #0 = { nounwind uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { nounwind }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top