LLVM概述
LLVM是構架編譯器(compiler)的框架系統,以C++編寫而成,用于優化以任意程 序語言編寫的程序的編譯時間(compile-time)、鏈接時間(link-time)、運行時間 (run-time)以及空閑時間(idle-time),對開發者保持開放,并兼容已有腳本。
LLVM計劃啟動于2000年,最初由美國UIUC大學的Chris Lattner博士主持開展。 2006年C hris Lattner加盟Apple Inc.并致力于LLVM在Apple開發體系中的應用。
Apple也是LLVM計劃的主要資助者。
目前LLVM已經被蘋果IOS開發工具、Xilinx Vivado、Facebook、Google等各大 公司采用。
傳統編譯器設計
編譯器前端(Frontend)
編譯器前端的任務是解析源代碼。它會進行:詞法分析,語法分析,語義分析, 檢查源代碼是否存在錯誤,然后構建抽象語法樹(Abstract Syntax Tree,AST) ,LLVM的前端還會生成中間代碼(intermediate representation , IR)。
優化器(Optimizer)
優化器負責進行各種優化。改善代碼的運行時間,例如消除冗余計算等。
后端(Backend) /代碼生成器(CodeGenerator)
將代碼映射到目標指令集。生成機器語言,并且進行機器相關的代碼優化。
iOS的編譯器架構
Objective C/C/C++使用的編譯器前端是Clang, Swift是Swift,后端都是LLVM。
LLVM的設計
當編譯器決定支持多種源語言或多種硬件架構時,LLVM最重要的地方就來了。 其他的編譯器如GCC,它方法非常成功,但由于它是作為整體應用程序設計的, 因此它們的用途受到了很大的限制。
LLVM設計的最重要方面是,使用通用的代碼表示形式(IR),它是用來在編譯器中表示代碼的形式。所以LLVM可以為任何編程語言獨立編寫前端,并且可以為任意硬件架構獨立編寫后端。
出了一個新的高級語言,添加設計一個前端就可以了。出現新的cpu,添加一個后端就可以。
Clang
Clang是LLVM項目中的一個子項目。它是基于LLVM架構的輕量級編譯器,誕生 之初是為了替代GCC,提供更快的編譯速度。它是負責編譯C、C++、Objecte- C語言的編譯器,它屬于整個LLVM架構中的,編譯器前端。對于開發者來說,研究Clang可以給我們帶來很多好處。
編譯流程
通過命令可以打印源碼的編譯階段
clang -ccc-print-phases main.m
0: input, "main.m", objective-c
1: preprocessor, {0}, objective-c-cpp-output
2: compiler, {1}, ir
3: backend, {2}, assembler
4: assembler, {3}, object
5: linker, {4}, image
6: bind-arch, "x86_64", {5}, image
0:輸入文件:找到源文件。
1:預處理階段:這個過程處理包括宏的替換,頭文件的導入。
2:編譯階段:進行詞法分析、語法分析、檢測語法是否正確,最終生成IR。
3:后端:這里LLVM會通過一個一個的Pass去優化,每個Pass做一些事情,最 終生成匯編代碼。
4:生成目標文件。
5:鏈接:鏈接需要的動態庫和靜態庫,生成可執行文件。
6:通過不同的架構,生成對應的可執行文件。
預處理階段
#import <stdio.h>
#define C 30
typedef int HK_INT_64;
int main(int argc, const char * argv[]) {
@autoreleasepool {
HK_INT_64 a = 10;
HK_INT_64 b = 20;
printf("%d",a + b + C);
}
return 0;
}
執行如下命令
clang -E main.m
clang -E main.m >> mian2.m //輸出到文件中
...
typedef int HK_INT_64;
int main(int argc, const char * argv[]) {
@autoreleasepool {
HK_INT_64 a = 10;
HK_INT_64 b = 20;
printf("%d",a + b + 30);
}
return 0;
}
執行完畢可以看到頭文件的導入和宏的替換。類型別名沒有被替換掉。
編譯階段
詞法分析
預處理完成后就會進行詞法分析.這里會把代碼切成一個個Token,比如大小括 號,等于號還有字符串等。
clang -fmodules -fsyntax-only -Xclang -dump-tokens main.m
annot_module_include '#import <stdio.h>
#define C 30
typedef int HK_INT_64;
int main(int argc, const char * argv[]) {
@autoreleasepool {
HK_INT_6' Loc=<main.m:9:1>
typedef 'typedef' [StartOfLine] Loc=<main.m:12:1>
int 'int' [LeadingSpace] Loc=<main.m:12:9>
identifier 'HK_INT_64' [LeadingSpace] Loc=<main.m:12:13>
semi ';' Loc=<main.m:12:22>
int 'int' [StartOfLine] Loc=<main.m:14:1>
identifier 'main' [LeadingSpace] Loc=<main.m:14:5>
l_paren '(' Loc=<main.m:14:9>
int 'int' Loc=<main.m:14:10>
identifier 'argc' [LeadingSpace] Loc=<main.m:14:14>
comma ',' Loc=<main.m:14:18>
const 'const' [LeadingSpace] Loc=<main.m:14:20>
char 'char' [LeadingSpace] Loc=<main.m:14:26>
star '*' [LeadingSpace] Loc=<main.m:14:31>
identifier 'argv' [LeadingSpace] Loc=<main.m:14:33>
l_square '[' Loc=<main.m:14:37>
r_square ']' Loc=<main.m:14:38>
r_paren ')' Loc=<main.m:14:39>
l_brace '{' [LeadingSpace] Loc=<main.m:14:41>
at '@' [StartOfLine] [LeadingSpace] Loc=<main.m:15:5>
identifier 'autoreleasepool' Loc=<main.m:15:6>
l_brace '{' [LeadingSpace] Loc=<main.m:15:22>
identifier 'HK_INT_64' [StartOfLine] [LeadingSpace] Loc=<main.m:16:9>
identifier 'a' [LeadingSpace] Loc=<main.m:16:19>
equal '=' [LeadingSpace] Loc=<main.m:16:21>
numeric_constant '10' [LeadingSpace] Loc=<main.m:16:23>
semi ';' Loc=<main.m:16:25>
identifier 'HK_INT_64' [StartOfLine] [LeadingSpace] Loc=<main.m:17:9>
identifier 'b' [LeadingSpace] Loc=<main.m:17:19>
equal '=' [LeadingSpace] Loc=<main.m:17:21>
numeric_constant '20' [LeadingSpace] Loc=<main.m:17:23>
semi ';' Loc=<main.m:17:25>
identifier 'printf' [StartOfLine] [LeadingSpace] Loc=<main.m:18:9>
l_paren '(' Loc=<main.m:18:15>
string_literal '"%d"' Loc=<main.m:18:16>
comma ',' Loc=<main.m:18:20>
identifier 'a' Loc=<main.m:18:21>
plus '+' [LeadingSpace] Loc=<main.m:18:23>
identifier 'b' [LeadingSpace] Loc=<main.m:18:25>
plus '+' [LeadingSpace] Loc=<main.m:18:27>
numeric_constant '30' [LeadingSpace] Loc=<main.m:18:29 <Spelling=main.m:10:11>>
r_paren ')' Loc=<main.m:18:30>
semi ';' Loc=<main.m:18:31>
r_brace '}' [StartOfLine] [LeadingSpace] Loc=<main.m:19:5>
return 'return' [StartOfLine] [LeadingSpace] Loc=<main.m:20:5>
numeric_constant '0' [LeadingSpace] Loc=<main.m:20:12>
semi ';' Loc=<main.m:20:13>
r_brace '}' [StartOfLine] Loc
語法分析
詞法分析完成之后就是語法分析,它的任務是驗證語法是否正確。在詞法分析的 基礎上將單詞序列組合成各類語法短語,如“程序”,“語句”,“表達式”等等,然 后將所有節點組成抽象語法樹(Abstract Syntax Tree, AST)。語法分析程序判 斷源程序在結構上是否正確。
clang -fmodules -fsyntax-only -Xclang -ast-dump main.m
如果導入頭文件找不到,那么可以指定SDK
clang -isysroot/Applications/Xcode.app/Contents/Developer/Platforms/ iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk (自己S DK 路徑) -fmodules -fsyntax-only -Xclang -ast-dump main.m
TranslationUnitDecl 0x7f8da082e408 <<invalid sloc>> <invalid sloc> <undeserialized declarations>
|-TypedefDecl 0x7f8da082eca0 <<invalid sloc>> <invalid sloc> implicit __int128_t '__int128'
| `-BuiltinType 0x7f8da082e9a0 '__int128'
|-TypedefDecl 0x7f8da082ed10 <<invalid sloc>> <invalid sloc> implicit __uint128_t 'unsigned __int128'
| `-BuiltinType 0x7f8da082e9c0 'unsigned __int128'
|-TypedefDecl 0x7f8da082edb0 <<invalid sloc>> <invalid sloc> implicit SEL 'SEL *'
| `-PointerType 0x7f8da082ed70 'SEL *'
| `-BuiltinType 0x7f8da082ec00 'SEL'
|-TypedefDecl 0x7f8da082ee98 <<invalid sloc>> <invalid sloc> implicit id 'id'
| `-ObjCObjectPointerType 0x7f8da082ee40 'id'
| `-ObjCObjectType 0x7f8da082ee10 'id'
|-TypedefDecl 0x7f8da082ef78 <<invalid sloc>> <invalid sloc> implicit Class 'Class'
| `-ObjCObjectPointerType 0x7f8da082ef20 'Class'
| `-ObjCObjectType 0x7f8da082eef0 'Class'
|-ObjCInterfaceDecl 0x7f8da082efd0 <<invalid sloc>> <invalid sloc> implicit Protocol
|-TypedefDecl 0x7f8da082f348 <<invalid sloc>> <invalid sloc> implicit __NSConstantString 'struct __NSConstantString_tag'
| `-RecordType 0x7f8da082f140 'struct __NSConstantString_tag'
| `-Record 0x7f8da082f0a0 '__NSConstantString_tag'
|-TypedefDecl 0x7f8da100ac00 <<invalid sloc>> <invalid sloc> implicit __builtin_ms_va_list 'char *'
| `-PointerType 0x7f8da082f3a0 'char *'
| `-BuiltinType 0x7f8da082e4a0 'char'
|-TypedefDecl 0x7f8da100aee8 <<invalid sloc>> <invalid sloc> implicit __builtin_va_list 'struct __va_list_tag [1]'
| `-ConstantArrayType 0x7f8da100ae90 'struct __va_list_tag [1]' 1
| `-RecordType 0x7f8da100acf0 'struct __va_list_tag'
| `-Record 0x7f8da100ac58 '__va_list_tag'
|-ImportDecl 0x7f8da100b710 <main.m:9:1> col:1 implicit Darwin.C.stdio
|-TypedefDecl 0x7f8da100b768 <line:12:1, col:13> col:13 referenced HK_INT_64 'int'
| `-BuiltinType 0x7f8da082e500 'int'
`-FunctionDecl 0x7f8da100ba40 <line:14:1, line:21:1> line:14:5 main 'int (int, const char **)'
|-ParmVarDecl 0x7f8da100b7d8 <col:10, col:14> col:14 argc 'int'
|-ParmVarDecl 0x7f8da100b8f0 <col:20, col:38> col:33 argv 'const char **':'const char **'
`-CompoundStmt 0x7f8da11681c0 <col:41, line:21:1>
|-ObjCAutoreleasePoolStmt 0x7f8da1168178 <line:15:5, line:19:5>
| `-CompoundStmt 0x7f8da1168150 <line:15:22, line:19:5>
| |-DeclStmt 0x7f8da1167a88 <line:16:9, col:25>
| | `-VarDecl 0x7f8da1167a00 <col:9, col:23> col:19 used a 'HK_INT_64':'int' cinit
| | `-IntegerLiteral 0x7f8da1167a68 <col:23> 'int' 10
| |-DeclStmt 0x7f8da1167f18 <line:17:9, col:25>
| | `-VarDecl 0x7f8da1167ab0 <col:9, col:23> col:19 used b 'HK_INT_64':'int' cinit
| | `-IntegerLiteral 0x7f8da1167b18 <col:23> 'int' 20
| `-CallExpr 0x7f8da11680f0 <line:18:9, col:30> 'int'
| |-ImplicitCastExpr 0x7f8da11680d8 <col:9> 'int (*)(const char *, ...)' <FunctionToPointerDecay>
| | `-DeclRefExpr 0x7f8da1167f30 <col:9> 'int (const char *, ...)' Function 0x7f8da1167b40 'printf' 'int (const char *, ...)'
| |-ImplicitCastExpr 0x7f8da1168138 <col:16> 'const char *' <NoOp>
| | `-ImplicitCastExpr 0x7f8da1168120 <col:16> 'char *' <ArrayToPointerDecay>
| | `-StringLiteral 0x7f8da1167f88 <col:16> 'char [3]' lvalue "%d"
| `-BinaryOperator 0x7f8da1168088 <col:21, line:10:11> 'int' '+'
| |-BinaryOperator 0x7f8da1168048 <line:18:21, col:25> 'int' '+'
| | |-ImplicitCastExpr 0x7f8da1168018 <col:21> 'HK_INT_64':'int' <LValueToRValue>
| | | `-DeclRefExpr 0x7f8da1167fa8 <col:21> 'HK_INT_64':'int' lvalue Var 0x7f8da1167a00 'a' 'HK_INT_64':'int'
| | `-ImplicitCastExpr 0x7f8da1168030 <col:25> 'HK_INT_64':'int' <LValueToRValue>
| | `-DeclRefExpr 0x7f8da1167fe0 <col:25> 'HK_INT_64':'int' lvalue Var 0x7f8da1167ab0 'b' 'HK_INT_64':'int'
| `-IntegerLiteral 0x7f8da1168068 <line:10:11> 'int' 30
`-ReturnStmt 0x7f8da11681b0 <line:20:5, col:12>
生成中間代碼 IR(intermediate representation )
完成以上步驟后就開始生成中間代碼IR 了,代碼生成器(Code Generation )會 將語法樹自頂向下遍歷逐步翻譯成LLVM IR。通過下面命令可以生成.11的文本文 件,查看IR代碼。
int test(int a,int b){
return a + b + 3;
}
int main(int argc, const char * argv[]) {
int a = test(1, 2);
printf("%d",a);
return 0;
}
clang -S -fobjc-arc -emit-llvm main.m
Objective C代碼在這一步會進行runtime的橋接:property合成,ARC處理等
IR的基本語法
; ModuleID = 'main.m'
source_filename = "main.m"
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.15.0"
@.str = private unnamed_addr constant [3 x i8] c"%d\00", align 1
; Function Attrs: noinline nounwind optnone ssp uwtable
define i32 @test(i32, i32) #0 {; int a0,int a1
%3 = alloca i32, align 4 ;int a3
%4 = alloca i32, align 4 ;int b4
store i32 %0, i32* %3, align 4 ;a3 = a0
store i32 %1, i32* %4, align 4 ;a4 = a1
%5 = load i32, i32* %3, align 4 ; int a5 = a3
%6 = load i32, i32* %4, align 4 ; int a6 = a4
%7 = add nsw i32 %5, %6 ; int a7 = a5 + a6
%8 = add nsw i32 %7, 3 ; int a8 = a7 + 3
ret i32 %8 ;return a8;
}
; Function Attrs: noinline optnone ssp uwtable
define i32 @main(i32, i8**) #1 {
%3 = alloca i32, align 4
%4 = alloca i32, align 4
%5 = alloca i8**, align 8
%6 = alloca i32, align 4
store i32 0, i32* %3, align 4
store i32 %0, i32* %4, align 4
store i8** %1, i8*** %5, align 8
%7 = call i32 @test(i32 1, i32 2)
store i32 %7, i32* %6, align 4
%8 = load i32, i32* %6, align 4
%9 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str, i64 0, i64 0), i32 %8)
ret i32 0
}
declare i32 @printf(i8*, ...) #2
attributes #0 = { noinline nounwind optnone ssp uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "darwin-stkchk-strong-link" "disable-tail-calls"="false" "frame-pointer"="all" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "probe-stack"="___chkstk_darwin" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+cx8,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { noinline optnone ssp uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "darwin-stkchk-strong-link" "disable-tail-calls"="false" "frame-pointer"="all" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "probe-stack"="___chkstk_darwin" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+cx8,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #2 = { "correctly-rounded-divide-sqrt-fp-math"="false" "darwin-stkchk-strong-link" "disable-tail-calls"="false" "frame-pointer"="all" "less-precise-fpmad"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "probe-stack"="___chkstk_darwin" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+cx8,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7}
!llvm.ident = !{!8}
!0 = !{i32 2, !"SDK Version", [3 x i32] [i32 10, i32 15, i32 6]}
!1 = !{i32 1, !"Objective-C Version", i32 2}
!2 = !{i32 1, !"Objective-C Image Info Version", i32 0}
!3 = !{i32 1, !"Objective-C Image Info Section", !"__DATA,__objc_imageinfo,regular,no_dead_strip"}
!4 = !{i32 4, !"Objective-C Garbage Collection", i32 0}
!5 = !{i32 1, !"Objective-C Class Properties", i32 64}
!6 = !{i32 1, !"wchar_size", i32 4}
!7 = !{i32 7, !"PIC Level", i32 2}
!8 = !{!"Apple clang version 11.0.3 (clang-1103.0.32.62)"}
@全局標識
%局部標識
alloca開辟空間
align內存對齊
i32 32個bit, 4個字節
store寫入內存
load讀取數據
call調用函數
ret返回
IR的優化
LLVM的優化級別分別是-O0 -O1 -O2 -O3 -Os(第一個是大寫英文字母O)
clang -Os -S -fobjc-arc -emit-llvm main.m -o main.ll
bitCode
xcode7以后開啟bitcode蘋果會做進一步的優化。生成.be的中間代碼。 我們通過優化后的IR代碼生成.be代碼
clang -emit-llvm -c main.ll -o main.bc
生成匯編代碼
我們通過最終的.be或者.ll代碼生成匯編代碼
clang -S -fobjc-arc main.bc -o main.s
clang -S -fobjc-arc main.ll -o main.s
生成匯編代碼也可以進行優化
clang -Os -S -fobjc-arc main.m -o main.s
生成目標文件(匯編器)
目標文件的生成,是匯編器以匯編代碼作為輸入,將匯編代碼轉換為機器代碼, 最后輸出目標文件(object file)o
clang -fmodules -c main.s -o main.o
通過nm命令,查看下main.o中的符號
$xcrun nm -nm main.o
(undefined) external _printf
0000000000000000 ( _TEXT, _text) external _test
000000000000000a ( TEXT, text) external _main
_printf 是一個是 undefined externaI
的。
undefined表示在當前文件暫時找不到符號_printf external表示這個符號是外部可以訪問的。
生成可執行文件(鏈接)
連接器把編譯產生的.o文件和(.dylib .a)文件,生成一個mach-o文件。
clang main.o -o main
查看鏈接之后的符號
$xcrun nm -nm main
(undefined) external _printf (from libSystem)//運行的時候動態的綁定
(undefined) external dyld_stub_binder (from libSyste
m)
0000000100000000 ( TEXT, text) [referenced dynamically] external
mh_execute_header
000000100000f6d ( _TEXT, _text) external _test
000000100000f77 ( TEXT, text) external _main
這就是將源代碼編譯成可執行的文件