Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
LLVM Essentials
LLVM Essentials

LLVM Essentials: Become familiar with the LLVM infrastructure and start using LLVM libraries to design a compiler

Arrow left icon
Profile Icon Suyog Sarda Profile Icon John Criswell Profile Icon Mayur Pandey Profile Icon David Farago
Arrow right icon
€10.99 €16.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3 (7 Ratings)
eBook Dec 2015 166 pages 1st Edition
eBook
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Suyog Sarda Profile Icon John Criswell Profile Icon Mayur Pandey Profile Icon David Farago
Arrow right icon
€10.99 €16.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3 (7 Ratings)
eBook Dec 2015 166 pages 1st Edition
eBook
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

LLVM Essentials

Chapter 2. Building LLVM IR

A high level programming language facilitates human interaction with the target machine. Most of the popular high level languages today have certain basic elements such as variables, loops, if-else decision making statements, blocks, functions, and so on. A variable holds value of data types; a basic block gives an idea of the scope of the variable. An if-else decision statement helps in selection of a path of code. A function makes a block of code reusable. High level languages may vary in type checking, type casting, variable declarations, complex data types, and so on. However, almost every other language has the basic building blocks listed earlier in this section.

A language may have its own parser which tokenizes the statement and extracts meaningful information such as identifier, its data type; a function name, its declaration, definition and calls; a loop condition, and so on. This meaningful information may be stored in a data structure where...

Creating an LLVM module

In the previous chapter, we got an idea as to how an LLVM IR looks. In LLVM, a module represents a single unit of code that is to be processed together. An LLVM module class is the top-level container for all other LLVM IR objects. The LLVM module contains global variables, functions, data layout, host triples, and so on. Let's create a simple LLVM module.

LLVM provides Module() constructor for creating a module. The first argument is the name of the module. The second argument is LLVMContext. Let's get these arguments in the main function and create a module as demonstrated here:

static LLVMContext &Context = getGlobalContext();
static Module *ModuleOb = new Module("my compiler", Context);

For these functions to work, we need to include certain header files:

#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
using namespace llvm;
static LLVMContext &Context = getGlobalContext();
static Module *ModuleOb = new...

Emitting a function in a module

Now that we have created a module, the next step is to emit a function. LLVM has an IRBuilder class that is used to generate LLVM IR and print it using the dump function of the Module object. LLVM provides the class llvm::Function to create a function and llvm::FunctionType() to associate a return type for the function. Let's assume that our foo() function returns an integer type.

Function *createFunc(IRBuilder<> &Builder, std::string Name) {
  FunctionType *funcType = llvm::FunctionType::get(Builder.getInt32Ty(), false);
  Function *fooFunc = llvm::Function::Create(
      funcType, llvm::Function::ExternalLinkage, Name, ModuleOb);
  return fooFunc;
}

Finally, call function verifyFunction() on fooFunc. This function performs a variety of consistency checks on the generated code, to determine if our compiler is doing everything right.

