编译器入门小记

编译器的介绍

传统的编译器通常分为三个部分,前端(frontEnd),优化器(Optimizer)和后端(backEnd). 在编译过程中,前端主要负责词法和语法分析,将源代码转化为抽象语法树;优化器则是在前端的基础上,对得到的中间代码进行优化,使代码更加高效;后端则是将已经优化的中间代码转化为针对各自平台的机器代码。
一般的程序员也是编译器“前端”的用户,代码语法规范就是编译器的“说明书”。

LLVM编译器架构介绍

[https://llvm.org]
The LLVM Project is a collection of modular and reusable compiler and toolchain technologies. Despite its name, LLVM has little to do with traditional virtual machines. The name "LLVM" itself is not an acronym; it is the full name of the project.

LLVM began as a research project at the University of Illinois, with the goal of providing a modern, SSA-based compilation strategy capable of supporting both static and dynamic compilation of arbitrary programming languages. Since then, LLVM has grown to be an umbrella project consisting of a number of subprojects, many of which are being used in production by a wide variety of commercial and open source projects as well as being widely used in academic research. Code in the LLVM project is licensed under the "Apache 2.0 License with LLVM exceptions"

[https://zhuanlan.zhihu.com/p/161626997]
LLVM编译器架构:前端进行语法分析生成中间代码(LLVM IR),后端优化并编译为机器语言。
LLVM IR:LLVM Intermediate Representation

整体过程:
.c --frontend--> AST --frontend--> LLVM IR --LLVM opt--> LLVM IR --LLVM llc--> .s Assembly --OS Assembler--> .o --OS Linker--> executable

开始LLVM编译器之旅

安装LLVM套件

macOS: brew install llvm
或者从官网下载[https://releases.llvm.org/download.html].

中文编程语言

中文编程软件有:
BCY语言(1964年)
朱邦復曾設計過的一些中文語言,如中文培基(英语:Chinese BASIC)與中文cobol(1980年代)
伙計培基(1987年)
易語言(2000年)
丙正正,C++语言的中文版本(2000年代 2001)
唐鳳曾經設計過能以文言文寫作的perl模組PerlYuYan(2002年)
中蟒(2002年)
O語言,一种中文組合語言(2005年)
周蟒(2007年)
習語言,支持中文的C语言(2009年)
中文小海龜 中文化的Logo語言(2009年)
蝉语(2014年)
Wenyan-lang,类文言文的编程语言(2020年)

易语言代码举例

周蟒代码举例

#!/usr/bin/env zhpy
# 檔名:while.py
數字 = 23
運行 = 真
當 運行:
    猜測 = 整數(輸入('輸入一個數字: '))

    如果 猜測 == 數字:
        印出 '恭喜, 你猜對了.'
        運行 = 假 # 這會讓循環語句結束
    假使 猜測 < 數字:
        印出 '錯了, 數字再大一點.'
    否則:
        印出 '錯了, 數字再小一點.'
否則:
    印出 '循環語句結束'
印出 '結束'

周蟒,又名zhpy,是一个轻量的,与Python语言互相兼容的中文Python语言。让用户可以使用纯中文语句(繁体或简体)来编写程序。
即周蟒的基本上就是将Python替换了关键字。
另外一种"中蟒"大同小异

#!/usr/local/bin/cpython
回答 = 读入('你认为中文程式语言有存在价值吗?(有/没有)');
如 回答 == '有':
	写 '好吧,让我们一起努力!';
不然 回答 == '没有':
	写 '好吧,中文并没有作为程式语言的价值.';
否则:
	写 '请认真考虑后再回答.';

LLVM IR语言的HelloWorld程序

[https://zhuanlan.zhihu.com/p/161780623]
当然不是让编译器对我们说HelloWorld!而是测试编译器运行正常:
文件:main.ll

; main.ll
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx11.0.0"

define i32 @main() {
    ret i32 0
}

vscode有.ll文件的扩展.
类同

int main() {
    return 0;
}

编译:

clang main.ll -o main
./main

说明:target datalayout和target triple字段可以通过clang -S -emit-llvm test.c获得.

posted @ 2022-09-25 22:28  qsBye  阅读(211)  评论(0编辑  收藏  举报