LLVM IR 模块结构

LLVM程序由Module’s组成,每个程序模块都是输入程序的翻译单元。每个模块由函数,全局变量和符号表条目组成。模块可以与LLVM链接器组合在一起,LLVM链接器合并函数(和全局变量)定义,解析前向声明,并合并符号表条目。

以下是“hello world”模块的示例:

; Declare the string constant as a global constant.
@.str = private unnamed_addr constant [13 x i8] c"hello world\0A\00"

; External declaration of the puts function
declare i32 @puts(i8* nocapture) nounwind

; Definition of main function
define i32 @main() {   ; i32()*
  ; Convert [13 x i8]* to i8*...
  %cast210 = getelementptr [13 x i8], [13 x i8]* @.str, i64 0, i64 0

  ; Call puts function to write out the string to stdout.
  call i32 @puts(i8* %cast210)
  ret i32 0
}

; Named metadata
!0 = !{i32 42, null, !"string"}
!foo = !{!0}

这个例子由一个全局变量”.str”,一个”puts”函数的外部声明,一个”main”函数的函数定义和一个具名元数据”foo”组成。

一般情况下,一个模块由全局值(函数和全局变量都是全局值)的列表组成,全局值通过存储单元的指针表示(在这种情况下,一个指针指向字符数组,一个指针指向一个函数)并具有以下的链接类型之一。