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
$19.99 per month
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3 (7 Ratings)
Paperback Dec 2015 166 pages 1st Edition
eBook
NZ$21.99 NZ$31.99
Paperback
NZ$39.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
$19.99 per month
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.3 (7 Ratings)
Paperback Dec 2015 166 pages 1st Edition
eBook
NZ$21.99 NZ$31.99
Paperback
NZ$39.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
NZ$21.99 NZ$31.99
Paperback
NZ$39.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781785280801
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 21, 2015
Length: 166 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280801
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 NZ$7 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 NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 183.97
LLVM Essentials
NZ$39.99
Getting started with LLVM core libraries
NZ$71.99
LLVM Cookbook
NZ$71.99
Total NZ$ 183.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.