int main(int argc, char *argv[]) {
  static IRBuilder<> Builder(Context);
  Function *fooFunc = createFunc...

Adding a block to a function

A function consists of basic blocks. A basic block has an entry point. A basic block consists of a number of IR instructions, the last instruction being a terminator instruction. It has single exit point. LLVM provides the BasicBlock class to create and handle basic blocks. A basic block might have an entry point as its label, which indicates where to insert the next instructions. We can use the IRBuilder object to hold these new basic block IR.

BasicBlock *createBB(Function *fooFunc, std::string Name) {
  return BasicBlock::Create(Context, Name, fooFunc);
}

The overall code is as follows:

#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include <vector>
using namespace llvm;

static LLVMContext &Context = getGlobalContext();
static Module *ModuleOb = new Module("my compiler", Context);

Function *createFunc(IRBuilder<> &amp...

Emitting a global variable

Global variables have visibility of all the functions within a given module. LLVM provides the GlobalVariable class to create global variables and set its properties such as linkage type, alignment, and so on. The Module class has the method getOrInsertGlobal() to create a global variable. It takes two arguments—the first is the name of the variable and the second is the data type of the variable.

As global variables are part of a module, we create global variables after creating the module. Insert the following code just after creating the module in toy.cpp:

GlobalVariable *createGlob(IRBuilder<> &Builder, std::string Name) {
  ModuleOb->getOrInsertGlobal(Name, Builder.getInt32Ty());
  GlobalVariable *gVar = ModuleOb->getNamedGlobal(Name);
  gVar->setLinkage(GlobalValue::CommonLinkage);
  gVar->setAlignment(4);
  return gVar;
}

Linkage is what determines if multiple declarations of the same object refer to the same object, or to separate...

Emitting a return statement

A function might return a value or it may return void. Here in our example, we have defined that our function returns an integer. Let's assume that our function returns 0. The first step is to get a 0 value, which can be done using the Constant class.

Builder.CreateRet(Builder.getInt32(0));

The overall code is as follows:

#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include <vector>
using namespace llvm;

static LLVMContext &Context = getGlobalContext();
static Module *ModuleOb = new Module("my compiler", Context);

Function *createFunc(IRBuilder<> &Builder, std::string Name) {
  FunctionType *funcType = llvm::FunctionType::get(Builder.getInt32Ty(), false);
  Function *fooFunc = llvm::Function::Create(
      funcType, llvm::Function::ExternalLinkage, Name, ModuleOb);
  return fooFunc;
}

BasicBlock *createBB(Function...

Creating an LLVM module


In the previous chapter, we got an idea as to how an LLVM IR looks. In LLVM, a module represents a single unit of code that is to be processed together. An LLVM module class is the top-level container for all other LLVM IR objects. The LLVM module contains global variables, functions, data layout, host triples, and so on. Let's create a simple LLVM module.

LLVM provides Module() constructor for creating a module. The first argument is the name of the module. The second argument is LLVMContext. Let's get these arguments in the main function and create a module as demonstrated here:

static LLVMContext &Context = getGlobalContext();
static Module *ModuleOb = new Module("my compiler", Context);

For these functions to work, we need to include certain header files:

#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
using namespace llvm;
static LLVMContext &Context = getGlobalContext();
static Module *ModuleOb = new Module("my compiler", Context);

int main...

Emitting a function in a module


Now that we have created a module, the next step is to emit a function. LLVM has an IRBuilder class that is used to generate LLVM IR and print it using the dump function of the Module object. LLVM provides the class llvm::Function to create a function and llvm::FunctionType() to associate a return type for the function. Let's assume that our foo() function returns an integer type.

Function *createFunc(IRBuilder<> &Builder, std::string Name) {
  FunctionType *funcType = llvm::FunctionType::get(Builder.getInt32Ty(), false);
  Function *fooFunc = llvm::Function::Create(
      funcType, llvm::Function::ExternalLinkage, Name, ModuleOb);
  return fooFunc;
}

Finally, call function verifyFunction() on fooFunc. This function performs a variety of consistency checks on the generated code, to determine if our compiler is doing everything right.

int main(int argc, char *argv[]) {
  static IRBuilder<> Builder(Context);
  Function *fooFunc = createFunc(Builder...

Adding a block to a function


A function consists of basic blocks. A basic block has an entry point. A basic block consists of a number of IR instructions, the last instruction being a terminator instruction. It has single exit point. LLVM provides the BasicBlock class to create and handle basic blocks. A basic block might have an entry point as its label, which indicates where to insert the next instructions. We can use the IRBuilder object to hold these new basic block IR.

BasicBlock *createBB(Function *fooFunc, std::string Name) {
  return BasicBlock::Create(Context, Name, fooFunc);
}

The overall code is as follows:

#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include <vector>
using namespace llvm;

static LLVMContext &Context = getGlobalContext();
static Module *ModuleOb = new Module("my compiler", Context);

Function *createFunc(IRBuilder<> &Builder, std::string Name) {
  FunctionType *funcType...

Emitting a global variable


Global variables have visibility of all the functions within a given module. LLVM provides the GlobalVariable class to create global variables and set its properties such as linkage type, alignment, and so on. The Module class has the method getOrInsertGlobal() to create a global variable. It takes two arguments—the first is the name of the variable and the second is the data type of the variable.

As global variables are part of a module, we create global variables after creating the module. Insert the following code just after creating the module in toy.cpp:

GlobalVariable *createGlob(IRBuilder<> &Builder, std::string Name) {
  ModuleOb->getOrInsertGlobal(Name, Builder.getInt32Ty());
  GlobalVariable *gVar = ModuleOb->getNamedGlobal(Name);
  gVar->setLinkage(GlobalValue::CommonLinkage);
  gVar->setAlignment(4);
  return gVar;
}

Linkage is what determines if multiple declarations of the same object refer to the same object, or to separate ones...

Emitting a return statement


A function might return a value or it may return void. Here in our example, we have defined that our function returns an integer. Let's assume that our function returns 0. The first step is to get a 0 value, which can be done using the Constant class.

Builder.CreateRet(Builder.getInt32(0));

The overall code is as follows:

#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include <vector>
using namespace llvm;

static LLVMContext &Context = getGlobalContext();
static Module *ModuleOb = new Module("my compiler", Context);

Function *createFunc(IRBuilder<> &Builder, std::string Name) {
  FunctionType *funcType = llvm::FunctionType::get(Builder.getInt32Ty(), false);
  Function *fooFunc = llvm::Function::Create(
      funcType, llvm::Function::ExternalLinkage, Name, ModuleOb);
  return fooFunc;
}

BasicBlock *createBB(Function *fooFunc, std::string Name) {
  return BasicBlock...
Left arrow icon Right arrow icon

Key benefits

  • Learn to use the LLVM libraries to emit intermediate representation (IR) from high-level language
  • Build your own optimization pass for better code generation
  • Understand AST generation and use it in a meaningful way

Description

LLVM is currently the point of interest for many firms, and has a very active open source community. It provides us with a compiler infrastructure that can be used to write a compiler for a language. It provides us with a set of reusable libraries that can be used to optimize code, and a target-independent code generator to generate code for different backends. It also provides us with a lot of other utility tools that can be easily integrated into compiler projects. This book details how you can use the LLVM compiler infrastructure libraries effectively, and will enable you to design your own custom compiler with LLVM in a snap. We start with the basics, where you’ll get to know all about LLVM. We then cover how you can use LLVM library calls to emit intermediate representation (IR) of simple and complex high-level language paradigms. Moving on, we show you how to implement optimizations at different levels, write an optimization pass, generate code that is independent of a target, and then map the code generated to a backend. The book also walks you through CLANG, IR to IR transformations, advanced IR block transformations, and target machines. By the end of this book, you’ll be able to easily utilize the LLVM libraries in your own projects.

Who is this book for?

This book is intended for those who already know some of the concepts of compilers and want to quickly get familiar with the LLVM infrastructure and the rich set of libraries that it provides.

What you will learn

  • Get an introduction to LLVM modular design and LLVM tools
  • Convert frontend code to LLVM IR
  • Implement advanced LLVM IR paradigms
  • Understand the LLVM IR Optimization Pass Manager infrastructure and write an optimization pass
  • Absorb LLVM IR transformations
  • Understand the steps involved in converting LLVM IR to Selection DAG
  • Implement a custom target using the LLVM infrastructure
  • Get a grasp of C's frontend clang, an AST dump, and static analysis

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 21, 2015
Length: 166 pages
Edition : 1st
Language : English
ISBN-13 : 9781783558629
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 21, 2015
Length: 166 pages
Edition : 1st
Language : English
ISBN-13 : 9781783558629
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 94.97
LLVM Essentials
€20.99
Getting started with LLVM core libraries
€36.99
LLVM Cookbook
€36.99
Total 94.97 Stars icon

Table of Contents

8 Chapters
1. Playing with LLVM Chevron down icon Chevron up icon
2. Building LLVM IR Chevron down icon Chevron up icon
3. Advanced LLVM IR Chevron down icon Chevron up icon
4. Basic IR Transformations Chevron down icon Chevron up icon
5. Advanced IR Block Transformations Chevron down icon Chevron up icon
6. IR to Selection DAG phase Chevron down icon Chevron up icon
7. Generating Code for Target Architecture Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3
(7 Ratings)
5 star 0%
4 star 14.3%
3 star 28.6%
2 star 28.6%
1 star 28.6%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer Sep 02, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I knew nothing about LLVM and was going to start playing with it. The web has too much information for a rookie and the book just saved me some time in learning.
Amazon Verified review Amazon
Amazon Customer Jul 24, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
this helps you to grasp the basic of LLVM in 3 hours.
Amazon Verified review Amazon
Gideon Buckwalter Jan 29, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Overall not bad, but the version of LLVM this book uses is somewhat out of date, so a lot of the examples did not compile without tweaking. The major focus of the book is on the C++ API for building IR code and optimization passes. I was hoping this would be a language reference for the intermediate representation, but it is not.I also noticed a surprising number of grammar mistakes which is unfortunate. Hopefully these will be fixed in the next edition.
Amazon Verified review Amazon
poorna shashank May 10, 2019
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Half of the book is filled with repititive code. Lots of the pages are redundant. I would have loved if he explained how a syntax is related to a concept in theory.Examples are very basic. Not recommended if you know compiler basics, llvm web documentation is better
Amazon Verified review Amazon
David Lamkins Nov 15, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Poorly edited: inconsistent use of terminology, tortured grammar, unclear and poorly-explained examples. way too much repetition, etc.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.