[llvm-dev] How to call C function 'malloc' ?

Bruce Hoult via llvm-dev llvm-dev at lists.llvm.org
Sat Dec 5 13:25:42 PST 2015


The answer to such questions is usually best obtained by looking at what
clang does. See below.

$ cat foo.c

#include <stdlib.h>

void* foo(int i){return malloc(i);}

$ clang -emit-llvm -S foo.c

$ cat foo.ll

; ModuleID = 'foo.c'

target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"

target triple = "x86_64-apple-macosx10.10.0"


; Function Attrs: nounwind ssp uwtable

define i8* @foo(i32 %i) #0 {

  %1 = alloca i32, align 4

  store i32 %i, i32* %1, align 4

  %2 = load i32* %1, align 4

  %3 = sext i32 %2 to i64

  %4 = call i8* @malloc(i64 %3)

  ret i8* %4

}


declare i8* @malloc(i64) #1


attributes #0 = { nounwind ssp 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 = { "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" }


!llvm.ident = !{!0}


!0 = metadata !{metadata !"Apple LLVM version 6.0 (clang-600.0.56) (based
on LLVM 3.5svn)"}



On Thu, Dec 3, 2015 at 4:03 PM, AllenShow via llvm-dev <
llvm-dev at lists.llvm.org> wrote:

> Hi, everyone.
> I am new to llvm and I want to use C function “malloc" and “free" to do
> heap allocation, but It seems it is not a built-in function like ‘’printf”
> so I got an error “Unknown extern function”.
> I use ExecutionEngineer to run my main function and how should I do to
> make EE link the C library I want.
> Thanks.
> _______________________________________________
> LLVM Developers mailing list
> llvm-dev at lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20151206/5f32a8b4/attachment.html>


More information about the llvm-dev mailing list