5

I created a very simple LLVM IR code piece via the API. Inside the main block, I want to insert calls to functions that are available in the C standard library such as malloc, printf or some other ones that I write in C by myself.

; ModuleID = 'main.d2'
source_filename = "main.d2"
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-darwin17.7.0"

define i32 @main() {
  %1 = alloca i32
  store i32 0, i32* %1

insert call here

  %2 = load i32, i32* %1
  ret i32 %2
}

I compile the bitcode with

llc -filetype=obj -o main.o main.bit

and link the objects with

clang main.o -o main

commands.

Questions

  • Do I need to link C stdlib in the last step with compiler flags and/or do I prepare a wrapper library in C which includes the functions I need in order to compile something like clib.o for external linkage? Is the second command the proper way for linking such external dependencies?

  • Also, how is it going to behave on Windows (I'm on Mac or Ubuntu right now) if I use the same approach? What should change in my workflow?

  • Am I missing something here that makes the whole problem irrelevant?

My machine:

clang version 7.0.0 (tags/RELEASE_700/final)
Target: x86_64-apple-darwin18.0.0
Thread model: posix
InstalledDir: /opt/local/libexec/llvm-7.0/bin
diegoperini
  • 1,796
  • 21
  • 37

1 Answers1

2

Am I missing something here that makes the whole problem irrelevant?

Yes, you are using clang for linking. It knows how and when link C runtime and all these crt things. You can even pass textual IR to clang directly.

arrowd
  • 33,231
  • 8
  • 79
  • 110
  • Is this true even when I don't do something equivalent to `#include ` and `#include ` in my code or in the commands above? If so, why do we do includes in C if they are automatically added by clang? Sorry for the noob questions. – diegoperini Oct 28 '18 at 13:40