blob: 789042b53d3a6add9c4161a91f596d1e4363cc97 [file] [log] [blame]
Hans Wennborg74e4f8a2019-04-11 07:46:25 +00001:orphan:
2
Chris Lattnerd80f1182019-04-07 13:14:23 +00003======================================================
4Kaleidoscope: Conclusion and other useful LLVM tidbits
5======================================================
6
7.. contents::
8 :local:
9
10Tutorial Conclusion
11===================
12
13Welcome to the final chapter of the "`Implementing a language with
14LLVM <index.html>`_" tutorial. In the course of this tutorial, we have
15grown our little Kaleidoscope language from being a useless toy, to
16being a semi-interesting (but probably still useless) toy. :)
17
18It is interesting to see how far we've come, and how little code it has
19taken. We built the entire lexer, parser, AST, code generator, an
20interactive run-loop (with a JIT!), and emitted debug information in
21standalone executables - all in under 1000 lines of (non-comment/non-blank)
22code.
23
24Our little language supports a couple of interesting features: it
25supports user defined binary and unary operators, it uses JIT
26compilation for immediate evaluation, and it supports a few control flow
27constructs with SSA construction.
28
29Part of the idea of this tutorial was to show you how easy and fun it
30can be to define, build, and play with languages. Building a compiler
31need not be a scary or mystical process! Now that you've seen some of
32the basics, I strongly encourage you to take the code and hack on it.
33For example, try adding:
34
35- **global variables** - While global variables have questional value
36 in modern software engineering, they are often useful when putting
37 together quick little hacks like the Kaleidoscope compiler itself.
38 Fortunately, our current setup makes it very easy to add global
39 variables: just have value lookup check to see if an unresolved
40 variable is in the global variable symbol table before rejecting it.
41 To create a new global variable, make an instance of the LLVM
42 ``GlobalVariable`` class.
43- **typed variables** - Kaleidoscope currently only supports variables
44 of type double. This gives the language a very nice elegance, because
45 only supporting one type means that you never have to specify types.
46 Different languages have different ways of handling this. The easiest
47 way is to require the user to specify types for every variable
48 definition, and record the type of the variable in the symbol table
49 along with its Value\*.
50- **arrays, structs, vectors, etc** - Once you add types, you can start
51 extending the type system in all sorts of interesting ways. Simple
52 arrays are very easy and are quite useful for many different
53 applications. Adding them is mostly an exercise in learning how the
54 LLVM `getelementptr <../LangRef.html#getelementptr-instruction>`_ instruction
55 works: it is so nifty/unconventional, it `has its own
56 FAQ <../GetElementPtr.html>`_!
57- **standard runtime** - Our current language allows the user to access
58 arbitrary external functions, and we use it for things like "printd"
59 and "putchard". As you extend the language to add higher-level
60 constructs, often these constructs make the most sense if they are
61 lowered to calls into a language-supplied runtime. For example, if
62 you add hash tables to the language, it would probably make sense to
63 add the routines to a runtime, instead of inlining them all the way.
64- **memory management** - Currently we can only access the stack in
65 Kaleidoscope. It would also be useful to be able to allocate heap
66 memory, either with calls to the standard libc malloc/free interface
67 or with a garbage collector. If you would like to use garbage
68 collection, note that LLVM fully supports `Accurate Garbage
69 Collection <../GarbageCollection.html>`_ including algorithms that
70 move objects and need to scan/update the stack.
71- **exception handling support** - LLVM supports generation of `zero
72 cost exceptions <../ExceptionHandling.html>`_ which interoperate with
73 code compiled in other languages. You could also generate code by
74 implicitly making every function return an error value and checking
75 it. You could also make explicit use of setjmp/longjmp. There are
76 many different ways to go here.
77- **object orientation, generics, database access, complex numbers,
78 geometric programming, ...** - Really, there is no end of crazy
79 features that you can add to the language.
80- **unusual domains** - We've been talking about applying LLVM to a
81 domain that many people are interested in: building a compiler for a
82 specific language. However, there are many other domains that can use
83 compiler technology that are not typically considered. For example,
84 LLVM has been used to implement OpenGL graphics acceleration,
85 translate C++ code to ActionScript, and many other cute and clever
86 things. Maybe you will be the first to JIT compile a regular
87 expression interpreter into native code with LLVM?
88
89Have fun - try doing something crazy and unusual. Building a language
90like everyone else always has, is much less fun than trying something a
91little crazy or off the wall and seeing how it turns out. If you get
92stuck or want to talk about it, feel free to email the `llvm-dev mailing
93list <http://lists.llvm.org/mailman/listinfo/llvm-dev>`_: it has lots
94of people who are interested in languages and are often willing to help
95out.
96
97Before we end this tutorial, I want to talk about some "tips and tricks"
98for generating LLVM IR. These are some of the more subtle things that
99may not be obvious, but are very useful if you want to take advantage of
100LLVM's capabilities.
101
102Properties of the LLVM IR
103=========================
104
105We have a couple of common questions about code in the LLVM IR form -
106let's just get these out of the way right now, shall we?
107
108Target Independence
109-------------------
110
111Kaleidoscope is an example of a "portable language": any program written
112in Kaleidoscope will work the same way on any target that it runs on.
113Many other languages have this property, e.g. lisp, java, haskell,
114javascript, python, etc (note that while these languages are portable,
115not all their libraries are).
116
117One nice aspect of LLVM is that it is often capable of preserving target
118independence in the IR: you can take the LLVM IR for a
119Kaleidoscope-compiled program and run it on any target that LLVM
120supports, even emitting C code and compiling that on targets that LLVM
121doesn't support natively. You can trivially tell that the Kaleidoscope
122compiler generates target-independent code because it never queries for
123any target-specific information when generating code.
124
125The fact that LLVM provides a compact, target-independent,
126representation for code gets a lot of people excited. Unfortunately,
127these people are usually thinking about C or a language from the C
128family when they are asking questions about language portability. I say
129"unfortunately", because there is really no way to make (fully general)
130C code portable, other than shipping the source code around (and of
131course, C source code is not actually portable in general either - ever
132port a really old application from 32- to 64-bits?).
133
134The problem with C (again, in its full generality) is that it is heavily
135laden with target specific assumptions. As one simple example, the
136preprocessor often destructively removes target-independence from the
137code when it processes the input text:
138
139.. code-block:: c
140
141 #ifdef __i386__
142 int X = 1;
143 #else
144 int X = 42;
145 #endif
146
147While it is possible to engineer more and more complex solutions to
148problems like this, it cannot be solved in full generality in a way that
149is better than shipping the actual source code.
150
151That said, there are interesting subsets of C that can be made portable.
152If you are willing to fix primitive types to a fixed size (say int =
15332-bits, and long = 64-bits), don't care about ABI compatibility with
154existing binaries, and are willing to give up some other minor features,
155you can have portable code. This can make sense for specialized domains
156such as an in-kernel language.
157
158Safety Guarantees
159-----------------
160
161Many of the languages above are also "safe" languages: it is impossible
162for a program written in Java to corrupt its address space and crash the
163process (assuming the JVM has no bugs). Safety is an interesting
164property that requires a combination of language design, runtime
165support, and often operating system support.
166
167It is certainly possible to implement a safe language in LLVM, but LLVM
168IR does not itself guarantee safety. The LLVM IR allows unsafe pointer
169casts, use after free bugs, buffer over-runs, and a variety of other
170problems. Safety needs to be implemented as a layer on top of LLVM and,
171conveniently, several groups have investigated this. Ask on the `llvm-dev
172mailing list <http://lists.llvm.org/mailman/listinfo/llvm-dev>`_ if
173you are interested in more details.
174
175Language-Specific Optimizations
176-------------------------------
177
178One thing about LLVM that turns off many people is that it does not
179solve all the world's problems in one system. One specific
180complaint is that people perceive LLVM as being incapable of performing
181high-level language-specific optimization: LLVM "loses too much
182information". Here are a few observations about this:
183
184First, you're right that LLVM does lose information. For example, as of
185this writing, there is no way to distinguish in the LLVM IR whether an
186SSA-value came from a C "int" or a C "long" on an ILP32 machine (other
187than debug info). Both get compiled down to an 'i32' value and the
188information about what it came from is lost. The more general issue
189here, is that the LLVM type system uses "structural equivalence" instead
190of "name equivalence". Another place this surprises people is if you
191have two types in a high-level language that have the same structure
192(e.g. two different structs that have a single int field): these types
193will compile down into a single LLVM type and it will be impossible to
194tell what it came from.
195
196Second, while LLVM does lose information, LLVM is not a fixed target: we
197continue to enhance and improve it in many different ways. In addition
198to adding new features (LLVM did not always support exceptions or debug
199info), we also extend the IR to capture important information for
200optimization (e.g. whether an argument is sign or zero extended,
201information about pointers aliasing, etc). Many of the enhancements are
202user-driven: people want LLVM to include some specific feature, so they
203go ahead and extend it.
204
205Third, it is *possible and easy* to add language-specific optimizations,
206and you have a number of choices in how to do it. As one trivial
207example, it is easy to add language-specific optimization passes that
208"know" things about code compiled for a language. In the case of the C
209family, there is an optimization pass that "knows" about the standard C
210library functions. If you call "exit(0)" in main(), it knows that it is
211safe to optimize that into "return 0;" because C specifies what the
212'exit' function does.
213
214In addition to simple library knowledge, it is possible to embed a
215variety of other language-specific information into the LLVM IR. If you
216have a specific need and run into a wall, please bring the topic up on
217the llvm-dev list. At the very worst, you can always treat LLVM as if it
218were a "dumb code generator" and implement the high-level optimizations
219you desire in your front-end, on the language-specific AST.
220
221Tips and Tricks
222===============
223
224There is a variety of useful tips and tricks that you come to know after
225working on/with LLVM that aren't obvious at first glance. Instead of
226letting everyone rediscover them, this section talks about some of these
227issues.
228
229Implementing portable offsetof/sizeof
230-------------------------------------
231
232One interesting thing that comes up, if you are trying to keep the code
233generated by your compiler "target independent", is that you often need
234to know the size of some LLVM type or the offset of some field in an
235llvm structure. For example, you might need to pass the size of a type
236into a function that allocates memory.
237
238Unfortunately, this can vary widely across targets: for example the
239width of a pointer is trivially target-specific. However, there is a
240`clever way to use the getelementptr
241instruction <http://nondot.org/sabre/LLVMNotes/SizeOf-OffsetOf-VariableSizedStructs.txt>`_
242that allows you to compute this in a portable way.
243
244Garbage Collected Stack Frames
245------------------------------
246
247Some languages want to explicitly manage their stack frames, often so
248that they are garbage collected or to allow easy implementation of
249closures. There are often better ways to implement these features than
250explicit stack frames, but `LLVM does support
251them, <http://nondot.org/sabre/LLVMNotes/ExplicitlyManagedStackFrames.txt>`_
252if you want. It requires your front-end to convert the code into
253`Continuation Passing
254Style <http://en.wikipedia.org/wiki/Continuation-passing_style>`_ and
255the use of tail calls (which LLVM also supports).
256