LLVM编译

llvm 工具牛刀小试

  1. 编写hello.c
#include 
int main(){
   printf("hello world\n");
}
  1. 将C文件编译为本机可执行文件,执行clang 命令如下:
$ clang  hello.c -o hello

PS: Clang为LLVM提供的C语言编译器,默认参数可以生成本机可执行的二进制程序。-S和-c参数与GCC一样,可分别生成.s汇编文件与.o目标文件。

  1. 将C文件编译为LLVM bitcode 文件, 执行如下如下命令
$ clang -o3  -emit-llvm hello.c -c -o hello.bc
$ clang -o3  -emit-llvm hello.c -S -o hello.ll

.ll 文件 llvm bitcode 的可读文本 .bc 是bitcode的二进制格式

  1. 两种形式运行程序
$./hello
hello world
$./lli hello.bc
hello world

5.llvm-dis 工具反汇编llvm bitcode 文件, 可以将bc文件的内容以刻度文本形式进行展示

$ ./llvm-dis < hello.bc
; ModuleID = ''
source_filename = "hello.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 ssp uwtable
define i32 @main() local_unnamed_addr #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) local_unnamed_addr #1

attributes #0 = { nounwind ssp uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "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-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { nounwind }

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

!0 = !{i32 1, !"wchar_size", i32 4}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 7.0.0 (tags/RELEASE_700/final)"}
  1. llc 代码生成器将程序编译为本机CPU架构的汇编指令
$ ./llc hello.bc -o hello.s
$ cat hello.s
    .section    __TEXT,__text,regular,pure_instructions
    .macosx_version_min 10, 12
    .globl  _main                   ## -- Begin function main
    .p2align    4, 0x90
_main:                                  ## @main
    .cfi_startproc
## %bb.0:
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register %rbp
    leaq    L_str(%rip), %rdi
    callq   _puts
    xorl    %eax, %eax
    popq    %rbp
    retq
    .cfi_endproc
                                        ## -- End function
    .section    __TEXT,__cstring,cstring_literals
L_str:                                  ## @str
    .asciz  "hello world"


.subsections_via_symbols
  1. 将本机的汇编语言文件编译成程序,使用gcc 命令直接编译:
$ gcc hello.s -o hello.native

你可能感兴趣的:(LLVM编译)