[ThinLTO] Add code comment. NFC
[llvm-core.git] / docs / GettingStarted.rst
blob479becacd10f61b60635f1a8842f016a67a5394d
1 ====================================
2 Getting Started with the LLVM System
3 ====================================
5 .. contents::
6    :local:
8 Overview
9 ========
11 Welcome to the LLVM project! In order to get started, you first need to know
12 some basic information.
14 First, the LLVM project has multiple components. The core of the project is
15 itself called "LLVM". This contains all of the tools, libraries, and header
16 files needed to process an intermediate representation and convert it into
17 object files.  It contains an assembler, disassembler, bitcode analyzer and
18 bitcode optimizer.  It also contains basic regression tests.
20 Another piece is the `Clang <http://clang.llvm.org/>`_ front end.  This
21 component compiles C, C++, Objective C, and Objective C++ code into LLVM bitcode
22 -- and from there into object files, using LLVM.
24 There are other components as well:
25 the `libc++ C++ standard library <https://libcxx.llvm.org>`_,
26 the `LLD linker <https://lld.llvm.org>`_, and more.
28 Getting Started Quickly (A Summary)
29 ===================================
31 The LLVM Getting Started documentation may be out of date.  So, the `Clang
32 Getting Started <http://clang.llvm.org/get_started.html>`_ page might also be a
33 good place to start.
35 Here's the short story for getting up and running quickly with LLVM:
37 #. Read the documentation.
38 #. Read the documentation.
39 #. Remember that you were warned twice about reading the documentation.
41 #. Checkout LLVM (including related subprojects like Clang):
43    * ``git clone https://github.com/llvm/llvm-project.git``
44    * Or, on windows, ``git clone --config core.autocrlf=false
45      https://github.com/llvm/llvm-project.git``
47 #. Configure and build LLVM and Clang:.
49    * ``cd llvm-project``
50    * ``mkdir build``
51    * ``cd build``
52    * ``cmake -G <generator> [options] ../llvm``
54      Some common generators are:
56      * ``Ninja`` --- for generating `Ninja <https://ninja-build.org>`_
57        build files. Most llvm developers use Ninja.
58      * ``Unix Makefiles`` --- for generating make-compatible parallel makefiles.
59      * ``Visual Studio`` --- for generating Visual Studio projects and
60        solutions.
61      * ``Xcode`` --- for generating Xcode projects.
63      Some Common options:
65      * ``-DLLVM_ENABLE_PROJECTS='...'`` --- semicolon-separated list of the LLVM
66        subprojects you'd like to additionally build. Can include any of: clang,
67        clang-tools-extra, libcxx, libcxxabi, libunwind, lldb, compiler-rt, lld,
68        polly, or debuginfo-tests.
70        For example, to build LLVM, Clang, libcxx, and libcxxabi, use
71        ``-DLLVM_ENABLE_PROJECTS="clang;libcxx;libcxxabi"``.
73      * ``-DCMAKE_INSTALL_PREFIX=directory`` --- Specify for *directory* the full
74        pathname of where you want the LLVM tools and libraries to be installed
75        (default ``/usr/local``).
77      * ``-DCMAKE_BUILD_TYPE=type`` --- Valid options for *type* are Debug,
78        Release, RelWithDebInfo, and MinSizeRel. Default is Debug.
80      * ``-DLLVM_ENABLE_ASSERTIONS=On`` --- Compile with assertion checks enabled
81        (default is Yes for Debug builds, No for all other build types).
83    * Run your build tool of choice!
85      * The default target (i.e. ``ninja`` or ``make``) will build all of LLVM.
87      * The ``check-all`` target (i.e. ``ninja check-all``) will run the
88        regression tests to ensure everything is in working order.
90      * CMake will generate build targets for each tool and library, and most
91        LLVM sub-projects generate their own ``check-<project>`` target.
93      * Running a serial build will be *slow*.  Make sure you run a parallel
94        build. That's already done by default in Ninja; for ``make``, use
95        ``make -j NNN`` (with an appropriate value of NNN, e.g. number of CPUs
96        you have.)
98    * For more information see `CMake <CMake.html>`__
100    * If you get an "internal compiler error (ICE)" or test failures, see
101      `below`_.
103 Consult the `Getting Started with LLVM`_ section for detailed information on
104 configuring and compiling LLVM.  Go to `Directory Layout`_ to learn about the
105 layout of the source code tree.
107 Requirements
108 ============
110 Before you begin to use the LLVM system, review the requirements given below.
111 This may save you some trouble by knowing ahead of time what hardware and
112 software you will need.
114 Hardware
115 --------
117 LLVM is known to work on the following host platforms:
119 ================== ===================== =============
120 OS                 Arch                  Compilers
121 ================== ===================== =============
122 Linux              x86\ :sup:`1`         GCC, Clang
123 Linux              amd64                 GCC, Clang
124 Linux              ARM                   GCC, Clang
125 Linux              PowerPC               GCC, Clang
126 Solaris            V9 (Ultrasparc)       GCC
127 FreeBSD            x86\ :sup:`1`         GCC, Clang
128 FreeBSD            amd64                 GCC, Clang
129 NetBSD             x86\ :sup:`1`         GCC, Clang
130 NetBSD             amd64                 GCC, Clang
131 macOS\ :sup:`2`    PowerPC               GCC
132 macOS              x86                   GCC, Clang
133 Cygwin/Win32       x86\ :sup:`1, 3`      GCC
134 Windows            x86\ :sup:`1`         Visual Studio
135 Windows x64        x86-64                Visual Studio
136 ================== ===================== =============
138 .. note::
140   #. Code generation supported for Pentium processors and up
141   #. Code generation supported for 32-bit ABI only
142   #. To use LLVM modules on Win32-based system, you may configure LLVM
143      with ``-DBUILD_SHARED_LIBS=On``.
145 Note that Debug builds require a lot of time and disk space.  An LLVM-only build
146 will need about 1-3 GB of space.  A full build of LLVM and Clang will need around
147 15-20 GB of disk space.  The exact space requirements will vary by system.  (It
148 is so large because of all the debugging information and the fact that the
149 libraries are statically linked into multiple tools).
151 If you are space-constrained, you can build only selected tools or only
152 selected targets.  The Release build requires considerably less space.
154 The LLVM suite *may* compile on other platforms, but it is not guaranteed to do
155 so.  If compilation is successful, the LLVM utilities should be able to
156 assemble, disassemble, analyze, and optimize LLVM bitcode.  Code generation
157 should work as well, although the generated native code may not work on your
158 platform.
160 Software
161 --------
163 Compiling LLVM requires that you have several software packages installed. The
164 table below lists those required packages. The Package column is the usual name
165 for the software package that LLVM depends on. The Version column provides
166 "known to work" versions of the package. The Notes column describes how LLVM
167 uses the package and provides other details.
169 =========================================================== ============ ==========================================
170 Package                                                     Version      Notes
171 =========================================================== ============ ==========================================
172 `CMake <http://cmake.org/>`__                               >=3.4.3      Makefile/workspace generator
173 `GCC <http://gcc.gnu.org/>`_                                >=5.1.0      C/C++ compiler\ :sup:`1`
174 `python <http://www.python.org/>`_                          >=2.7        Automated test suite\ :sup:`2`
175 `zlib <http://zlib.net>`_                                   >=1.2.3.4    Compression library\ :sup:`3`
176 `GNU Make <http://savannah.gnu.org/projects/make>`_         3.79, 3.79.1 Makefile/build processor\ :sup:`4`
177 =========================================================== ============ ==========================================
179 .. note::
181    #. Only the C and C++ languages are needed so there's no need to build the
182       other languages for LLVM's purposes. See `below` for specific version
183       info.
184    #. Only needed if you want to run the automated test suite in the
185       ``llvm/test`` directory.
186    #. Optional, adds compression / uncompression capabilities to selected LLVM
187       tools.
188    #. Optional, you can use any other build tool supported by CMake.
190 Additionally, your compilation host is expected to have the usual plethora of
191 Unix utilities. Specifically:
193 * **ar** --- archive library builder
194 * **bzip2** --- bzip2 command for distribution generation
195 * **bunzip2** --- bunzip2 command for distribution checking
196 * **chmod** --- change permissions on a file
197 * **cat** --- output concatenation utility
198 * **cp** --- copy files
199 * **date** --- print the current date/time
200 * **echo** --- print to standard output
201 * **egrep** --- extended regular expression search utility
202 * **find** --- find files/dirs in a file system
203 * **grep** --- regular expression search utility
204 * **gzip** --- gzip command for distribution generation
205 * **gunzip** --- gunzip command for distribution checking
206 * **install** --- install directories/files
207 * **mkdir** --- create a directory
208 * **mv** --- move (rename) files
209 * **ranlib** --- symbol table builder for archive libraries
210 * **rm** --- remove (delete) files and directories
211 * **sed** --- stream editor for transforming output
212 * **sh** --- Bourne shell for make build scripts
213 * **tar** --- tape archive for distribution generation
214 * **test** --- test things in file system
215 * **unzip** --- unzip command for distribution checking
216 * **zip** --- zip command for distribution generation
218 .. _below:
219 .. _check here:
221 Host C++ Toolchain, both Compiler and Standard Library
222 ------------------------------------------------------
224 LLVM is very demanding of the host C++ compiler, and as such tends to expose
225 bugs in the compiler. We also attempt to follow improvements and developments in
226 the C++ language and library reasonably closely. As such, we require a modern
227 host C++ toolchain, both compiler and standard library, in order to build LLVM.
229 LLVM is written using the subset of C++ documented in :doc:`coding
230 standards<CodingStandards>`. To enforce this language version, we check the most
231 popular host toolchains for specific minimum versions in our build systems:
233 * Clang 3.5
234 * Apple Clang 6.0
235 * GCC 5.1
236 * Visual Studio 2017
238 Anything older than these toolchains *may* work, but will require forcing the
239 build system with a special option and is not really a supported host platform.
240 Also note that older versions of these compilers have often crashed or
241 miscompiled LLVM.
243 For less widely used host toolchains such as ICC or xlC, be aware that a very
244 recent version may be required to support all of the C++ features used in LLVM.
246 We track certain versions of software that are *known* to fail when used as
247 part of the host toolchain. These even include linkers at times.
249 **GNU ld 2.16.X**. Some 2.16.X versions of the ld linker will produce very long
250 warning messages complaining that some "``.gnu.linkonce.t.*``" symbol was
251 defined in a discarded section. You can safely ignore these messages as they are
252 erroneous and the linkage is correct.  These messages disappear using ld 2.17.
254 **GNU binutils 2.17**: Binutils 2.17 contains `a bug
255 <http://sourceware.org/bugzilla/show_bug.cgi?id=3111>`__ which causes huge link
256 times (minutes instead of seconds) when building LLVM.  We recommend upgrading
257 to a newer version (2.17.50.0.4 or later).
259 **GNU Binutils 2.19.1 Gold**: This version of Gold contained `a bug
260 <http://sourceware.org/bugzilla/show_bug.cgi?id=9836>`__ which causes
261 intermittent failures when building LLVM with position independent code.  The
262 symptom is an error about cyclic dependencies.  We recommend upgrading to a
263 newer version of Gold.
265 Getting a Modern Host C++ Toolchain
266 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
268 This section mostly applies to Linux and older BSDs. On macOS, you should
269 have a sufficiently modern Xcode, or you will likely need to upgrade until you
270 do. Windows does not have a "system compiler", so you must install either Visual
271 Studio 2017 or a recent version of mingw64. FreeBSD 10.0 and newer have a modern
272 Clang as the system compiler.
274 However, some Linux distributions and some other or older BSDs sometimes have
275 extremely old versions of GCC. These steps attempt to help you upgrade you
276 compiler even on such a system. However, if at all possible, we encourage you
277 to use a recent version of a distribution with a modern system compiler that
278 meets these requirements. Note that it is tempting to install a prior
279 version of Clang and libc++ to be the host compiler, however libc++ was not
280 well tested or set up to build on Linux until relatively recently. As
281 a consequence, this guide suggests just using libstdc++ and a modern GCC as the
282 initial host in a bootstrap, and then using Clang (and potentially libc++).
284 The first step is to get a recent GCC toolchain installed. The most common
285 distribution on which users have struggled with the version requirements is
286 Ubuntu Precise, 12.04 LTS. For this distribution, one easy option is to install
287 the `toolchain testing PPA`_ and use it to install a modern GCC. There is
288 a really nice discussions of this on the `ask ubuntu stack exchange`_ and a
289 `github gist`_ with updated commands. However, not all users can use PPAs and
290 there are many other distributions, so it may be necessary (or just useful, if
291 you're here you *are* doing compiler development after all) to build and install
292 GCC from source. It is also quite easy to do these days.
294 .. _toolchain testing PPA:
295   https://launchpad.net/~ubuntu-toolchain-r/+archive/test
296 .. _ask ubuntu stack exchange:
297   https://askubuntu.com/questions/466651/how-do-i-use-the-latest-gcc-on-ubuntu/581497#58149
298 .. _github gist:
299   https://gist.github.com/application2000/73fd6f4bf1be6600a2cf9f56315a2d91
301 Easy steps for installing GCC 5.1.0:
303 .. code-block:: console
305   % gcc_version=5.1.0
306   % wget https://ftp.gnu.org/gnu/gcc/gcc-${gcc_version}/gcc-${gcc_version}.tar.bz2
307   % wget https://ftp.gnu.org/gnu/gcc/gcc-${gcc_version}/gcc-${gcc_version}.tar.bz2.sig
308   % wget https://ftp.gnu.org/gnu/gnu-keyring.gpg
309   % signature_invalid=`gpg --verify --no-default-keyring --keyring ./gnu-keyring.gpg gcc-${gcc_version}.tar.bz2.sig`
310   % if [ $signature_invalid ]; then echo "Invalid signature" ; exit 1 ; fi
311   % tar -xvjf gcc-${gcc_version}.tar.bz2
312   % cd gcc-${gcc_version}
313   % ./contrib/download_prerequisites
314   % cd ..
315   % mkdir gcc-${gcc_version}-build
316   % cd gcc-${gcc_version}-build
317   % $PWD/../gcc-${gcc_version}/configure --prefix=$HOME/toolchains --enable-languages=c,c++
318   % make -j$(nproc)
319   % make install
321 For more details, check out the excellent `GCC wiki entry`_, where I got most
322 of this information from.
324 .. _GCC wiki entry:
325   https://gcc.gnu.org/wiki/InstallingGCC
327 Once you have a GCC toolchain, configure your build of LLVM to use the new
328 toolchain for your host compiler and C++ standard library. Because the new
329 version of libstdc++ is not on the system library search path, you need to pass
330 extra linker flags so that it can be found at link time (``-L``) and at runtime
331 (``-rpath``). If you are using CMake, this invocation should produce working
332 binaries:
334 .. code-block:: console
336   % mkdir build
337   % cd build
338   % CC=$HOME/toolchains/bin/gcc CXX=$HOME/toolchains/bin/g++ \
339     cmake .. -DCMAKE_CXX_LINK_FLAGS="-Wl,-rpath,$HOME/toolchains/lib64 -L$HOME/toolchains/lib64"
341 If you fail to set rpath, most LLVM binaries will fail on startup with a message
342 from the loader similar to ``libstdc++.so.6: version `GLIBCXX_3.4.20' not
343 found``. This means you need to tweak the -rpath linker flag.
345 When you build Clang, you will need to give *it* access to modern C++
346 standard library in order to use it as your new host in part of a bootstrap.
347 There are two easy ways to do this, either build (and install) libc++ along
348 with Clang and then use it with the ``-stdlib=libc++`` compile and link flag,
349 or install Clang into the same prefix (``$HOME/toolchains`` above) as GCC.
350 Clang will look within its own prefix for libstdc++ and use it if found. You
351 can also add an explicit prefix for Clang to look in for a GCC toolchain with
352 the ``--gcc-toolchain=/opt/my/gcc/prefix`` flag, passing it to both compile and
353 link commands when using your just-built-Clang to bootstrap.
355 .. _Getting Started with LLVM:
357 Getting Started with LLVM
358 =========================
360 The remainder of this guide is meant to get you up and running with LLVM and to
361 give you some basic information about the LLVM environment.
363 The later sections of this guide describe the `general layout`_ of the LLVM
364 source tree, a `simple example`_ using the LLVM tool chain, and `links`_ to find
365 more information about LLVM or to get help via e-mail.
367 Terminology and Notation
368 ------------------------
370 Throughout this manual, the following names are used to denote paths specific to
371 the local system and working environment.  *These are not environment variables
372 you need to set but just strings used in the rest of this document below*.  In
373 any of the examples below, simply replace each of these names with the
374 appropriate pathname on your local system.  All these paths are absolute:
376 ``SRC_ROOT``
378   This is the top level directory of the LLVM source tree.
380 ``OBJ_ROOT``
382   This is the top level directory of the LLVM object tree (i.e. the tree where
383   object files and compiled programs will be placed.  It can be the same as
384   SRC_ROOT).
386 Unpacking the LLVM Archives
387 ---------------------------
389 If you have the LLVM distribution, you will need to unpack it before you can
390 begin to compile it.  LLVM is distributed as a number of different
391 subprojects. Each one has its own download which is a TAR archive that is
392 compressed with the gzip program.
394 The files are as follows, with *x.y* marking the version number:
396 ``llvm-x.y.tar.gz``
398   Source release for the LLVM libraries and tools.
400 ``cfe-x.y.tar.gz``
402   Source release for the Clang frontend.
404 .. _checkout:
406 Checkout LLVM from Git
407 ----------------------
409 You can also checkout the source code for LLVM from Git. While the LLVM
410 project's official source-code repository is Subversion, we are in the process
411 of migrating to git. We currently recommend that all developers use Git for
412 day-to-day development.
414 .. note::
416   Passing ``--config core.autocrlf=false`` should not be required in
417   the future after we adjust the .gitattribute settings correctly, but
418   is required for Windows users at the time of this writing.
420 Simply run:
422 .. code-block:: console
424   % git clone https://github.com/llvm/llvm-project.git
426 or on Windows,
428 .. code-block:: console
430   % git clone --config core.autocrlf=false https://github.com/llvm/llvm-project.git
432 This will create an '``llvm-project``' directory in the current directory and
433 fully populate it with all of the source code, test directories, and local
434 copies of documentation files for LLVM and all the related subprojects. Note
435 that unlike the tarballs, which contain each subproject in a separate file, the
436 git repository contains all of the projects together.
438 If you want to get a specific release (as opposed to the most recent revision),
439 you can check out a tag after cloning the repository. E.g., `git checkout
440 llvmorg-6.0.1` inside the ``llvm-project`` directory created by the above
441 command.  Use `git tag -l` to list all of them.
443 Sending patches
444 ^^^^^^^^^^^^^^^
446 Please read `Developer Policy <DeveloperPolicy.html#one-off-patches>`_, too.
448 We don't currently accept github pull requests, so you'll need to send patches
449 either via emailing to llvm-commits, or, preferably, via :ref:`Phabricator
450 <phabricator-reviews>`.
452 You'll generally want to make sure your branch has a single commit,
453 corresponding to the review you wish to send, up-to-date with the upstream
454 ``origin/master`` branch, and doesn't contain merges. Once you have that, you
455 can use ``git show`` or ``git format-patch`` to output the diff, and attach it
456 to a Phabricator review (or to an email message).
458 However, using the "Arcanist" tool is often easier. After `installing
459 arcanist`_, you can upload the latest commit using:
461 .. code-block:: console
463   % arc diff HEAD~1
465 Additionally, before sending a patch for review, please also try to ensure it's
466 formatted properly. We use ``clang-format`` for this, which has git integration
467 through the ``git-clang-format`` script. On some systems, it may already be
468 installed (or be installable via your package manager). If so, you can simply
469 run it -- the following command will format only the code changed in the most
470 recent commit:
472 .. code-block:: console
474   % git clang-format HEAD~1
476 Note that this modifies the files, but doesn't commit them -- you'll likely want
477 to run
479 .. code-block:: console
481   % git commit --amend -a
483 in order to update the last commit with all pending changes.
485 .. note::
486   If you don't already have ``clang-format`` or ``git clang-format`` installed
487   on your system, the ``clang-format`` binary will be built alongside clang, and
488   the git integration can be run from
489   ``clang/tools/clang-format/git-clang-format``.
492 .. _commit_from_git:
494 For developers to commit changes from Git
495 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
497 A helper script is provided in ``llvm/utils/git-svn/git-llvm``. After you add it
498 to your path, you can push committed changes upstream with ``git llvm
499 push``. While this creates a Subversion checkout and patches it under the hood,
500 it does not require you to have interaction with it.
502 .. code-block:: console
504   % export PATH=$PATH:$TOP_LEVEL_DIR/llvm-project/llvm/utils/git-svn/
505   % git llvm push
507 Within a couple minutes after pushing to subversion, the svn commit will have
508 been converted back to a Git commit, and made its way into the official Git
509 repository. At that point, ``git pull`` should get back the changes as they were
510 committed.
512 You'll likely want to ``git pull --rebase`` to get the official git commit
513 downloaded back to your repository. The SVN revision numbers of each commit can
514 be found at the end of the commit message, e.g. ``llvm-svn: 350914``.
516 You may also find the ``-n`` flag useful, like ``git llvm push -n``. This runs
517 through all the steps of committing _without_ actually doing the commit, and
518 tell you what it would have done. That can be useful if you're unsure whether
519 the right thing will happen.
521 Reverting a change when using Git
522 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
524 If you're using Git and need to revert a patch, Git needs to be supplied a
525 commit hash, not an svn revision. To make things easier, you can use
526 ``git llvm revert`` to revert with either an SVN revision or a Git hash instead.
528 Additionally, you can first run with ``git llvm revert -n`` to print which Git
529 commands will run, without doing anything.
531 Running ``git llvm revert`` will only revert things in your local repository. To
532 push the revert upstream, you still need to run ``git llvm push`` as described
533 earlier.
535 .. code-block:: console
537   % git llvm revert rNNNNNN       # Revert by SVN id
538   % git llvm revert abcdef123456  # Revert by Git commit hash
539   % git llvm revert -n rNNNNNN    # Print the commands without doing anything
541 Checkout via SVN (deprecated)
542 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
544 Until we have fully migrated to Git, you may also get a fresh copy of
545 the code from the official Subversion repository.
547 * ``cd where-you-want-llvm-to-live``
548 * Read-Only: ``svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm``
549 * Read-Write: ``svn co https://user@llvm.org/svn/llvm-project/llvm/trunk llvm``
551 This will create an '``llvm``' directory in the current directory and fully
552 populate it with the LLVM source code, Makefiles, test directories, and local
553 copies of documentation files.
555 If you want to get a specific release (as opposed to the most recent revision),
556 you can check it out from the '``tags``' directory (instead of '``trunk``'). The
557 following releases are located in the following subdirectories of the '``tags``'
558 directory:
560 * Release 3.5.0 and later: **RELEASE_350/final** and so on
561 * Release 2.9 through 3.4: **RELEASE_29/final** and so on
562 * Release 1.1 through 2.8: **RELEASE_11** and so on
563 * Release 1.0: **RELEASE_1**
565 Local LLVM Configuration
566 ------------------------
568 Once checked out repository, the LLVM suite source code must be configured
569 before being built. This process uses CMake.  Unlinke the normal ``configure``
570 script, CMake generates the build files in whatever format you request as well
571 as various ``*.inc`` files, and ``llvm/include/Config/config.h``.
573 Variables are passed to ``cmake`` on the command line using the format
574 ``-D<variable name>=<value>``. The following variables are some common options
575 used by people developing LLVM.
577 +-------------------------+----------------------------------------------------+
578 | Variable                | Purpose                                            |
579 +=========================+====================================================+
580 | CMAKE_C_COMPILER        | Tells ``cmake`` which C compiler to use. By        |
581 |                         | default, this will be /usr/bin/cc.                 |
582 +-------------------------+----------------------------------------------------+
583 | CMAKE_CXX_COMPILER      | Tells ``cmake`` which C++ compiler to use. By      |
584 |                         | default, this will be /usr/bin/c++.                |
585 +-------------------------+----------------------------------------------------+
586 | CMAKE_BUILD_TYPE        | Tells ``cmake`` what type of build you are trying  |
587 |                         | to generate files for. Valid options are Debug,    |
588 |                         | Release, RelWithDebInfo, and MinSizeRel. Default   |
589 |                         | is Debug.                                          |
590 +-------------------------+----------------------------------------------------+
591 | CMAKE_INSTALL_PREFIX    | Specifies the install directory to target when     |
592 |                         | running the install action of the build files.     |
593 +-------------------------+----------------------------------------------------+
594 | PYTHON_EXECUTABLE       | Forces CMake to use a specific Python version by   |
595 |                         | passing a path to a Python interpreter. By default |
596 |                         | the Python version of the interpreter in your PATH |
597 |                         | is used.                                           |
598 +-------------------------+----------------------------------------------------+
599 | LLVM_TARGETS_TO_BUILD   | A semicolon delimited list controlling which       |
600 |                         | targets will be built and linked into llvm.        |
601 |                         | The default list is defined as                     |
602 |                         | ``LLVM_ALL_TARGETS``, and can be set to include    |
603 |                         | out-of-tree targets. The default value includes:   |
604 |                         | ``AArch64, AMDGPU, ARM, BPF, Hexagon, Mips,        |
605 |                         | MSP430, NVPTX, PowerPC, Sparc, SystemZ, X86,       |
606 |                         | XCore``.                                           |
607 |                         |                                                    |
608 +-------------------------+----------------------------------------------------+
609 | LLVM_ENABLE_DOXYGEN     | Build doxygen-based documentation from the source  |
610 |                         | code This is disabled by default because it is     |
611 |                         | slow and generates a lot of output.                |
612 +-------------------------+----------------------------------------------------+
613 | LLVM_ENABLE_PROJECTS    | A semicolon-delimited list selecting which of the  |
614 |                         | other LLVM subprojects to additionally build. (Only|
615 |                         | effective when using a side-by-side project layout |
616 |                         | e.g. via git). The default list is empty. Can      |
617 |                         | include: clang, libcxx, libcxxabi, libunwind, lldb,|
618 |                         | compiler-rt, lld, polly, or debuginfo-tests.       |
619 +-------------------------+----------------------------------------------------+
620 | LLVM_ENABLE_SPHINX      | Build sphinx-based documentation from the source   |
621 |                         | code. This is disabled by default because it is    |
622 |                         | slow and generates a lot of output. Sphinx version |
623 |                         | 1.5 or later recommended.                          |
624 +-------------------------+----------------------------------------------------+
625 | LLVM_BUILD_LLVM_DYLIB   | Generate libLLVM.so. This library contains a       |
626 |                         | default set of LLVM components that can be         |
627 |                         | overridden with ``LLVM_DYLIB_COMPONENTS``. The     |
628 |                         | default contains most of LLVM and is defined in    |
629 |                         | ``tools/llvm-shlib/CMakelists.txt``.               |
630 +-------------------------+----------------------------------------------------+
631 | LLVM_OPTIMIZED_TABLEGEN | Builds a release tablegen that gets used during    |
632 |                         | the LLVM build. This can dramatically speed up     |
633 |                         | debug builds.                                      |
634 +-------------------------+----------------------------------------------------+
636 To configure LLVM, follow these steps:
638 #. Change directory into the object root directory:
640    .. code-block:: console
642      % cd OBJ_ROOT
644 #. Run the ``cmake``:
646    .. code-block:: console
648      % cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=/install/path
649        [other options] SRC_ROOT
651 Compiling the LLVM Suite Source Code
652 ------------------------------------
654 Unlike with autotools, with CMake your build type is defined at configuration.
655 If you want to change your build type, you can re-run cmake with the following
656 invocation:
658    .. code-block:: console
660      % cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=type SRC_ROOT
662 Between runs, CMake preserves the values set for all options. CMake has the
663 following build types defined:
665 Debug
667   These builds are the default. The build system will compile the tools and
668   libraries unoptimized, with debugging information, and asserts enabled.
670 Release
672   For these builds, the build system will compile the tools and libraries
673   with optimizations enabled and not generate debug info. CMakes default
674   optimization level is -O3. This can be configured by setting the
675   ``CMAKE_CXX_FLAGS_RELEASE`` variable on the CMake command line.
677 RelWithDebInfo
679   These builds are useful when debugging. They generate optimized binaries with
680   debug information. CMakes default optimization level is -O2. This can be
681   configured by setting the ``CMAKE_CXX_FLAGS_RELWITHDEBINFO`` variable on the
682   CMake command line.
684 Once you have LLVM configured, you can build it by entering the *OBJ_ROOT*
685 directory and issuing the following command:
687 .. code-block:: console
689   % make
691 If the build fails, please `check here`_ to see if you are using a version of
692 GCC that is known not to compile LLVM.
694 If you have multiple processors in your machine, you may wish to use some of the
695 parallel build options provided by GNU Make.  For example, you could use the
696 command:
698 .. code-block:: console
700   % make -j2
702 There are several special targets which are useful when working with the LLVM
703 source code:
705 ``make clean``
707   Removes all files generated by the build.  This includes object files,
708   generated C/C++ files, libraries, and executables.
710 ``make install``
712   Installs LLVM header files, libraries, tools, and documentation in a hierarchy
713   under ``$PREFIX``, specified with ``CMAKE_INSTALL_PREFIX``, which
714   defaults to ``/usr/local``.
716 ``make docs-llvm-html``
718   If configured with ``-DLLVM_ENABLE_SPHINX=On``, this will generate a directory
719   at ``OBJ_ROOT/docs/html`` which contains the HTML formatted documentation.
721 Cross-Compiling LLVM
722 --------------------
724 It is possible to cross-compile LLVM itself. That is, you can create LLVM
725 executables and libraries to be hosted on a platform different from the platform
726 where they are built (a Canadian Cross build). To generate build files for
727 cross-compiling CMake provides a variable ``CMAKE_TOOLCHAIN_FILE`` which can
728 define compiler flags and variables used during the CMake test operations.
730 The result of such a build is executables that are not runnable on the build
731 host but can be executed on the target. As an example the following CMake
732 invocation can generate build files targeting iOS. This will work on macOS
733 with the latest Xcode:
735 .. code-block:: console
737   % cmake -G "Ninja" -DCMAKE_OSX_ARCHITECTURES="armv7;armv7s;arm64"
738     -DCMAKE_TOOLCHAIN_FILE=<PATH_TO_LLVM>/cmake/platforms/iOS.cmake
739     -DCMAKE_BUILD_TYPE=Release -DLLVM_BUILD_RUNTIME=Off -DLLVM_INCLUDE_TESTS=Off
740     -DLLVM_INCLUDE_EXAMPLES=Off -DLLVM_ENABLE_BACKTRACES=Off [options]
741     <PATH_TO_LLVM>
743 Note: There are some additional flags that need to be passed when building for
744 iOS due to limitations in the iOS SDK.
746 Check :doc:`HowToCrossCompileLLVM` and `Clang docs on how to cross-compile in general
747 <http://clang.llvm.org/docs/CrossCompilation.html>`_ for more information
748 about cross-compiling.
750 The Location of LLVM Object Files
751 ---------------------------------
753 The LLVM build system is capable of sharing a single LLVM source tree among
754 several LLVM builds.  Hence, it is possible to build LLVM for several different
755 platforms or configurations using the same source tree.
757 * Change directory to where the LLVM object files should live:
759   .. code-block:: console
761     % cd OBJ_ROOT
763 * Run ``cmake``:
765   .. code-block:: console
767     % cmake -G "Unix Makefiles" SRC_ROOT
769 The LLVM build will create a structure underneath *OBJ_ROOT* that matches the
770 LLVM source tree. At each level where source files are present in the source
771 tree there will be a corresponding ``CMakeFiles`` directory in the *OBJ_ROOT*.
772 Underneath that directory there is another directory with a name ending in
773 ``.dir`` under which you'll find object files for each source.
775 For example:
777   .. code-block:: console
779     % cd llvm_build_dir
780     % find lib/Support/ -name APFloat*
781     lib/Support/CMakeFiles/LLVMSupport.dir/APFloat.cpp.o
783 Optional Configuration Items
784 ----------------------------
786 If you're running on a Linux system that supports the `binfmt_misc
787 <http://en.wikipedia.org/wiki/binfmt_misc>`_
788 module, and you have root access on the system, you can set your system up to
789 execute LLVM bitcode files directly. To do this, use commands like this (the
790 first command may not be required if you are already using the module):
792 .. code-block:: console
794   % mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
795   % echo ':llvm:M::BC::/path/to/lli:' > /proc/sys/fs/binfmt_misc/register
796   % chmod u+x hello.bc   (if needed)
797   % ./hello.bc
799 This allows you to execute LLVM bitcode files directly.  On Debian, you can also
800 use this command instead of the 'echo' command above:
802 .. code-block:: console
804   % sudo update-binfmts --install llvm /path/to/lli --magic 'BC'
806 .. _Program Layout:
807 .. _general layout:
809 Directory Layout
810 ================
812 One useful source of information about the LLVM source base is the LLVM `doxygen
813 <http://www.doxygen.org/>`_ documentation available at
814 `<http://llvm.org/doxygen/>`_.  The following is a brief introduction to code
815 layout:
817 ``llvm/examples``
818 -----------------
820 Simple examples using the LLVM IR and JIT.
822 ``llvm/include``
823 ----------------
825 Public header files exported from the LLVM library. The three main subdirectories:
827 ``llvm/include/llvm``
829   All LLVM-specific header files, and  subdirectories for different portions of
830   LLVM: ``Analysis``, ``CodeGen``, ``Target``, ``Transforms``, etc...
832 ``llvm/include/llvm/Support``
834   Generic support libraries provided with LLVM but not necessarily specific to
835   LLVM. For example, some C++ STL utilities and a Command Line option processing
836   library store header files here.
838 ``llvm/include/llvm/Config``
840   Header files configured by ``cmake``.  They wrap "standard" UNIX and
841   C header files.  Source code can include these header files which
842   automatically take care of the conditional #includes that ``cmake``
843   generates.
845 ``llvm/lib``
846 ------------
848 Most source files are here. By putting code in libraries, LLVM makes it easy to
849 share code among the `tools`_.
851 ``llvm/lib/IR/``
853   Core LLVM source files that implement core classes like Instruction and
854   BasicBlock.
856 ``llvm/lib/AsmParser/``
858   Source code for the LLVM assembly language parser library.
860 ``llvm/lib/Bitcode/``
862   Code for reading and writing bitcode.
864 ``llvm/lib/Analysis/``
866   A variety of program analyses, such as Call Graphs, Induction Variables,
867   Natural Loop Identification, etc.
869 ``llvm/lib/Transforms/``
871   IR-to-IR program transformations, such as Aggressive Dead Code Elimination,
872   Sparse Conditional Constant Propagation, Inlining, Loop Invariant Code Motion,
873   Dead Global Elimination, and many others.
875 ``llvm/lib/Target/``
877   Files describing target architectures for code generation.  For example,
878   ``llvm/lib/Target/X86`` holds the X86 machine description.
880 ``llvm/lib/CodeGen/``
882   The major parts of the code generator: Instruction Selector, Instruction
883   Scheduling, and Register Allocation.
885 ``llvm/lib/MC/``
887   (FIXME: T.B.D.)  ....?
889 ``llvm/lib/ExecutionEngine/``
891   Libraries for directly executing bitcode at runtime in interpreted and
892   JIT-compiled scenarios.
894 ``llvm/lib/Support/``
896   Source code that corresponding to the header files in ``llvm/include/ADT/``
897   and ``llvm/include/Support/``.
899 ``llvm/projects``
900 -----------------
902 Projects not strictly part of LLVM but shipped with LLVM. This is also the
903 directory for creating your own LLVM-based projects which leverage the LLVM
904 build system.
906 ``llvm/test``
907 -------------
909 Feature and regression tests and other sanity checks on LLVM infrastructure. These
910 are intended to run quickly and cover a lot of territory without being exhaustive.
912 ``test-suite``
913 --------------
915 A comprehensive correctness, performance, and benchmarking test suite
916 for LLVM.  This comes in a ``separate git repository
917 <https://github.com/llvm/llvm-test-suite>``, because it contains a
918 large amount of third-party code under a variety of licenses. For
919 details see the :doc:`Testing Guide <TestingGuide>` document.
921 .. _tools:
923 ``llvm/tools``
924 --------------
926 Executables built out of the libraries
927 above, which form the main part of the user interface.  You can always get help
928 for a tool by typing ``tool_name -help``.  The following is a brief introduction
929 to the most important tools.  More detailed information is in
930 the `Command Guide <CommandGuide/index.html>`_.
932 ``bugpoint``
934   ``bugpoint`` is used to debug optimization passes or code generation backends
935   by narrowing down the given test case to the minimum number of passes and/or
936   instructions that still cause a problem, whether it is a crash or
937   miscompilation. See `<HowToSubmitABug.html>`_ for more information on using
938   ``bugpoint``.
940 ``llvm-ar``
942   The archiver produces an archive containing the given LLVM bitcode files,
943   optionally with an index for faster lookup.
945 ``llvm-as``
947   The assembler transforms the human readable LLVM assembly to LLVM bitcode.
949 ``llvm-dis``
951   The disassembler transforms the LLVM bitcode to human readable LLVM assembly.
953 ``llvm-link``
955   ``llvm-link``, not surprisingly, links multiple LLVM modules into a single
956   program.
958 ``lli``
960   ``lli`` is the LLVM interpreter, which can directly execute LLVM bitcode
961   (although very slowly...). For architectures that support it (currently x86,
962   Sparc, and PowerPC), by default, ``lli`` will function as a Just-In-Time
963   compiler (if the functionality was compiled in), and will execute the code
964   *much* faster than the interpreter.
966 ``llc``
968   ``llc`` is the LLVM backend compiler, which translates LLVM bitcode to a
969   native code assembly file.
971 ``opt``
973   ``opt`` reads LLVM bitcode, applies a series of LLVM to LLVM transformations
974   (which are specified on the command line), and outputs the resultant
975   bitcode.   '``opt -help``'  is a good way to get a list of the
976   program transformations available in LLVM.
978   ``opt`` can also  run a specific analysis on an input LLVM bitcode
979   file and print  the results.  Primarily useful for debugging
980   analyses, or familiarizing yourself with what an analysis does.
982 ``llvm/utils``
983 --------------
985 Utilities for working with LLVM source code; some are part of the build process
986 because they are code generators for parts of the infrastructure.
989 ``codegen-diff``
991   ``codegen-diff`` finds differences between code that LLC
992   generates and code that LLI generates. This is useful if you are
993   debugging one of them, assuming that the other generates correct output. For
994   the full user manual, run ```perldoc codegen-diff'``.
996 ``emacs/``
998    Emacs and XEmacs syntax highlighting  for LLVM   assembly files and TableGen
999    description files.  See the ``README`` for information on using them.
1001 ``getsrcs.sh``
1003   Finds and outputs all non-generated source files,
1004   useful if one wishes to do a lot of development across directories
1005   and does not want to find each file. One way to use it is to run,
1006   for example: ``xemacs `utils/getsources.sh``` from the top of the LLVM source
1007   tree.
1009 ``llvmgrep``
1011   Performs an ``egrep -H -n`` on each source file in LLVM and
1012   passes to it a regular expression provided on ``llvmgrep``'s command
1013   line. This is an efficient way of searching the source base for a
1014   particular regular expression.
1016 ``TableGen/``
1018   Contains the tool used to generate register
1019   descriptions, instruction set descriptions, and even assemblers from common
1020   TableGen description files.
1022 ``vim/``
1024   vim syntax-highlighting for LLVM assembly files
1025   and TableGen description files. See the    ``README`` for how to use them.
1027 .. _simple example:
1029 An Example Using the LLVM Tool Chain
1030 ====================================
1032 This section gives an example of using LLVM with the Clang front end.
1034 Example with clang
1035 ------------------
1037 #. First, create a simple C file, name it 'hello.c':
1039    .. code-block:: c
1041      #include <stdio.h>
1043      int main() {
1044        printf("hello world\n");
1045        return 0;
1046      }
1048 #. Next, compile the C file into a native executable:
1050    .. code-block:: console
1052      % clang hello.c -o hello
1054    .. note::
1056      Clang works just like GCC by default.  The standard -S and -c arguments
1057      work as usual (producing a native .s or .o file, respectively).
1059 #. Next, compile the C file into an LLVM bitcode file:
1061    .. code-block:: console
1063      % clang -O3 -emit-llvm hello.c -c -o hello.bc
1065    The -emit-llvm option can be used with the -S or -c options to emit an LLVM
1066    ``.ll`` or ``.bc`` file (respectively) for the code.  This allows you to use
1067    the `standard LLVM tools <CommandGuide/index.html>`_ on the bitcode file.
1069 #. Run the program in both forms. To run the program, use:
1071    .. code-block:: console
1073       % ./hello
1075    and
1077    .. code-block:: console
1079      % lli hello.bc
1081    The second examples shows how to invoke the LLVM JIT, :doc:`lli
1082    <CommandGuide/lli>`.
1084 #. Use the ``llvm-dis`` utility to take a look at the LLVM assembly code:
1086    .. code-block:: console
1088      % llvm-dis < hello.bc | less
1090 #. Compile the program to native assembly using the LLC code generator:
1092    .. code-block:: console
1094      % llc hello.bc -o hello.s
1096 #. Assemble the native assembly language file into a program:
1098    .. code-block:: console
1100      % /opt/SUNWspro/bin/cc -xarch=v9 hello.s -o hello.native   # On Solaris
1102      % gcc hello.s -o hello.native                              # On others
1104 #. Execute the native code program:
1106    .. code-block:: console
1108      % ./hello.native
1110    Note that using clang to compile directly to native code (i.e. when the
1111    ``-emit-llvm`` option is not present) does steps 6/7/8 for you.
1113 Common Problems
1114 ===============
1116 If you are having problems building or using LLVM, or if you have any other
1117 general questions about LLVM, please consult the `Frequently Asked
1118 Questions <FAQ.html>`_ page.
1120 .. _links:
1122 Links
1123 =====
1125 This document is just an **introduction** on how to use LLVM to do some simple
1126 things... there are many more interesting and complicated things that you can do
1127 that aren't documented here (but we'll gladly accept a patch if you want to
1128 write something up!).  For more information about LLVM, check out:
1130 * `LLVM Homepage <http://llvm.org/>`_
1131 * `LLVM Doxygen Tree <http://llvm.org/doxygen/>`_
1132 * `Starting a Project that Uses LLVM <http://llvm.org/docs/Projects.html>`_
1134 .. _installing arcanist: https://secure.phabricator.com/book/phabricator/article/arcanist_quick_start/