Fix up code-highlighting sections.
This commit is contained in:
parent
415c01f745
commit
ce8884aa33
18 changed files with 5611 additions and 6037 deletions
|
|
@ -13,34 +13,29 @@ References to functions already present in a module can be retrieved via
|
|||
``Function.get``. All functions in a module can be enumerated by
|
||||
iterating over ``module_obj.functions``.
|
||||
|
||||
{% highlight python %} # create a type, representing functions that take
|
||||
an integer and return # a floating point value. ft = Type.function(
|
||||
Type.float(), [ Type.int() ] )
|
||||
|
||||
create a function of this type
|
||||
==============================
|
||||
.. code-block:: python
|
||||
|
||||
f1 = module\_obj.add\_function(ft, "func1")
|
||||
# create a type, representing functions that take
|
||||
an integer and return # a floating point value. ft = Type.function(
|
||||
Type.float(), [ Type.int() ] )
|
||||
|
||||
# create a function of this type
|
||||
f1 = module_obj.add_function(ft, "func1")
|
||||
|
||||
# or equivalently, like this:
|
||||
f2 = Function.new(module_obj, ft, "func2")
|
||||
|
||||
# get a reference to an existing function
|
||||
f3 = module_obj.get_function_named("func3")
|
||||
|
||||
# or like this:
|
||||
f4 = Function.get(module_obj, "func4")
|
||||
|
||||
# list all function names in a module
|
||||
for f in module_obj.functions: print f.name
|
||||
|
||||
or equivalently, like this:
|
||||
===========================
|
||||
|
||||
f2 = Function.new(module\_obj, ft, "func2")
|
||||
|
||||
get a reference to an existing function
|
||||
=======================================
|
||||
|
||||
f3 = module\_obj.get\_function\_named("func3")
|
||||
|
||||
or like this:
|
||||
=============
|
||||
|
||||
f4 = Function.get(module\_obj, "func4")
|
||||
|
||||
list all function names in a module
|
||||
===================================
|
||||
|
||||
for f in module\_obj.functions: print f.name {% endhighlight %}
|
||||
|
||||
Intrinsic
|
||||
=========
|
||||
|
|
@ -52,13 +47,16 @@ called with a module object, an intrinsic ID (which is a numeric
|
|||
constant) and a list of the types of arguments (which LLVM uses to
|
||||
resolve overloaded intrinsic functions).
|
||||
|
||||
{% highlight python %} # get a reference to the llvm.bswap intrinsic
|
||||
bswap = Function.intrinsic(mod, INTR\_BSWAP, [Type.int()])
|
||||
|
||||
call it
|
||||
=======
|
||||
.. code-block:: python
|
||||
|
||||
# get a reference to the llvm.bswap intrinsic
|
||||
bswap = Function.intrinsic(mod, INTR_BSWAP, [Type.int()])
|
||||
|
||||
# call it
|
||||
builder.call(bswap, [value])
|
||||
|
||||
|
||||
builder.call(bswap, [value]) {% endhighlight %}
|
||||
|
||||
Here, the constant ``INTR_BSWAP``, available from ``llvm.core``,
|
||||
represents the LLVM intrinsic
|
||||
|
|
@ -111,13 +109,16 @@ The value objects corresponding to the arguments of a function can be
|
|||
got using the read-only property ``args``. These can be iterated over,
|
||||
and also be indexed via integers. An example:
|
||||
|
||||
{% highlight python %} # list all argument names and types for arg in
|
||||
fn.args: print arg.name, "of type", arg.type
|
||||
|
||||
change the name of the first argument
|
||||
=====================================
|
||||
.. code-block:: python
|
||||
|
||||
# list all argument names and types for arg in
|
||||
fn.args: print arg.name, "of type", arg.type
|
||||
|
||||
# change the name of the first argument
|
||||
fn.args[0].name = "objptr"
|
||||
|
||||
|
||||
fn.args[0].name = "objptr" {% endhighlight %}
|
||||
|
||||
Basic blocks (see later) are contained within functions. When newly
|
||||
created, a function has no basic blocks. They have to be added
|
||||
|
|
@ -130,71 +131,19 @@ blocks can be got via ``basic_block_count`` method. Note that
|
|||
``get_entry_basic_block`` is slightly faster than ``basic_blocks[0]``
|
||||
and so is ``basic_block_count``, over ``len(f.basic_blocks)``.
|
||||
|
||||
{% highlight python %} # add a basic block b1 =
|
||||
fn.append\_basic\_block("entry")
|
||||
|
||||
get the first one
|
||||
=================
|
||||
.. code-block:: python
|
||||
|
||||
b2 = fn.get\_entry\_basic\_block() b2 = fn.basic\_mdblocks[0] # slower
|
||||
than previous method
|
||||
|
||||
print names of all basic blocks
|
||||
===============================
|
||||
|
||||
for b in fn.basic\_blocks: print b.name
|
||||
|
||||
get number of basic blocks
|
||||
==========================
|
||||
|
||||
n = fn.basic\_block\_count n = len(fn.basic\_blocks) # slower than
|
||||
previous method {% endhighlight %}
|
||||
|
||||
Functions can be deleted using the method ``delete``. This deletes them
|
||||
from their containing module. All references to the function object
|
||||
should be dropped after ``delete`` has been called.
|
||||
|
||||
Functions can be verified with the ``verify`` method. Note that this may
|
||||
not work properly (aborts on errors).
|
||||
|
||||
Function Attributes # {#fnattr}
|
||||
===============================
|
||||
|
||||
Function attributes, as documented
|
||||
`here <http://www.llvm.org/docs/LangRef.html#fnattrs>`_, can be set on
|
||||
functions using the methods ``add_attribute`` and ``remove_attribute``.
|
||||
The following values may be used to refer to the LLVM attributes:
|
||||
|
||||
Value \| Equivalent LLVM Assembly Keyword \|
|
||||
------\|----------------------------------\|
|
||||
``ATTR_ALWAYS_INLINE``\ \|\ ``alwaysinline`` \|
|
||||
``ATTR_INLINE_HINT``\ \|\ ``inlinehint`` \|
|
||||
``ATTR_NO_INLINE``\ \|\ ``noinline`` \|
|
||||
``ATTR_OPTIMIZE_FOR_SIZE``\ \|\ ``optsize`` \|
|
||||
``ATTR_NO_RETURN``\ \|\ ``noreturn`` \|
|
||||
``ATTR_NO_UNWIND``\ \|\ ``nounwind`` \|
|
||||
``ATTR_READ_NONE``\ \|\ ``readnone`` \|
|
||||
``ATTR_READONLY``\ \|\ ``readonly`` \|
|
||||
``ATTR_STACK_PROTECT``\ \|\ ``ssp`` \|
|
||||
``ATTR_STACK_PROTECT_REQ``\ \|\ ``sspreq`` \|
|
||||
``ATTR_NO_REDZONE``\ \|\ ``noredzone`` \|
|
||||
``ATTR_NO_IMPLICIT_FLOAT``\ \|\ ``noimplicitfloat`` \|
|
||||
``ATTR_NAKED``\ \|\ ``naked`` \|
|
||||
|
||||
Here is how attributes can be set and removed:
|
||||
|
||||
{% highlight python %} # create a function ti = Type.int(32) tf =
|
||||
Type.function(ti, [ti, ti]) m = Module.new('mod') f =
|
||||
m.add\_function(tf, 'sum') print f # declare i32 @sum(i32, i32)
|
||||
|
||||
add a couple of attributes
|
||||
==========================
|
||||
|
||||
f.add\_attribute(ATTR\_NO\_UNWIND) f.add\_attribute(ATTR\_READONLY)
|
||||
print f # declare i32 @sum(i32, i32) nounwind readonly {% endhighlight
|
||||
%}
|
||||
|
||||
**Related Links**
|
||||
|
||||
`llvm.core.Function <llvm.core.Function.html>`_,
|
||||
`llvm.core.Argument <llvm.core.Argument.html>`_
|
||||
# add a basic block b1 =
|
||||
fn.append_basic_block("entry")
|
||||
|
||||
# get the first one
|
||||
b2 = fn.get_entry_basic_block() b2 = fn.basic_mdblocks[0] # slower
|
||||
than previous method
|
||||
|
||||
# print names of all basic blocks
|
||||
for b in fn.basic_blocks: print b.name
|
||||
|
||||
# get number of basic blocks
|
||||
n = fn.basic_block_count n = len(fn.basic_blocks) # slower than
|
||||
previous method
|
||||
|
|
|
|||
|
|
@ -78,8 +78,9 @@ object files be built with the ``-fPIC`` option (generate position
|
|||
independent code). Be sure to use the ``--enable-pic`` option while
|
||||
configuring LLVM (default is no PIC), like this:
|
||||
|
||||
{% highlight bash %} ~/llvm$ ./configure --enable-pic --enable-optimized
|
||||
{% endhighlight %}
|
||||
.. code-block:: bash
|
||||
|
||||
$ ~/llvm ./configure --enable-pic --enable-optimized
|
||||
|
||||
llvm-config
|
||||
-----------
|
||||
|
|
@ -103,51 +104,8 @@ LLVM's 'configure'.
|
|||
|
||||
Get llvmpy and install it:
|
||||
|
||||
{% highlight bash %} $ git clone git@github.com:numba/llvmpy.git $ cd
|
||||
llvmpy $ python setup.py install {% endhighlight %}
|
||||
|
||||
If you need to tell the build script where ``llvm-config`` is, do it
|
||||
this way:
|
||||
.. code-block:: bash
|
||||
|
||||
{% highlight bash %} $ python setup.py install --user
|
||||
--llvm-config=/home/mdevan/llvm/Release/bin/llvm-config {% endhighlight
|
||||
%}
|
||||
|
||||
To build a debug version of llvmpy, that links against the debug
|
||||
libraries of LLVM, use this:
|
||||
|
||||
{% highlight bash %} $ python setup.py build -g
|
||||
--llvm-config=/home/mdevan/llvm/Debug/bin/llvm-config $ python setup.py
|
||||
install --user --llvm-config=/home/mdevan/llvm/Debug/bin/llvm-config {%
|
||||
endhighlight %}
|
||||
|
||||
Be warned that debug binaries will be huge (100MB+) ! They are required
|
||||
only if you need to debug into LLVM also.
|
||||
|
||||
``setup.py`` is a standard Python distutils script. See the Python
|
||||
documentation regarding `Installing Python
|
||||
Modules <http://docs.python.org/inst/inst.html>`_ and `Distributing
|
||||
Python Modules <http://docs.python.org/dist/dist.html>`_ for more
|
||||
information on such scripts.
|
||||
|
||||
|
||||
Uninstall
|
||||
==============
|
||||
|
||||
If you'd installed llvmpy with the ``--user`` option, then llvmpy
|
||||
would be present under ``~/.local/lib/python2.7/site-packages``.
|
||||
Otherwise, it might be under ``/usr/lib/python2.7/site-packages`` or
|
||||
``/usr/local/lib/python2.7/site-packages``. The directory would vary
|
||||
with your Python version and OS flavour. Look around.
|
||||
|
||||
Once you've located the site-packages directory, the modules and the
|
||||
"egg" can be removed like so:
|
||||
|
||||
{% highlight bash %} $ rm -rf /llvm /llvm\_py-.egg-info {% endhighlight
|
||||
%}
|
||||
|
||||
See the `Python
|
||||
documentation <http://docs.python.org/install/index.html>`_ for more
|
||||
information.
|
||||
|
||||
--------------
|
||||
$ git clone git@github.com:numba/llvmpy.git $ cd
|
||||
llvmpy $ python setup.py install
|
||||
|
|
|
|||
|
|
@ -112,23 +112,36 @@ This gives the language a very nice and simple syntax. For example, the
|
|||
following simple example computes `Fibonacci
|
||||
numbers <http://en.wikipedia.org/wiki/Fibonacci_number>`_:
|
||||
|
||||
{% highlight python %} # Compute the x'th fibonacci number. def fib(x)
|
||||
if x < 3 then 1 else fib(x-1)+fib(x-2)
|
||||
|
||||
This expression will compute the 40th number.
|
||||
=============================================
|
||||
.. code-block::
|
||||
|
||||
# Compute the x'th fibonacci number.
|
||||
def fib(x):
|
||||
if x < 3:
|
||||
return 1
|
||||
else:
|
||||
return fib(x-1)+fib(x-2)
|
||||
|
||||
# This expression will compute the 40th number.
|
||||
fib(40)
|
||||
|
||||
|
||||
fib(40) {% endhighlight %}
|
||||
|
||||
We also allow Kaleidoscope to call into standard library functions (the
|
||||
LLVM JIT makes this completely trivial). This means that you can use the
|
||||
'extern' keyword to define a function before you use it (this is also
|
||||
useful for mutually recursive functions). For example:
|
||||
|
||||
{% highlight python %} extern sin(arg); extern cos(arg); extern
|
||||
atan2(arg1 arg2);
|
||||
|
||||
atan2(sin(0.4), cos(42)) {% endhighlight %}
|
||||
.. code-block::
|
||||
|
||||
extern sin(arg);
|
||||
extern cos(arg);
|
||||
extern atan2(arg1 arg2);
|
||||
|
||||
atan2(sin(0.4), cos(42))
|
||||
|
||||
|
||||
|
||||
A more interesting example is included in Chapter 6 where we write a
|
||||
little Kaleidoscope application that
|
||||
|
|
@ -150,23 +163,32 @@ traditional way to do this is to use a
|
|||
the lexer includes a token type and potentially some metadata (e.g. the
|
||||
numeric value of a number). First, we define the possibilities:
|
||||
|
||||
{% highlight python %} # The lexer yields one of these types for each
|
||||
token. class EOFToken(object): pass
|
||||
|
||||
class DefToken(object): pass
|
||||
.. code-block:: python
|
||||
|
||||
class ExternToken(object): pass
|
||||
# The lexer yields one of these types for each token.
|
||||
class EOFToken(object): pass
|
||||
|
||||
class DefToken(object): pass
|
||||
|
||||
class ExternToken(object): pass
|
||||
|
||||
class IdentifierToken(object):
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
class NumberToken(object):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
class CharacterToken(object):
|
||||
def __init__(self, char):
|
||||
self.char = char
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, CharacterToken) and self.char == other.char
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
class IdentifierToken(object): def **init**\ (self, name): self.name =
|
||||
name
|
||||
|
||||
class NumberToken(object): def **init**\ (self, value): self.value =
|
||||
value
|
||||
|
||||
class CharacterToken(object): def **init**\ (self, char): self.char =
|
||||
char def **eq**\ (self, other): return isinstance(other, CharacterToken)
|
||||
and self.char == other.char def **ne**\ (self, other): return not self
|
||||
== other {% endhighlight %}
|
||||
|
||||
Each token yielded by our lexer will be of one of the above types. For
|
||||
simple tokens that are always the same, like the "def" keyword, the
|
||||
|
|
@ -193,82 +215,109 @@ digits. Identifiers (and keywords) are alphanumeric string starting with
|
|||
a letter and comments are anything between a hash (``#``) and the end of
|
||||
the line.
|
||||
|
||||
{% highlight python %} import re
|
||||
|
||||
...
|
||||
.. code-block:: python
|
||||
|
||||
Regular expressions that tokens and comments of our language.
|
||||
=============================================================
|
||||
|
||||
REGEX\_NUMBER = re.compile('[0-9]+(?:.[0-9]+)?') REGEX\_IDENTIFIER =
|
||||
re.compile('[a-zA-Z][a-zA-Z0-9]\ *') REGEX\_COMMENT = re.compile('#.*')
|
||||
|
||||
{% endhighlight %}
|
||||
import re
|
||||
|
||||
...
|
||||
|
||||
# Regular expressions that tokens and comments of our language.
|
||||
REGEX_NUMBER = re.compile('[0-9]+(?:.[0-9]+)?')
|
||||
REGEX_IDENTIFIER = re.compile('[a-zA-Z][a-zA-Z0-9]\ *')
|
||||
REGEX_COMMENT = re.compile('#.*')
|
||||
|
||||
|
||||
Next, let's start defining the ``Tokenize`` function itself. The first
|
||||
thing we need to do is set up a loop that scans the string, while
|
||||
ignoring whitespace between tokens:
|
||||
|
||||
{% highlight python %} def Tokenize(string): while string: # Skip
|
||||
whitespace. if string[0].isspace(): string = string[1:] continue
|
||||
|
||||
::
|
||||
.. code-block:: python
|
||||
|
||||
def Tokenize(string):
|
||||
while string: # Skip whitespace.
|
||||
if string[0].isspace():
|
||||
string = string[1:]
|
||||
continue
|
||||
|
||||
::
|
||||
|
||||
...
|
||||
|
||||
|
||||
|
||||
...
|
||||
|
||||
{% endhighlight %}
|
||||
|
||||
Next we want to find out what the next token is. For this we run the
|
||||
regexes we defined above on the remainder of the string. To simplify the
|
||||
rest of the code, we run all three regexes each time. As mentioned
|
||||
above, inefficiencies are ignored for the purpose of this tutorial:
|
||||
|
||||
{% highlight python %} # Run regexes. comment\_match =
|
||||
REGEX\_COMMENT.match(string) number\_match = REGEX\_NUMBER.match(string)
|
||||
identifier\_match = REGEX\_IDENTIFIER.match(string) {% endhighlight %}
|
||||
|
||||
Now se check if any of the regexes matched. For comments, we simply
|
||||
.. code-block:: python
|
||||
|
||||
# Run regexes.
|
||||
comment_match = REGEX_COMMENT.match(string)
|
||||
number_match = REGEX_NUMBER.match(string)
|
||||
identifier_match = REGEX_IDENTIFIER.match(string)
|
||||
|
||||
|
||||
Now we check if any of the regexes matched. For comments, we simply
|
||||
ignore the captured match:
|
||||
|
||||
{% highlight python %} # Check if any of the regexes matched and yield
|
||||
the appropriate result. if comment\_match: comment =
|
||||
comment\_match.group(0) string = string[len(comment):] {% endhighlight
|
||||
python %}
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Check if any of the regexes matched and yield
|
||||
# the appropriate result.
|
||||
if comment_match:
|
||||
comment = comment_match.group(0)
|
||||
string = string[len(comment):]
|
||||
|
||||
For numbers, we yield the captured match, converted to a float and
|
||||
tagged with the appropriate token type:
|
||||
|
||||
{% highlight python %} elif number\_match: number =
|
||||
number\_match.group(0) yield NumberToken(float(number)) string =
|
||||
string[len(number):] {% endhighlight %}
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
elif number_match:
|
||||
number = number_match.group(0)
|
||||
yield NumberToken(float(number))
|
||||
string = string[len(number):]
|
||||
|
||||
The identifier case is a little more complex. We have to check for
|
||||
keywords to decide whether we have captured an identifier or a keyword:
|
||||
|
||||
{% highlight python %} elif identifier\_match: identifier =
|
||||
identifier\_match.group(0) # Check if we matched a keyword. if
|
||||
identifier == 'def': yield DefToken() elif identifier == 'extern': yield
|
||||
ExternToken() else: yield IdentifierToken(identifier) string =
|
||||
string[len(identifier):] {% endhighlight %}
|
||||
.. code-block:: python
|
||||
|
||||
elif identifier_match:
|
||||
identifier = identifier_match.group(0)
|
||||
# Check if we matched a keyword.
|
||||
if identifier == 'def':
|
||||
yield DefToken()
|
||||
elif identifier == 'extern':
|
||||
yield ExternToken()
|
||||
else:
|
||||
yield IdentifierToken(identifier)
|
||||
string = string[len(identifier):]
|
||||
|
||||
|
||||
Finally, if we haven't recognized a comment, a number of an identifier,
|
||||
we yield the current character as an "unknown character" token. This is
|
||||
used, for example, for operators like ``+`` or ``*``:
|
||||
|
||||
{% highlight python %} else: # Yield the unknown character. yield
|
||||
CharacterToken(string[0]) string = string[1:] {% endhighlight %}
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
else: # Yield the unknown character.
|
||||
yield CharacterToken(string[0])
|
||||
string = string[1:]
|
||||
|
||||
|
||||
Once we're done with the loop, we return a final end-of-file token:
|
||||
|
||||
{% highlight python %} yield EOFToken() {% endhighlight %}
|
||||
|
||||
With this, we have the complete lexer for the basic Kaleidoscope
|
||||
language (the `full code listing <PythonLangImpl2.html#code>`_ for the
|
||||
Lexer is available in the `next chapter <PythonLangImpl2.html>`_ of the
|
||||
tutorial). Next we'll `build a simple parser that uses this to build an
|
||||
Abstract Syntax Tree <PythonLangImpl2.html>`_. When we have that, we'll
|
||||
include a driver so that you can use the lexer and parser together.
|
||||
.. code-block:: python
|
||||
|
||||
--------------
|
||||
yield EOFToken()
|
||||
|
||||
**`Next: Implementing a Parser and AST <PythonLangImpl2.html>`_**
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,277 +0,0 @@
|
|||
*****************************************************************
|
||||
Chapter 8: Conclusion and other useful LLVM tidbits
|
||||
*****************************************************************
|
||||
|
||||
Written by `Chris Lattner <mailto:sabre@nondot.org>`_
|
||||
|
||||
|
||||
Tutorial Conclusion # {#conclusion}
|
||||
===================================
|
||||
|
||||
Welcome to the the final chapter of the `Implementing a language with
|
||||
LLVM <http://www.llvm.org/docs/tutorial/index.html>`_ tutorial. In the
|
||||
course of this tutorial, we have grown our little Kaleidoscope language
|
||||
from being a useless toy, to being a semi-interesting (but probably
|
||||
still useless) toy. :)
|
||||
|
||||
It is interesting to see how far we've come, and how little code it has
|
||||
taken. We built the entire lexer, parser, AST, code generator, and an
|
||||
interactive run-loop (with a JIT!) by-hand in under 540 lines of
|
||||
(non-comment/non-blank) code.
|
||||
|
||||
Our little language supports a couple of interesting features: it
|
||||
supports user defined binary and unary operators, it uses JIT
|
||||
compilation for immediate evaluation, and it supports a few control flow
|
||||
constructs with SSA construction.
|
||||
|
||||
Part of the idea of this tutorial was to show you how easy and fun it
|
||||
can be to define, build, and play with languages. Building a compiler
|
||||
need not be a scary or mystical process! Now that you've seen some of
|
||||
the basics, I strongly encourage you to take the code and hack on it.
|
||||
For example, try adding:
|
||||
|
||||
- **global variables** -- While global variables have questional value
|
||||
in modern software engineering, they are often useful when putting
|
||||
together quick little hacks like the Kaleidoscope compiler itself.
|
||||
Fortunately, our current setup makes it very easy to add global
|
||||
variables: just have value lookup check to see if an unresolved
|
||||
variable is in the global variable symbol table before rejecting it.
|
||||
To create a new global variable, make an instance of the LLVM
|
||||
``GlobalVariable`` class.
|
||||
|
||||
- **typed variables** -- Kaleidoscope currently only supports variables
|
||||
of type double. This gives the language a very nice elegance, because
|
||||
only supporting one type means that you never have to specify types.
|
||||
Different languages have different ways of handling this. The easiest
|
||||
way is to require the user to specify types for every variable
|
||||
definition, and record the type of the variable in the symbol table
|
||||
along with its Value\*.
|
||||
|
||||
- **arrays, structs, vectors, etc** -- Once you add types, you can
|
||||
start extending the type system in all sorts of interesting ways.
|
||||
Simple arrays are very easy and are quite useful for many different
|
||||
applications. Adding them is mostly an exercise in learning how the
|
||||
LLVM
|
||||
`getelementptr <http://www.llvm.org/docs/LangRef.html#i_getelementptr>`_
|
||||
instruction works: it is so nifty/unconventional, it `has its own
|
||||
FAQ <http://www.llvm.org/docs/GetElementPtr.html>`_! If you add
|
||||
support for recursive types (e.g. linked lists), make sure to read
|
||||
the `section in the LLVM Programmer's
|
||||
Manual <http://www.llvm.org/docs/ProgrammersManual.html#TypeResolve>`_
|
||||
that describes how to construct them.
|
||||
|
||||
- **standard runtime** -- Our current language allows the user to
|
||||
access arbitrary external functions, and we use it for things like
|
||||
"putchard". As you extend the language to add higher-level
|
||||
constructs, often these constructs make the most sense if they are
|
||||
lowered to calls into a language-supplied runtime. For example, if
|
||||
you add hash tables to the language, it would probably make sense to
|
||||
add the routines to a runtime, instead of inlining them all the way.
|
||||
|
||||
- **memory management** -- Currently we can only access the stack in
|
||||
Kaleidoscope. It would also be useful to be able to allocate heap
|
||||
memory, either with calls to the standard libc malloc/free interface
|
||||
or with a garbage collector. If you would like to use garbage
|
||||
collection, note that LLVM fully supports `Accurate Garbage
|
||||
Collection <http://www.llvm.org/docs/GarbageCollection.html>`_
|
||||
including algorithms that move objects and need to scan/update the
|
||||
stack.
|
||||
|
||||
- **debugger support** -- LLVM supports generation of `DWARF Debug
|
||||
info <http://www.llvm.org/docs/SourceLevelDebugging.html>`_ which is
|
||||
understood by common debuggers like GDB. Adding support for debug
|
||||
info is fairly straightforward. The best way to understand it is to
|
||||
compile some C/C++ code with "``llvm-gcc -g -O0``\ " and taking a
|
||||
look at what it produces.
|
||||
|
||||
- **exception handling support** - LLVM supports generation of `zero
|
||||
cost exceptions <http://www.llvm.org/docs/ExceptionHandling.html>`_
|
||||
which interoperate with code compiled in other languages. You could
|
||||
also generate code by implicitly making every function return an
|
||||
error value and checking it. You could also make explicit use of
|
||||
setjmp/longjmp. There are many different ways to go here.
|
||||
|
||||
- **object orientation, generics, database access, complex numbers,
|
||||
geometric programming, ...** -- Really, there is no end of crazy
|
||||
features that you can add to the language.
|
||||
|
||||
- **unusual domains** -- We've been talking about applying LLVM to a
|
||||
domain that many people are interested in: building a compiler for a
|
||||
specific language. However, there are many other domains that can use
|
||||
compiler technology that are not typically considered. For example,
|
||||
LLVM has been used to implement OpenGL graphics acceleration,
|
||||
translate C++ code to ActionScript, and many other cute and clever
|
||||
things. Maybe you will be the first to JIT compile a regular
|
||||
expression interpreter into native code with LLVM?
|
||||
|
||||
Have fun - try doing something crazy and unusual. Building a language
|
||||
like everyone else always has, is much less fun than trying something a
|
||||
little crazy or off the wall and seeing how it turns out. If you get
|
||||
stuck or want to talk about it, feel free to email the `llvmdev mailing
|
||||
list <http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev>`_: it has lots
|
||||
of people who are interested in languages and are often willing to help
|
||||
out.
|
||||
|
||||
Before we end this tutorial, I want to talk about some "tips and tricks"
|
||||
for generating LLVM IR. These are some of the more subtle things that
|
||||
may not be obvious, but are very useful if you want to take advantage of
|
||||
LLVM's capabilities.
|
||||
|
||||
--------------
|
||||
|
||||
Properties of the LLVM IR # {#llvmirproperties}
|
||||
===============================================
|
||||
|
||||
We have a couple common questions about code in the LLVM IR form - let's
|
||||
just get these out of the way right now, shall we?
|
||||
|
||||
Target Independence ## {#targetindep}
|
||||
-------------------------------------
|
||||
|
||||
Kaleidoscope is an example of a "portable language": any program written
|
||||
in Kaleidoscope will work the same way on any target that it runs on.
|
||||
Many other languages have this property, e.g. LISP, Java, Haskell,
|
||||
Javascript, Python, etc. (note that while these languages are portable,
|
||||
not all their libraries are).
|
||||
|
||||
One nice aspect of LLVM is that it is often capable of preserving target
|
||||
independence in the IR: you can take the LLVM IR for a
|
||||
Kaleidoscope-compiled program and run it on any target that LLVM
|
||||
supports, even emitting C code and compiling that on targets that LLVM
|
||||
doesn't support natively. You can trivially tell that the Kaleidoscope
|
||||
compiler generates target-independent code because it never queries for
|
||||
any target-specific information when generating code.
|
||||
|
||||
The fact that LLVM provides a compact, target-independent,
|
||||
representation for code gets a lot of people excited. Unfortunately,
|
||||
these people are usually thinking about C or a language from the C
|
||||
family when they are asking questions about language portability. I say
|
||||
"unfortunately", because there is really no way to make (fully general)
|
||||
C code portable, other than shipping the source code around (and of
|
||||
course, C source code is not actually portable in general either - ever
|
||||
port a really old application from 32- to 64-bits?).
|
||||
|
||||
The problem with C (again, in its full generality) is that it is heavily
|
||||
laden with target specific assumptions. As one simple example, the
|
||||
preprocessor often destructively removes target-independence from the
|
||||
code when it processes the input text:
|
||||
|
||||
{% highlight c %} #ifdef **i386** int X = 1; #else int X = 42; #endif {%
|
||||
endhighlight %}
|
||||
|
||||
While it is possible to engineer more and more complex solutions to
|
||||
problems like this, it cannot be solved in full generality in a way that
|
||||
is better than shipping the actual source code.
|
||||
|
||||
That said, there are interesting subsets of C that can be made portable.
|
||||
If you are willing to fix primitive types to a fixed size (say int =
|
||||
32-bits, and long = 64-bits), don't care about ABI compatibility with
|
||||
existing binaries, and are willing to give up some other minor features,
|
||||
you can have portable code. This can make sense for specialized domains
|
||||
such as an in-kernel language.
|
||||
|
||||
Safety Guarantees ## {#safety}
|
||||
------------------------------
|
||||
|
||||
Many of the languages above are also "safe" languages: it is impossible
|
||||
for a program written in Java to corrupt its address space and crash the
|
||||
process (assuming the JVM has no bugs). Safety is an interesting
|
||||
property that requires a combination of language design, runtime
|
||||
support, and often operating system support.
|
||||
|
||||
It is certainly possible to implement a safe language in LLVM, but LLVM
|
||||
IR does not itself guarantee safety. The LLVM IR allows unsafe pointer
|
||||
casts, use after free bugs, buffer over-runs, and a variety of other
|
||||
problems. Safety needs to be implemented as a layer on top of LLVM and,
|
||||
conveniently, several groups have investigated this. Ask on the `llvmdev
|
||||
mailing list <http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev>`_ if
|
||||
you are interested in more details.
|
||||
|
||||
Language-Specific Optimizations ## {#langspecific}
|
||||
--------------------------------------------------
|
||||
|
||||
One thing about LLVM that turns off many people is that it does not
|
||||
solve all the world's problems in one system (sorry 'world hunger',
|
||||
someone else will have to solve you some other day). One specific
|
||||
complaint is that people perceive LLVM as being incapable of performing
|
||||
high-level language-specific optimization: LLVM "loses too much
|
||||
information".
|
||||
|
||||
Unfortunately, this is really not the place to give you a full and
|
||||
unified version of "Chris Lattner's theory of compiler design". Instead,
|
||||
I'll make a few observations:
|
||||
|
||||
First, you're right that LLVM does lose information. For example, as of
|
||||
this writing, there is no way to distinguish in the LLVM IR whether an
|
||||
SSA-value came from a C "int" or a C "long" on an ILP32 machine (other
|
||||
than debug info). Both get compiled down to an 'i32' value and the
|
||||
information about what it came from is lost. The more general issue
|
||||
here, is that the LLVM type system uses "structural equivalence" instead
|
||||
of "name equivalence". Another place this surprises people is if you
|
||||
have two types in a high-level language that have the same structure
|
||||
(e.g. two different structs that have a single int field): these types
|
||||
will compile down into a single LLVM type and it will be impossible to
|
||||
tell what it came from.
|
||||
|
||||
Second, while LLVM does lose information, LLVM is not a fixed target: we
|
||||
continue to enhance and improve it in many different ways. In addition
|
||||
to adding new features (LLVM did not always support exceptions or debug
|
||||
info), we also extend the IR to capture important information for
|
||||
optimization (e.g. whether an argument is sign or zero extended,
|
||||
information about pointers aliasing, etc). Many of the enhancements are
|
||||
user-driven: people want LLVM to include some specific feature, so they
|
||||
go ahead and extend it.
|
||||
|
||||
Third, it is *possible and easy* to add language-specific optimizations,
|
||||
and you have a number of choices in how to do it. As one trivial
|
||||
example, it is easy to add language-specific optimization passes that
|
||||
"know" things about code compiled for a language. In the case of the C
|
||||
family, there is an optimization pass that "knows" about the standard C
|
||||
library functions. If you call "exit(0)" in main(), it knows that it is
|
||||
safe to optimize that into "return 0;" because C specifies what the
|
||||
'exit' function does.
|
||||
|
||||
In addition to simple library knowledge, it is possible to embed a
|
||||
variety of other language-specific information into the LLVM IR. If you
|
||||
have a specific need and run into a wall, please bring the topic up on
|
||||
the llvmdev list. At the very worst, you can always treat LLVM as if it
|
||||
were a "dumb code generator" and implement the high-level optimizations
|
||||
you desire in your front-end, on the language-specific AST.
|
||||
|
||||
--------------
|
||||
|
||||
Tips and Tricks # {#tipsandtricks}
|
||||
==================================
|
||||
|
||||
There is a variety of useful tips and tricks that you come to know after
|
||||
working on/with LLVM that aren't obvious at first glance. Instead of
|
||||
letting everyone rediscover them, this section talks about some of these
|
||||
issues.
|
||||
|
||||
Implementing portable offsetof/sizeof ## {#offsetofsizeof}
|
||||
----------------------------------------------------------
|
||||
|
||||
One interesting thing that comes up, if you are trying to keep the code
|
||||
generated by your compiler "target independent", is that you often need
|
||||
to know the size of some LLVM type or the offset of some field in an
|
||||
llvm structure. For example, you might need to pass the size of a type
|
||||
into a function that allocates memory.
|
||||
|
||||
Unfortunately, this can vary widely across targets: for example the
|
||||
width of a pointer is trivially target-specific. However, there is a
|
||||
`clever way to use the getelementptr
|
||||
instruction <http://nondot.org/sabre/LLVMNotes/SizeOf-OffsetOf-VariableSizedStructs.txt>`_
|
||||
that allows you to compute this in a portable way.
|
||||
|
||||
Garbage Collected Stack Frames ## {#gcstack}
|
||||
--------------------------------------------
|
||||
|
||||
Some languages want to explicitly manage their stack frames, often so
|
||||
that they are garbage collected or to allow easy implementation of
|
||||
closures. There are often better ways to implement these features than
|
||||
explicit stack frames, but `LLVM does support
|
||||
them <http://nondot.org/sabre/LLVMNotes/ExplicitlyManagedStackFrames.txt>`_,
|
||||
if you want. It requires your front-end to convert the code into
|
||||
`Continuation Passing
|
||||
Style <http://en.wikipedia.org/wiki/Continuation-passing_style>`_ and
|
||||
the use of tail calls (which LLVM also supports).
|
||||
|
|
@ -11,344 +11,343 @@ created from Python constants. A constant expression is also a constant
|
|||
etc) can be specified, to yield a new ``Constant`` object. Let's see
|
||||
some examples:
|
||||
|
||||
{% highlight python %} #!/usr/bin/env python
|
||||
|
||||
ti = Type.int() # a 32-bit int type
|
||||
.. code-block:: python
|
||||
|
||||
k1 = Constant.int(ti, 42) # "int k1 = 42;" k2 = k1.add( Constant.int(
|
||||
ti, 10 ) ) # "int k2 = k1 + 10;"
|
||||
|
||||
tr = Type.float()
|
||||
|
||||
r1 = Constant.real(tr, "3.141592") # create from a string r2 =
|
||||
Constant.real(tr, 1.61803399) # create from a Python float {%
|
||||
endhighlight %}
|
||||
|
||||
llvm.core.Constant
|
||||
==================
|
||||
|
||||
- This will become a table of contents (this text will be scraped).
|
||||
#!/usr/bin/env python
|
||||
|
||||
ti = Type.int() # a 32-bit int type
|
||||
|
||||
k1 = Constant.int(ti, 42) # "int k1 = 42;" k2 = k1.add( Constant.int(
|
||||
ti, 10 ) ) # "int k2 = k1 + 10;"
|
||||
|
||||
tr = Type.float()
|
||||
|
||||
r1 = Constant.real(tr, "3.141592") # create from a string r2 =
|
||||
Constant.real(tr, 1.61803399) # create from a Python float {%
|
||||
endhighlight %}
|
||||
|
||||
# llvm.core.Constant
|
||||
- This will become a table of contents (this text will be scraped).
|
||||
{:toc}
|
||||
|
||||
Static factory methods
|
||||
----------------------
|
||||
|
||||
``null(ty)``
|
||||
~~~~~~~~~~~~
|
||||
|
||||
A null value (all zeros) of type ``ty``
|
||||
|
||||
``all_ones(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
All 1's value of type ``ty``
|
||||
|
||||
``undef(ty)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
An undefined value of type ``ty``
|
||||
|
||||
``int(ty, value)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Integer of type ``ty``, with value ``value`` (a Python int or long)
|
||||
|
||||
``int_signextend(ty, value)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Integer of signed type ``ty`` (use for signed types)
|
||||
|
||||
``real(ty, value)``
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Floating point value of type ``ty``, with value ``value`` (a Python
|
||||
float)
|
||||
|
||||
``stringz(value)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
A null-terminated string. ``value`` is a Python string
|
||||
|
||||
``string(value)``
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
As ``string(ty)``, but not null terminated
|
||||
|
||||
``array(ty, consts)``
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Array of type ``ty``, initialized with ``consts`` (an iterable yielding
|
||||
``Constant`` objects of the appropriate type)
|
||||
|
||||
``struct(ty, consts)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Struct (unpacked) of type ``ty``, initialized with ``consts`` (an
|
||||
iterable yielding ``Constant`` objects of the appropriate type)
|
||||
|
||||
``packed_struct(ty, consts)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
As ``struct(ty, consts)`` but packed
|
||||
|
||||
``vector(consts)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Vector, initialized with ``consts`` (an iterable yielding ``Constant``
|
||||
objects of the appropriate type)
|
||||
|
||||
``sizeof(ty)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Constant value representing the sizeof the type ``ty``
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
The following operations on constants are supported. For more details on
|
||||
any operation, consult the `Constant
|
||||
Expressions <http://www.llvm.org/docs/LangRef.html#constantexprs>`_
|
||||
section of the LLVM Language Reference.
|
||||
|
||||
``k.neg()``
|
||||
~~~~~~~~~~~
|
||||
|
||||
negation, same as ``0 - k``
|
||||
|
||||
``k.not_()``
|
||||
~~~~~~~~~~~~
|
||||
|
||||
1's complement of ``k``. Note trailing underscore.
|
||||
|
||||
``k.add(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
``k + k2``, where ``k`` and ``k2`` are integers.
|
||||
|
||||
``k.fadd(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
``k + k2``, where ``k`` and ``k2`` are floating-point.
|
||||
|
||||
``k.sub(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
``k - k2``, where ``k`` and ``k2`` are integers.
|
||||
|
||||
``k.fsub(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
``k - k2``, where ``k`` and ``k2`` are floating-point.
|
||||
|
||||
``k.mul(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
``k * k2``, where ``k`` and ``k2`` are integers.
|
||||
|
||||
``k.fmul(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
``k * k2``, where ``k`` and ``k2`` are floating-point.
|
||||
|
||||
``k.udiv(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Quotient of unsigned division of ``k`` with ``k2``
|
||||
|
||||
``k.sdiv(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Quotient of signed division of ``k`` with ``k2``
|
||||
|
||||
``k.fdiv(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Quotient of floating point division of ``k`` with ``k2``
|
||||
|
||||
``k.urem(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Reminder of unsigned division of ``k`` with ``k2``
|
||||
|
||||
``k.srem(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Reminder of signed division of ``k`` with ``k2``
|
||||
|
||||
``k.frem(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Reminder of floating point division of ``k`` with ``k2``
|
||||
|
||||
``k.and_(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Bitwise and of ``k`` and ``k2``. Note trailing underscore.
|
||||
|
||||
``k.or_(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
Bitwise or of ``k`` and ``k2``. Note trailing underscore.
|
||||
|
||||
``k.xor(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
Bitwise exclusive-or of ``k`` and ``k2``.
|
||||
|
||||
``k.icmp(icmp, k2)``
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Compare ``k`` with ``k2`` using the predicate ``icmp``. See
|
||||
`here <comparision.html#icmp>`_ for list of predicates for integer
|
||||
operands.
|
||||
|
||||
``k.fcmp(fcmp, k2)``
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Compare ``k`` with ``k2`` using the predicate ``fcmp``. See
|
||||
`here <comparision.html#fcmp>`_ for list of predicates for real
|
||||
operands.
|
||||
|
||||
``k.shl(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
Shift ``k`` left by ``k2`` bits.
|
||||
|
||||
``k.lshr(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Shift ``k`` logically right by ``k2`` bits (new bits are 0s).
|
||||
|
||||
``k.ashr(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Shift ``k`` arithmetically right by ``k2`` bits (new bits are same as
|
||||
previous sign bit).
|
||||
|
||||
``k.gep(indices)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
GEP, see `LLVM docs <http://www.llvm.org/docs/GetElementPtr.html>`_.
|
||||
|
||||
``k.trunc(ty)``
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Truncate ``k`` to a type ``ty`` of lower bitwidth.
|
||||
|
||||
``k.sext(ty)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Sign extend ``k`` to a type ``ty`` of higher bitwidth, while extending
|
||||
the sign bit.
|
||||
|
||||
``k.zext(ty)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Sign extend ``k`` to a type ``ty`` of higher bitwidth, all new bits are
|
||||
0s.
|
||||
|
||||
``k.fptrunc(ty)``
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
Truncate floating point constant ``k`` to floating point type ``ty`` of
|
||||
lower size than k's.
|
||||
|
||||
``k.fpext(ty)``
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Extend floating point constant ``k`` to floating point type ``ty`` of
|
||||
higher size than k's.
|
||||
|
||||
``k.uitofp(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert an unsigned integer constant ``k`` to floating point constant of
|
||||
type ``ty``.
|
||||
|
||||
``k.sitofp(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert a signed integer constant ``k`` to floating point constant of
|
||||
type ``ty``.
|
||||
|
||||
``k.fptoui(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert a floating point constant ``k`` to an unsigned integer constant
|
||||
of type ``ty``.
|
||||
|
||||
``k.fptosi(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert a floating point constant ``k`` to a signed integer constant of
|
||||
type ``ty``.
|
||||
|
||||
``k.ptrtoint(ty)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert a pointer constant ``k`` to an integer constant of type ``ty``.
|
||||
|
||||
``k.inttoptr(ty)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert an integer constant ``k`` to a pointer constant of type ``ty``.
|
||||
|
||||
``k.bitcast(ty)``
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert ``k`` to a (equal-width) constant of type ``ty``.
|
||||
|
||||
``k.select(cond,k2,k3)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Replace value with ``k2`` if the 1-bit integer constant ``cond`` is 1,
|
||||
else with ``k3``.
|
||||
|
||||
``k.extract_element(idx)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Extract value at ``idx`` (integer constant) from a vector constant
|
||||
``k``.
|
||||
|
||||
``k.insert_element(k2,idx)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Insert value ``k2`` (scalar constant) at index ``idx`` (integer
|
||||
constant) of vector constant ``k``.
|
||||
|
||||
``k.shuffle_vector(k2,mask)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Shuffle vector constant ``k`` based on vector constants ``k2`` and
|
||||
``mask``.
|
||||
|
||||
--------------
|
||||
|
||||
Other Constant Classes
|
||||
======================
|
||||
|
||||
The following subclasses of ``Constant`` do not provide additional
|
||||
methods, **they serve only to provide richer type information.**
|
||||
|
||||
Subclass \| LLVM C++ Class \| Remarks \|
|
||||
---------\|----------------\|---------\| ``ConstantExpr`` \|
|
||||
``llvmConstantExpr`` \| A constant expression \|
|
||||
``ConstantAggregateZero``\ \| ``llvmConstantAggregateZero``\ \| All-zero
|
||||
constant \| ``ConstantInt``\ \| ``llvmConstantInt``\ \| An integer
|
||||
constant \| ``ConstantFP``\ \| ``llvmConstantFP``\ \| A floating-point
|
||||
constant \| ``ConstantArray``\ \| ``llvmConstantArray``\ \| An array
|
||||
constant \| ``ConstantStruct``\ \| ``llvmConstantStruct``\ \| A
|
||||
structure constant \| ``ConstantVector``\ \| ``llvmConstantVector``\ \|
|
||||
A vector constant \| ``ConstantPointerNull``\ \|
|
||||
``llvmConstantPointerNull``\ \| All-zero pointer constant \|
|
||||
``UndefValue``\ \| ``llvmUndefValue``\ \| corresponds to ``undef`` of
|
||||
LLVM IR \|
|
||||
|
||||
These types are helpful in ``isinstance`` checks, like so:
|
||||
|
||||
{% highlight python %} ti = Type.int(32) k1 = Constant.int(ti, 42) #
|
||||
int32\_t k1 = 42; k2 = Constant.array(ti, [k1, k1]) # int32\_t k2[] = {
|
||||
k1, k1 };
|
||||
|
||||
assert isinstance(k1, ConstantInt) assert isinstance(k2, ConstantArray)
|
||||
{% endhighlight %}
|
||||
|
||||
Static factory methods
|
||||
----------------------
|
||||
|
||||
``null(ty)``
|
||||
~~~~~~~~~~~~
|
||||
|
||||
A null value (all zeros) of type ``ty``
|
||||
|
||||
``all_ones(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
All 1's value of type ``ty``
|
||||
|
||||
``undef(ty)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
An undefined value of type ``ty``
|
||||
|
||||
``int(ty, value)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Integer of type ``ty``, with value ``value`` (a Python int or long)
|
||||
|
||||
``int_signextend(ty, value)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Integer of signed type ``ty`` (use for signed types)
|
||||
|
||||
``real(ty, value)``
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Floating point value of type ``ty``, with value ``value`` (a Python
|
||||
float)
|
||||
|
||||
``stringz(value)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
A null-terminated string. ``value`` is a Python string
|
||||
|
||||
``string(value)``
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
As ``string(ty)``, but not null terminated
|
||||
|
||||
``array(ty, consts)``
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Array of type ``ty``, initialized with ``consts`` (an iterable yielding
|
||||
``Constant`` objects of the appropriate type)
|
||||
|
||||
``struct(ty, consts)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Struct (unpacked) of type ``ty``, initialized with ``consts`` (an
|
||||
iterable yielding ``Constant`` objects of the appropriate type)
|
||||
|
||||
``packed_struct(ty, consts)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
As ``struct(ty, consts)`` but packed
|
||||
|
||||
``vector(consts)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Vector, initialized with ``consts`` (an iterable yielding ``Constant``
|
||||
objects of the appropriate type)
|
||||
|
||||
``sizeof(ty)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Constant value representing the sizeof the type ``ty``
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
The following operations on constants are supported. For more details on
|
||||
any operation, consult the `Constant
|
||||
Expressions <http://www.llvm.org/docs/LangRef.html#constantexprs>`_
|
||||
section of the LLVM Language Reference.
|
||||
|
||||
``k.neg()``
|
||||
~~~~~~~~~~~
|
||||
|
||||
negation, same as ``0 - k``
|
||||
|
||||
``k.not_()``
|
||||
~~~~~~~~~~~~
|
||||
|
||||
1's complement of ``k``. Note trailing underscore.
|
||||
|
||||
``k.add(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
``k + k2``, where ``k`` and ``k2`` are integers.
|
||||
|
||||
``k.fadd(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
``k + k2``, where ``k`` and ``k2`` are floating-point.
|
||||
|
||||
``k.sub(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
``k - k2``, where ``k`` and ``k2`` are integers.
|
||||
|
||||
``k.fsub(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
``k - k2``, where ``k`` and ``k2`` are floating-point.
|
||||
|
||||
``k.mul(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
``k * k2``, where ``k`` and ``k2`` are integers.
|
||||
|
||||
``k.fmul(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
``k * k2``, where ``k`` and ``k2`` are floating-point.
|
||||
|
||||
``k.udiv(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Quotient of unsigned division of ``k`` with ``k2``
|
||||
|
||||
``k.sdiv(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Quotient of signed division of ``k`` with ``k2``
|
||||
|
||||
``k.fdiv(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Quotient of floating point division of ``k`` with ``k2``
|
||||
|
||||
``k.urem(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Reminder of unsigned division of ``k`` with ``k2``
|
||||
|
||||
``k.srem(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Reminder of signed division of ``k`` with ``k2``
|
||||
|
||||
``k.frem(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Reminder of floating point division of ``k`` with ``k2``
|
||||
|
||||
``k.and_(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Bitwise and of ``k`` and ``k2``. Note trailing underscore.
|
||||
|
||||
``k.or_(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
Bitwise or of ``k`` and ``k2``. Note trailing underscore.
|
||||
|
||||
``k.xor(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
Bitwise exclusive-or of ``k`` and ``k2``.
|
||||
|
||||
``k.icmp(icmp, k2)``
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Compare ``k`` with ``k2`` using the predicate ``icmp``. See
|
||||
`here <comparision.html#icmp>`_ for list of predicates for integer
|
||||
operands.
|
||||
|
||||
``k.fcmp(fcmp, k2)``
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Compare ``k`` with ``k2`` using the predicate ``fcmp``. See
|
||||
`here <comparision.html#fcmp>`_ for list of predicates for real
|
||||
operands.
|
||||
|
||||
``k.shl(k2)``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
Shift ``k`` left by ``k2`` bits.
|
||||
|
||||
``k.lshr(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Shift ``k`` logically right by ``k2`` bits (new bits are 0s).
|
||||
|
||||
``k.ashr(k2)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Shift ``k`` arithmetically right by ``k2`` bits (new bits are same as
|
||||
previous sign bit).
|
||||
|
||||
``k.gep(indices)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
GEP, see `LLVM docs <http://www.llvm.org/docs/GetElementPtr.html>`_.
|
||||
|
||||
``k.trunc(ty)``
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Truncate ``k`` to a type ``ty`` of lower bitwidth.
|
||||
|
||||
``k.sext(ty)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Sign extend ``k`` to a type ``ty`` of higher bitwidth, while extending
|
||||
the sign bit.
|
||||
|
||||
``k.zext(ty)``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Sign extend ``k`` to a type ``ty`` of higher bitwidth, all new bits are
|
||||
0s.
|
||||
|
||||
``k.fptrunc(ty)``
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
Truncate floating point constant ``k`` to floating point type ``ty`` of
|
||||
lower size than k's.
|
||||
|
||||
``k.fpext(ty)``
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Extend floating point constant ``k`` to floating point type ``ty`` of
|
||||
higher size than k's.
|
||||
|
||||
``k.uitofp(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert an unsigned integer constant ``k`` to floating point constant of
|
||||
type ``ty``.
|
||||
|
||||
``k.sitofp(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert a signed integer constant ``k`` to floating point constant of
|
||||
type ``ty``.
|
||||
|
||||
``k.fptoui(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert a floating point constant ``k`` to an unsigned integer constant
|
||||
of type ``ty``.
|
||||
|
||||
``k.fptosi(ty)``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert a floating point constant ``k`` to a signed integer constant of
|
||||
type ``ty``.
|
||||
|
||||
``k.ptrtoint(ty)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert a pointer constant ``k`` to an integer constant of type ``ty``.
|
||||
|
||||
``k.inttoptr(ty)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert an integer constant ``k`` to a pointer constant of type ``ty``.
|
||||
|
||||
``k.bitcast(ty)``
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
Convert ``k`` to a (equal-width) constant of type ``ty``.
|
||||
|
||||
``k.select(cond,k2,k3)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Replace value with ``k2`` if the 1-bit integer constant ``cond`` is 1,
|
||||
else with ``k3``.
|
||||
|
||||
``k.extract_element(idx)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Extract value at ``idx`` (integer constant) from a vector constant
|
||||
``k``.
|
||||
|
||||
``k.insert_element(k2,idx)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Insert value ``k2`` (scalar constant) at index ``idx`` (integer
|
||||
constant) of vector constant ``k``.
|
||||
|
||||
``k.shuffle_vector(k2,mask)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Shuffle vector constant ``k`` based on vector constants ``k2`` and
|
||||
``mask``.
|
||||
|
||||
--------------
|
||||
|
||||
# Other Constant Classes
|
||||
The following subclasses of ``Constant`` do not provide additional
|
||||
methods, **they serve only to provide richer type information.**
|
||||
|
||||
Subclass \| LLVM C++ Class \| Remarks \|
|
||||
---------\|----------------\|---------\| ``ConstantExpr`` \|
|
||||
``llvmConstantExpr`` \| A constant expression \|
|
||||
``ConstantAggregateZero``\ \| ``llvmConstantAggregateZero``\ \| All-zero
|
||||
constant \| ``ConstantInt``\ \| ``llvmConstantInt``\ \| An integer
|
||||
constant \| ``ConstantFP``\ \| ``llvmConstantFP``\ \| A floating-point
|
||||
constant \| ``ConstantArray``\ \| ``llvmConstantArray``\ \| An array
|
||||
constant \| ``ConstantStruct``\ \| ``llvmConstantStruct``\ \| A
|
||||
structure constant \| ``ConstantVector``\ \| ``llvmConstantVector``\ \|
|
||||
A vector constant \| ``ConstantPointerNull``\ \|
|
||||
``llvmConstantPointerNull``\ \| All-zero pointer constant \|
|
||||
``UndefValue``\ \| ``llvmUndefValue``\ \| corresponds to ``undef`` of
|
||||
LLVM IR \|
|
||||
|
||||
These types are helpful in ``isinstance`` checks, like so:
|
||||
|
||||
{% highlight python %} ti = Type.int(32) k1 = Constant.int(ti, 42) #
|
||||
int32_t k1 = 42; k2 = Constant.array(ti, [k1, k1]) # int32_t k2[] = {
|
||||
k1, k1 };
|
||||
|
||||
assert isinstance(k1, ConstantInt) assert isinstance(k2, ConstantArray)
|
||||
|
||||
|
|
|
|||
|
|
@ -39,14 +39,10 @@ Returns an iterable object that yields `Type <llvm.core.Type.html>`_
|
|||
objects that represent, in order, the types of the arguments accepted by
|
||||
the function. Used like this:
|
||||
|
||||
{% highlight python %} func\_type = Type.function( Type.int(), [
|
||||
Type.int(), Type.int() ] ) for arg in func\_type.args: assert arg.kind
|
||||
== TYPE\_INTEGER assert arg == Type.int() assert func\_type.arg\_count
|
||||
== len(func\_type.args) {% endhighlight %}
|
||||
|
||||
``arg_count``
|
||||
~~~~~~~~~~~~~
|
||||
.. code-block:: python
|
||||
|
||||
[read-only]
|
||||
|
||||
The number of arguments. Same as ``len(obj.args)``, but faster.
|
||||
func_type = Type.function( Type.int(), [
|
||||
Type.int(), Type.int() ] ) for arg in func_type.args: assert arg.kind
|
||||
== TYPE_INTEGER assert arg == Type.int() assert func_type.arg_count
|
||||
== len(func_type.args)
|
||||
|
|
|
|||
|
|
@ -11,93 +11,29 @@ marked as constants. Global variables can be created either by using the
|
|||
``add_global_variable`` method of the `Module <llvm.core.Module.html>`_
|
||||
class, or by using the static method ``GlobalVariable.new``.
|
||||
|
||||
{% highlight python %} # create a global variable using
|
||||
add\_global\_variable method gv1 =
|
||||
module\_obj.add\_global\_variable(Type.int(), "gv1")
|
||||
|
||||
or equivalently, using a static constructor method
|
||||
==================================================
|
||||
.. code-block:: python
|
||||
|
||||
gv2 = GlobalVariable.new(module\_obj, Type.int(), "gv2") {% endhighlight
|
||||
%}
|
||||
|
||||
Existing global variables of a module can be accessed by name using
|
||||
``module_obj.get_global_variable_named(name)`` or
|
||||
``GlobalVariable.get``. All existing global variables can be enumerated
|
||||
via iterating over the property ``module_obj.global_variables``.
|
||||
|
||||
{% highlight python %} # retrieve a reference to the global variable
|
||||
gv1, # using the get\_global\_variable\_named method gv1 =
|
||||
module\_obj.get\_global\_variable\_named("gv1")
|
||||
|
||||
or equivalently, using the static ``get`` method:
|
||||
=================================================
|
||||
|
||||
gv2 = GlobalVariable.get(module\_obj, "gv2")
|
||||
|
||||
list all global variables in a module
|
||||
=====================================
|
||||
|
||||
for gv in module\_obj.global\_variables: print gv.name, "of type",
|
||||
gv.type {% endhighlight %}
|
||||
|
||||
The initializer for a global variable can be set by assigning to the
|
||||
``initializer`` property of the object. The ``is_global_constant``
|
||||
property can be used to indicate that the variable is a global constant.
|
||||
|
||||
Global variables can be delete using the ``delete`` method. Do not use
|
||||
the object after calling ``delete`` on it.
|
||||
|
||||
{% highlight python %} # add an initializer 10 (32-bit integer)
|
||||
gv.initializer = Constant.int( Type.int(), 10 )
|
||||
|
||||
delete the global
|
||||
=================
|
||||
|
||||
gv.delete() # DO NOT dereference \`gv' beyond this point! gv = None {%
|
||||
endhighlight %}
|
||||
|
||||
llvm.core.GlobalVariable
|
||||
========================
|
||||
|
||||
Base Class
|
||||
----------
|
||||
|
||||
- `llvm.core.GlobalValue <llvm.core.GlobalValue.html>`_
|
||||
|
||||
Static Constructors
|
||||
-------------------
|
||||
|
||||
``new(module_obj, ty, name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create a global variable named ``name`` of type ``ty`` in the module
|
||||
``module_obj`` and return a ``GlobalVariable`` object that represents
|
||||
it.
|
||||
|
||||
``get(module_obj, name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Return a ``GlobalVariable`` object to represent the global variable
|
||||
named ``name`` in the module ``module_obj`` or raise ``LLVMException``
|
||||
if such a variable does not exist.
|
||||
|
||||
Properties
|
||||
----------
|
||||
|
||||
``initializer``
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
The intializer of the variable. Set to
|
||||
`llvm.core.Constant <llvm.core.Constant.html>`_ (or derived). Gets the
|
||||
initializer constant, or ``None`` if none exists. ``global_constant``
|
||||
``True`` if the variable is a global constant, ``False`` otherwise.
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
``delete()``
|
||||
~~~~~~~~~~~~
|
||||
|
||||
Deletes the global variable from it's module. **Do not hold any
|
||||
references to this object after calling ``delete`` on it.**
|
||||
# create a global variable using
|
||||
add_global_variable method gv1 =
|
||||
module_obj.add_global_variable(Type.int(), "gv1")
|
||||
|
||||
# or equivalently, using a static constructor method
|
||||
gv2 = GlobalVariable.new(module_obj, Type.int(), "gv2") {% endhighlight
|
||||
%}
|
||||
|
||||
Existing global variables of a module can be accessed by name using
|
||||
``module_obj.get_global_variable_named(name)`` or
|
||||
``GlobalVariable.get``. All existing global variables can be enumerated
|
||||
via iterating over the property ``module_obj.global_variables``.
|
||||
|
||||
{% highlight python %} # retrieve a reference to the global variable
|
||||
gv1, # using the get_global_variable_named method gv1 =
|
||||
module_obj.get_global_variable_named("gv1")
|
||||
|
||||
# or equivalently, using the static ``get`` method:
|
||||
gv2 = GlobalVariable.get(module_obj, "gv2")
|
||||
|
||||
# list all global variables in a module
|
||||
for gv in module_obj.global_variables: print gv.name, "of type",
|
||||
gv.type
|
||||
|
|
|
|||
|
|
@ -8,226 +8,12 @@ Modules are top-level container objects. You need to create a module
|
|||
object first, before you can add global variables, aliases or functions.
|
||||
Modules are created using the static method ``Module.new``:
|
||||
|
||||
{% highlight python %} #!/usr/bin/env python
|
||||
|
||||
from llvm import \* from llvm.core import \*
|
||||
.. code-block:: python
|
||||
|
||||
create a module
|
||||
===============
|
||||
|
||||
my\_module = Module.new('my\_module') {% endhighlight %}
|
||||
|
||||
The constructor of the Module class should *not* be used to instantiate
|
||||
a Module object. This is a common feature for all llvmpy classes.
|
||||
|
||||
**Convention**
|
||||
|
||||
*All* llvmpy objects are instantiated using static methods of
|
||||
corresponding classes. Constructors *should not* be used.
|
||||
|
||||
The argument ``my_module`` is a module identifier (a plain string).
|
||||
A module can also be constructed via deserialization from a bit code
|
||||
file, using the static method ``from_bitcode``. This method takes a
|
||||
file-like object as argument, i.e., it should have a ``read()``
|
||||
method that returns the entire data in a single call, as is the case
|
||||
with the builtin file object. Here is an example:
|
||||
|
||||
{% highlight python %} # create a module from a bit code file bcfile =
|
||||
file("test.bc") my\_module = Module.from\_bitcode(bcfile) {%
|
||||
endhighlight %}
|
||||
|
||||
There is corresponding serialization method also, called ``to_bitcode``:
|
||||
|
||||
{% highlight python %} # write out a bit code file from the module
|
||||
bcfile = file("test.bc", "w") my\_module.to\_bitcode(bcfile) {%
|
||||
endhighlight %}
|
||||
|
||||
Modules can also be constructed from LLVM assembly files (``.ll``
|
||||
files). The static method ``from_assembly`` can be used for this.
|
||||
Similar to the ``from_bitcode`` method, this one also takes a file-like
|
||||
object as argument:
|
||||
|
||||
{% highlight python %} # create a module from an assembly file llfile =
|
||||
file("test.ll") my\_module = Module.from\_assembly(llfile) {%
|
||||
endhighlight %}
|
||||
|
||||
Modules can be converted into their assembly representation by
|
||||
stringifying them (see below).
|
||||
|
||||
--------------
|
||||
|
||||
llvm.core.Module
|
||||
================
|
||||
|
||||
- This will become a table of contents (this text will be scraped).
|
||||
{:toc}
|
||||
|
||||
Static Constructors
|
||||
-------------------
|
||||
|
||||
``new(module_id)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create a new ``Module`` instance with given ``module_id``. The
|
||||
``module_id`` should be a string.
|
||||
|
||||
``from_bitcode(fileobj)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create a new ``Module`` instance by deserializing the bitcode file
|
||||
represented by the file-like object ``fileobj``.
|
||||
|
||||
``from_assembly(fileobj)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Create a new ``Module`` instance by parsing the LLVM assembly file
|
||||
represented by the file-like object ``fileobj``.
|
||||
|
||||
Properties
|
||||
----------
|
||||
|
||||
``data_layout``
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
A string representing the ABI of the platform.
|
||||
|
||||
``target``
|
||||
~~~~~~~~~~
|
||||
|
||||
A string like ``i386-pc-linux-gnu`` or ``i386-pc-solaris2.8``.
|
||||
|
||||
``pointer_size``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
The size in bits of pointers, of the target platform. A value of zero
|
||||
represents ``llvm::Module::AnyPointerSize``.
|
||||
|
||||
``global_variables``
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
An iterable that yields
|
||||
`GlobalVariable <llvm.core.GlobalVariable.html>`_ objects, that
|
||||
represent the global variables of the module.
|
||||
|
||||
``functions``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
An iterable that yields `Function <llvm.core.Function.html>`_ objects,
|
||||
that represent functions in the module.
|
||||
|
||||
``id``
|
||||
~~~~~~
|
||||
|
||||
A string that represents the module identifier (name).
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
``get_type_named(name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Return a `StructType <llvm.core.StructType.html>`_ object for the given
|
||||
name.
|
||||
|
||||
The definition of this method was changed to work with LLVM 3.0+, in
|
||||
which the type system was rewritten. See `LLVM
|
||||
Blog <http://blog.llvm.org/2011/11/llvm-30-type-system-rewrite.html>`_.
|
||||
|
||||
{% comment %} ++++++++REMOVED+++++++++++ ### ``add_type_name(name, ty)``
|
||||
|
||||
Add an alias (typedef) for the type ``ty`` with the name ``name``.
|
||||
|
||||
``delete_type_name(name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Delete an alias with the name ``name``. ++++++++END-REMOVED+++++++++++
|
||||
{% endcomment %}
|
||||
|
||||
``add_global_variable(ty, name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Add a global variable of the type ``ty`` with the name ``name``. Returns
|
||||
a `GlobalVariable <llvm.core.GlobalVariable.html>`_ object.
|
||||
|
||||
``get_global_variable_named(name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Get a `GlobalVariable <llvm.core.GlobalVariable.html>`_ object
|
||||
corresponding to the global variable with the name ``name``. Raises
|
||||
``LLVMException`` if such a variable does not exist.
|
||||
|
||||
``add_library(name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Add a dependent library to the Module. This only adds a name to a list
|
||||
of dependent library. **No linking is performed**.
|
||||
|
||||
``add_function(ty, name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Add a function named ``name`` with the function type ``ty``. ``ty`` must
|
||||
of an object of type `FunctionType <llvm.core.FunctionType.html>`_.
|
||||
|
||||
``get_function_named(name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Get a `Function <llvm.core.Function.html>`_ object corresponding to the
|
||||
function with the name ``name``. Raises ``LLVMException`` if such a
|
||||
function does not exist.
|
||||
|
||||
``get_or_insert_function(ty, name)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Like ``get_function_named``, but adds the function first, if not present
|
||||
(like ``add_function``).
|
||||
|
||||
``verify()``
|
||||
~~~~~~~~~~~~
|
||||
|
||||
Verify the correctness of the module. Raises ``LLVMException`` on
|
||||
errors.
|
||||
|
||||
``to_bitcode(fileobj)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Write the bitcode representation of the module to the file-like object
|
||||
``fileobj``.
|
||||
|
||||
``link_in(other)``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Link in another module ``other`` into this module. Global variables,
|
||||
functions etc. are matched and resolved. The ``other`` module is no
|
||||
longer valid and should not be used after this operation. This API might
|
||||
be replaced with a full-fledged Linker class in the future.
|
||||
|
||||
Special Methods
|
||||
---------------
|
||||
|
||||
``__str__``
|
||||
~~~~~~~~~~~
|
||||
|
||||
``Module`` objects can be stringified into it's LLVM assembly language
|
||||
representation.
|
||||
|
||||
``__eq__``
|
||||
~~~~~~~~~~
|
||||
|
||||
``Module`` objects can be compared for equality. Internally, this
|
||||
converts both arguments into their LLVM assembly representations and
|
||||
compares the resultant strings.
|
||||
|
||||
**Convention**
|
||||
|
||||
*All* llvmpy objects (where it makes sense), when stringified,
|
||||
return the LLVM assembly representation. ``print module_obj`` for
|
||||
example, prints the LLVM assembly form of the entire module.
|
||||
|
||||
Such objects, when compared for equality, internally compare these
|
||||
string representations.
|
||||
#!/usr/bin/env python
|
||||
|
||||
from llvm import \* from llvm.core import \*
|
||||
|
||||
# create a module
|
||||
my_module = Module.new('my_module')
|
||||
|
|
|
|||
|
|
@ -1,84 +0,0 @@
|
|||
+---------------------------------+
|
||||
| layout: page |
|
||||
+---------------------------------+
|
||||
| title: StructType (llvm.core) |
|
||||
+---------------------------------+
|
||||
|
||||
llvm.core.StructType
|
||||
====================
|
||||
|
||||
Base Class
|
||||
----------
|
||||
|
||||
- `llvm.core.Type <llvm.core.Type.html>`_
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
``set_body(self, elems, packed=False)``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Define the body for opaque identified structure.
|
||||
|
||||
``elems`` is an iterable of `llvm.core.Type <llvm.core.Type.html>`_ If
|
||||
``packed`` is ``True``, creates a packed structure.
|
||||
|
||||
Properties
|
||||
----------
|
||||
|
||||
``is_identified``
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
``True`` if this is an identified structure.
|
||||
|
||||
``is_literal``
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
``True`` if this is a literal structure.
|
||||
|
||||
``is_opaque``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
``True`` if this is an opaque structure. Only identified structure can
|
||||
be opaque.
|
||||
|
||||
``packed``
|
||||
~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
``True`` if the structure is packed (no padding between elements).
|
||||
|
||||
``name``
|
||||
~~~~~~~~
|
||||
|
||||
Use in identified structure. If set to empty, the identified structure
|
||||
is removed from the global context.
|
||||
|
||||
``elements``
|
||||
~~~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
Returns an iterable object that yields `Type <llvm.core.Type.html>`_
|
||||
objects that represent, in order, the types of the elements of the
|
||||
structure. Used like this:
|
||||
|
||||
{% highlight python %} struct\_type = Type.struct( [ Type.int(),
|
||||
Type.int() ] ) for elem in struct\_type.elements: assert elem.kind ==
|
||||
TYPE\_INTEGER assert elem == Type.int() assert
|
||||
struct\_type.element\_count == len(struct\_type.elements) {%
|
||||
endhighlight %}
|
||||
|
||||
``element_count``
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
[read-only]
|
||||
|
||||
The number of elements. Same as ``len(obj.elements)``, but faster.
|
||||
|
|
@ -106,40 +106,23 @@ Properties
|
|||
A value (enum) representing the "type" of the object. It will be one of
|
||||
the following constants defined in ``llvm.core``:
|
||||
|
||||
{% highlight python %} # Warning: do not rely on actual numerical
|
||||
values! TYPE\_VOID = 0 TYPE\_FLOAT = 1 TYPE\_DOUBLE = 2 TYPE\_X86\_FP80
|
||||
= 3 TYPE\_FP128 = 4 TYPE\_PPC\_FP128 = 5 TYPE\_LABEL = 6 TYPE\_INTEGER =
|
||||
7 TYPE\_FUNCTION = 8 TYPE\_STRUCT = 9 TYPE\_ARRAY = 10 TYPE\_POINTER =
|
||||
11 TYPE\_OPAQUE = 12 TYPE\_VECTOR = 13 TYPE\_METADATA = 14 TYPE\_UNION =
|
||||
15 {% endhighlight %}
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Warning: do not rely on actual numerical
|
||||
values! TYPE_VOID = 0 TYPE_FLOAT = 1 TYPE_DOUBLE = 2 TYPE_X86_FP80
|
||||
= 3 TYPE_FP128 = 4 TYPE_PPC_FP128 = 5 TYPE_LABEL = 6 TYPE_INTEGER =
|
||||
7 TYPE_FUNCTION = 8 TYPE_STRUCT = 9 TYPE_ARRAY = 10 TYPE_POINTER =
|
||||
11 TYPE_OPAQUE = 12 TYPE_VECTOR = 13 TYPE_METADATA = 14 TYPE_UNION =
|
||||
15
|
||||
|
||||
|
||||
|
||||
Example:
|
||||
^^^^^^^^
|
||||
|
||||
{% highlight python %} assert Type.int().kind == TYPE\_INTEGER assert
|
||||
Type.void().kind == TYPE\_VOID {% endhighlight %}
|
||||
|
||||
Methods
|
||||
-------
|
||||
.. code-block:: python
|
||||
|
||||
``refine``
|
||||
~~~~~~~~~~
|
||||
|
||||
Used for constructing self-referencing types. See the documentation of
|
||||
`TypeHandle <llvm.core.TypeHandle.html>`_ objects.
|
||||
|
||||
Special Methods
|
||||
---------------
|
||||
|
||||
``__str__``
|
||||
~~~~~~~~~~~
|
||||
|
||||
``Type`` objects can be stringified into it's LLVM assembly language
|
||||
representation.
|
||||
|
||||
``__eq__``
|
||||
~~~~~~~~~~
|
||||
|
||||
``Type`` objects can be compared for equality. Internally, this converts
|
||||
both arguments into their LLVM assembly representations and compares the
|
||||
resultant strings.
|
||||
assert Type.int().kind == TYPE_INTEGER assert
|
||||
Type.void().kind == TYPE_VOID
|
||||
|
|
|
|||
|
|
@ -80,15 +80,8 @@ Pythonically, modules are imported with the statement
|
|||
``import llvm.core``. However, you might find it more convenient to
|
||||
import llvmpy modules thus:
|
||||
|
||||
{% highlight python %} from llvm import \* from llvm.core import \* from
|
||||
llvm.ee import \* from llvm.passes import \* {% endhighlight %}
|
||||
|
||||
This avoids quite some typing. Both conventions work, however.
|
||||
.. code-block:: python
|
||||
|
||||
**Tip**
|
||||
|
||||
Python-style documentation strings (``__doc__``) are present in
|
||||
llvmpy. You can use the ``help()`` of the interactive Python
|
||||
interpreter or the ``object?`` of
|
||||
`IPython <http://ipython.scipy.org/moin/>`_ to get online help.
|
||||
(Note: not complete yet!)
|
||||
from llvm import \* from llvm.core import \* from
|
||||
llvm.ee import \* from llvm.passes import \*
|
||||
|
|
|
|||
|
|
@ -60,50 +60,43 @@ An Example
|
|||
|
||||
Here is an example that demonstrates the creation of types:
|
||||
|
||||
{% highlight python %} #!/usr/bin/env python
|
||||
|
||||
integers
|
||||
========
|
||||
.. code-block:: python
|
||||
|
||||
int\_ty = Type.int() bool\_ty = Type.int(1) int\_64bit = Type.int(64)
|
||||
#!/usr/bin/env python
|
||||
|
||||
# integers
|
||||
int_ty = Type.int() bool_ty = Type.int(1) int_64bit = Type.int(64)
|
||||
|
||||
# floats
|
||||
sprec_real = Type.float() dprec_real = Type.double()
|
||||
|
||||
# arrays and vectors
|
||||
intar_ty = Type.array( int_ty, 10 ) # "typedef int intar_ty[10];"
|
||||
twodim = Type.array( intar_ty , 10 ) # "typedef int twodim[10][10];"
|
||||
vec = Type.array( int_ty, 10 )
|
||||
|
||||
# structures
|
||||
s1_ty = Type.struct( [ int_ty, sprec_real ] ) # "struct s1_ty { int
|
||||
v1; float v2; };"
|
||||
|
||||
# pointers
|
||||
intptr_ty = Type.pointer(int_ty) # "typedef int \*intptr_ty;"
|
||||
|
||||
# functions
|
||||
f1 = Type.function( int_ty, [ int_ty ] ) # functions that take 1
|
||||
int_ty and return 1 int_ty
|
||||
|
||||
f2 = Type.function( Type.void(), [ int_ty, int_ty ] ) # functions that
|
||||
take 2 int_tys and return nothing
|
||||
|
||||
f3 = Type.function( Type.void(), ( int_ty, int_ty ) ) # same as f2;
|
||||
any iterable can be used
|
||||
|
||||
fnargs = [ Type.pointer( Type.int(8) ) ] printf = Type.function(
|
||||
Type.int(), fnargs, True ) # variadic function
|
||||
|
||||
floats
|
||||
======
|
||||
|
||||
sprec\_real = Type.float() dprec\_real = Type.double()
|
||||
|
||||
arrays and vectors
|
||||
==================
|
||||
|
||||
intar\_ty = Type.array( int\_ty, 10 ) # "typedef int intar\_ty[10];"
|
||||
twodim = Type.array( intar\_ty , 10 ) # "typedef int twodim[10][10];"
|
||||
vec = Type.array( int\_ty, 10 )
|
||||
|
||||
structures
|
||||
==========
|
||||
|
||||
s1\_ty = Type.struct( [ int\_ty, sprec\_real ] ) # "struct s1\_ty { int
|
||||
v1; float v2; };"
|
||||
|
||||
pointers
|
||||
========
|
||||
|
||||
intptr\_ty = Type.pointer(int\_ty) # "typedef int \*intptr\_ty;"
|
||||
|
||||
functions
|
||||
=========
|
||||
|
||||
f1 = Type.function( int\_ty, [ int\_ty ] ) # functions that take 1
|
||||
int\_ty and return 1 int\_ty
|
||||
|
||||
f2 = Type.function( Type.void(), [ int\_ty, int\_ty ] ) # functions that
|
||||
take 2 int\_tys and return nothing
|
||||
|
||||
f3 = Type.function( Type.void(), ( int\_ty, int\_ty ) ) # same as f2;
|
||||
any iterable can be used
|
||||
|
||||
fnargs = [ Type.pointer( Type.int(8) ) ] printf = Type.function(
|
||||
Type.int(), fnargs, True ) # variadic function {% endhighlight %}
|
||||
|
||||
--------------
|
||||
|
||||
|
|
@ -123,16 +116,8 @@ The following code defines a opaque structure, named "mystruct". The
|
|||
body is defined after the construction using ``StructType.set_body``.
|
||||
The second subtype is a pointer to a "mystruct" type.
|
||||
|
||||
{% highlight python %} ts = Type.opaque('mystruct')
|
||||
ts.set\_body([Type.int(), Type.pointer(ts)]) {% endhighlight %}
|
||||
|
||||
--------------
|
||||
.. code-block:: python
|
||||
|
||||
**Related Links** `llvm.core.Type <llvm.core.Type.html>`_,
|
||||
`llvm.core.IntegerType <llvm.core.IntegerType.html>`_,
|
||||
`llvm.core.FunctionType <llvm.core.FunctionType.html>`_,
|
||||
`llvm.core.StructType <llvm.core.StructType.html>`_,
|
||||
`llvm.core.ArrayType <llvm.core.ArrayType.html>`_,
|
||||
`llvm.core.PointerType <llvm.core.PointerType.html>`_,
|
||||
`llvm.core.VectorType <llvm.core.VectorType.html>`_,
|
||||
`llvm.core.TypeHandle <llvm.core.TypeHandle.html>`_
|
||||
ts = Type.opaque('mystruct')
|
||||
ts.set_body([Type.int(), Type.pointer(ts)])
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue