Search code examples
compiler-constructionllvmcode-generationllvm-ir

llvm ir not behaving as expected


I have the following llvm ir and having spent the best part of the day trying to debug it I cannot seem to get a handle on it. The program simply freezes (with) segfault at the loop when run on my windows machine.

; standard declaration etc
%gen__list__0 = type { i8*, i64, i64 }
%const_array_offset = type { i64, i64 }
; other declaration etc
@gbl_constant_59 = common constant [20 x i8] c"aaaaaaaaaaaaaaaaaaaa", align 
; more function declarations etc

define internal %gen__list__0 @gen__fun__elevate12(%const_array_offset*) {
entry:
  %1 = alloca %gen__list__0
  %2 = getelementptr %const_array_offset, %const_array_offset* %0, i32 0, i32 0
  %3 = load i64, i64* %2
  %4 = getelementptr %const_array_offset, %const_array_offset* %0, i32 0, i32 1
  %5 = load i64, i64* %4
  %6 = sub i64 %5, %3
  %7 = mul i64 %6, i64 2
  %8 = getelementptr %gen__list__0, %gen__list__0* %1, i32 0, i32 0
  %9 = getelementptr %gen__list__0, %gen__list__0* %1, i32 0, i32 1
  %10 = getelementptr %gen__list__0, %gen__list__0* %1, i32 0, i32 2
  store i64 %6, i64* %9
  store i64 %7, i64* %10
  %11 = mul i64 ptrtoint (i8* getelementptr (i8, i8* null, i32 1) to i64), %7
  %12 = call i8* @malloc(i64 %11)
  store i8* %12, i8** %8
  %13 = getelementptr %gen__list__0, %gen__list__0* %1, i32 0, i32 0
  %14 = load i8*, i8** %13
  %15 = getelementptr i8, i8* %14, i64 %6
  %16 = getelementptr [20 x i8], [20 x i8]* @gbl_constant_59, i32 0, i64 %3
  %17 = alloca i8*
  store i8* %16, i8** %17
  %18 = alloca i8*
  store i8* %14, i8** %18
  br label %bb2

bb2:                                              ; preds = %bb3, %entry
  %19 = load i8*, i8** %18
  %20 = icmp ne i8* %19, %15
  br i1 %20, label %bb3, label %bb4

bb3:                                              ; preds = %bb2
  %21 = load i8*, i8** %17
  %22 = getelementptr i8, i8* %21, i32 1
  store i8* %22, i8** %17
  %23 = load i8*, i8** %18
  %24 = getelementptr i8, i8* %23, i32 1
  store i8* %24, i8** %18
  br label %bb2

bb4:                                              ; preds = %bb2
  %25 = load %gen__list__0, %gen__list__0* %1
  ret %gen__list__0 %25
}

All help appreciated to straighten this out/where it/I may be going wrong.

The loop simply implements

c++ style psuedo code for the sort of loop this implements

for(iterator it = begin; it != end; ++it) {
     //code in loop - atm blank
}

Solution

  • The problem was found by putting the code through llc. Apparently constants marked with common linkage can only have a zero initializer. To have a global constant without a zero initializer, as in the case of @gbl_constant_59 here, you need to declare the constant internal or external.