welcome to
evildojo


Programming Tutorials

C

002 - Hello, World! LLVM IR

Contents

  1. Introduction
  2. Hello World LLVM IR

Introduction

I recently came across this article on LLVM IR, which is an intermediate representation language used by LLVM to generate optimizations during the compilation phase of creating executable code: https://idea.popcount.org/2013-07-24-ir-is-better-than-assembly/


Hello World LLVM IR

Assuming your source file is located in main.c and the output is to be in main.ll:

$ clang -Os -S -emit-llvm main.c -o main.ll

This produces:

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

@str = private unnamed_addr constant [12 x i8] c"hello world\00"

; Function Attrs: nounwind optsize ssp uwtable
define i32 @main() #0 {
  %1 = tail call i32 @puts(i8* getelementptr inbounds ([12 x i8], [12 x i8]* @str, i64 0, i64 0))
  ret i32 0
}

; Function Attrs: nounwind
declare i32 @puts(i8* nocapture readonly) #1

attributes #0 = { nounwind optsize ssp uwtable "disable-tail-calls"="false" "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" "target-cpu"="penryn" "target-features"="+cx16,+fxsr,+mmx,+sse,+sse2,+sse3,+sse4.1,+ssse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { nounwind }

!llvm.module.flags = !{!0}
!llvm.ident = !{!1}

!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 8.0.0 (clang-800.0.42.1)"}