preface

After learning the principles of compiling last semester, I always wanted to do something big, so I came up with the idea of writing a compiler. After much searching I found the official LLVM tutorial. This tutorial implements a toy language called Kaleidoscope. In the official tutorial, there are two execution methods of just-in-time compilation and generating object files to be called by C++. I also have a one-to-one corresponding implementation in the project.

The official tutorial was written in C++, so I wondered if I could write it in swift. As it turns out, THERE is a swift open source library, LLVMSwift, that encapsulates LLVM. Of course, I think it’s ok to use LLVM directly without using the library, in fact, it’s closer to the official tutorial, and you need to understand the logic of using the open source library.

So I wrote the first eight chapters of their tutorial, and the warehouse is here

The tutorial is as follows:

Write compiler toys using Swift (0)

Learn how to write compiler toys using Swift

Use Swift to write compiler toys (2)

Use swift to write compiler toys (3)

Learn how to write compiler toys using Swift

Learn how to write compiler toys using Swift

Learn how to write compiler toys using Swift

Learn how to write compiler toys using Swift

Learn how to write compiler toys using Swift

In the warehouse

start

The first thing we’ll do for Chapter 0 is install LLVM. There is very little documentation on the web about this and it is a pain to learn by yourself. Here is how to install LLVM and use it in Xcode. Since all variables were resolved to int64 type instead of Double type at the beginning of the project, the following chapters may be different from the intermediate code IR generated in the official tutorial. Please make a specific analysis.

Download the LLVM

First we download LLVM through Homebrew

brew install llvm
Copy the code

After downloading LLVM, we continue to download PKg-config

brew install pkg-config
Copy the code

Do not use LLVMSwift

You need to introduce LLVM directly in Xcode by adding an environment to the.bash_profile file

Depending on the version of LLVM you have installed, configure the LLVM command line under.bash_profile
export PATH=/usr/local/ Cellar/LLVM / 8.0.0 _1 / bin:$PATH;
Copy the code

Then go to Xcode->Build Settings->Search Paths->Header Search Paths

/usr/local/opt/llvm/include
/usr/local/opt/llvm/lib
Copy the code

Using LLVMSwift

Download the LLVMSwift script.

Add in Package

.package(url: "https://github.com/llvm-swift/LLVMSwift.git", from: "0.5.0")
Copy the code

And rely on LLVM in target

dependencies: ["LLVM"]
Copy the code

Configure the environment

swift utils/make-pkgconfig.swift
Copy the code

Compile the project

swift build
Copy the code

Once the build is complete, you can introduce LLVM into your project and use LLVMSwift.