"clang" CFE Internals Manual

Introduction

This document describes some of the more important APIs and internal design decisions made in the clang C front-end. The purpose of this document is to both capture some of this high level information and also describe some of the design decisions behind it. This is meant for people interested in hacking on clang, not for end-users. The description below is categorized by libraries, and does not describe any of the clients of the libraries.

LLVM System and Support Libraries

The LLVM libsystem library provides the basic clang system abstraction layer, which is used for file system access. The LLVM libsupport library provides many underlying libraries and data-structures, including command line option processing and various containers.

The clang 'Basic' Library

This library certainly needs a better name. The 'basic' library contains a number of low-level utilities for tracking and manipulating source buffers, locations within the source buffers, diagnostics, tokens, target abstraction, and information about the subset of the language being compiled for.

Part of this infrastructure is specific to C (such as the TargetInfo class), other parts could be reused for other non-C-based languages (SourceLocation, SourceManager, Diagnostics, FileManager). When and if there is future demand we can figure out if it makes sense to introduce a new library, move the general classes somewhere else, or introduce some other solution.

We describe the roles of these classes in order of their dependencies.

The SourceLocation and SourceManager classes

Strangely enough, the SourceLocation class represents a location within the source code of the program. Important design points include:

  1. sizeof(SourceLocation) must be extremely small, as these are embedded into many AST nodes and are passed around often. Currently it is 32 bits.
  2. SourceLocation must be a simple value object that can be efficiently copied.
  3. We should be able to represent a source location for any byte of any input file. This includes in the middle of tokens, in whitespace, in trigraphs, etc.
  4. A SourceLocation must encode the current #include stack that was active when the location was processed. For example, if the location corresponds to a token, it should contain the set of #includes active when the token was lexed. This allows us to print the #include stack for a diagnostic.
  5. SourceLocation must be able to describe macro expansions, capturing both the ultimate instantiation point and the source of the original character data.

In practice, the SourceLocation works together with the SourceManager class to encode two pieces of information about a location: it's physical location and it's virtual location. For most tokens, these will be the same. However, for a macro expansion (or tokens that came from a _Pragma directive) these will describe the location of the characters corresponding to the token and the location where the token was used (i.e. the macro instantiation point or the location of the _Pragma itself).

For efficiency, we only track one level of macro instantions: if a token was produced by multiple instantiations, we only track the source and ultimate destination. Though we could track the intermediate instantiation points, this would require extra bookkeeping and no known client would benefit substantially from this.

The clang front-end inherently depends on the location of a token being tracked correctly. If it is ever incorrect, the front-end may get confused and die. The reason for this is that the notion of the 'spelling' of a Token in clang depends on being able to find the original input characters for the token. This concept maps directly to the "physical" location for the token.

The Lexer and Preprocessor Library

The Lexer library contains several tightly-connected classes that are involved with the nasty process of lexing and preprocessing C source code. The main interface to this library for outside clients is the large Preprocessor class. It contains the various pieces of state that are required to coherently read tokens out of a translation unit.

The core interface to the Preprocessor object (once it is set up) is the Preprocessor::Lex method, which returns the next Token from the preprocessor stream. There are two types of token providers that the preprocessor is capable of reading from: a buffer lexer (provided by the Lexer class) and a buffered token stream (provided by the MacroExpander class).

The Token class

The Token class is used to represent a single lexed token. Tokens are intended to be used by the lexer/preprocess and parser libraries, but are not intended to live beyond them (for example, they should not live in the ASTs).

Tokens most often live on the stack (or some other location that is efficient to access) as the parser is running, but occasionally do get buffered up. For example, macro definitions are stored as a series of tokens, and the C++ front-end will eventually need to buffer tokens up for tentative parsing and various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit system, sizeof(Token) is currently 16 bytes.

Tokens contain the following information:

One interesting (and somewhat unusual) aspect of tokens is that they don't contain any semantic information about the lexed value. For example, if the token was a pp-number token, we do not represent the value of the number that was lexed (this is left for later pieces of code to decide). Additionally, the lexer library has no notion of typedef names vs variable names: both are returned as identifiers, and the parser is left to decide whether a specific identifier is a typedef or a variable (tracking this requires scope information among other things).

The Lexer class

The Lexer class provides the mechanics of lexing tokens out of a source buffer and deciding what they mean. The Lexer is complicated by the fact that it operates on raw buffers that have not had spelling eliminated (this is a necessity to get decent performance), but this is countered with careful coding as well as standard performance techniques (for example, the comment handling code is vectorized on X86 and PowerPC hosts).

The lexer has a couple of interesting modal features:

In addition to these modes, the lexer keeps track of a couple of other features that are local to a lexed buffer, which change as the buffer is lexed:

The MacroExpander class

The MacroExpander class is a token provider that returns tokens from a list of tokens that came from somewhere else. It typically used for two things: 1) returning tokens from a macro definition as it is being expanded 2) returning tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and will most likely be used to handle unbounded look-ahead for the C++ parser.

The MultipleIncludeOpt class

The MultipleIncludeOpt class implements a really simple little state machine that is used to detect the standard "#ifndef XX / #define XX" idiom that people typically use to prevent multiple inclusion of headers. If a buffer uses this idiom and is subsequently #include'd, the preprocessor can simply check to see whether the guarding condition is defined or not. If so, the preprocessor can completely ignore the include of the header.

The Parser Library

The AST Library

The Type class and its subclasses

The Type class (and its subclasses) are an important part of the AST. Types are accessed through the ASTContext class, which implicitly creates and uniques them as they are needed. Types have a couple of non-obvious features: 1) they do not capture type qualifiers like const or volatile (See QualType), and 2) they implicitly capture typedef information. Once created, types are immutable (unlike decls).

Typedefs in C make semantic analysis a bit more complex than it would be without them. The issue is that we want to capture typedef information and represent it in the AST perfectly, but the semantics of operations need to "see through" typedefs. For example, consider this code:

void func() {
  typedef int foo;
  foo X, *Y;
  typedef foo* bar;
  bar Z;
  *X; // error
  **Y; // error
  **Z; // error
}

The code above is illegal, and thus we expect there to be diagnostics emitted on the annotated lines. In this example, we expect to get:

test.c:6:1: error: indirection requires pointer operand ('foo' invalid)
*X; // error
^~
test.c:7:1: error: indirection requires pointer operand ('foo' invalid)
**Y; // error
^~~
test.c:8:1: error: indirection requires pointer operand ('foo' invalid)
**Z; // error
^~~

While this example is somewhat silly, it illustrates the point: we want to retain typedef information where possible, so that we can emit errors about "std::string" instead of "std::basic_string<char, std:...". Doing this requires properly keeping typedef information (for example, the type of "X" is "foo", not "int"), and requires properly propagating it through the various operators (for example, the type of *Y is "foo", not "int"). In order to retain this information, the type of these expressions is an instance of the TypedefType class, which indicates that the type of these expressions is a typedef for foo.

Representing types like this is great for diagnostics, because the user-specified type is always immediately available. There are two problems with this: first, various semantic checks need to make judgements about the actual structure of a type, ignoring typdefs. Second, we need an efficient way to query whether two types are structurally identical to each other, ignoring typedefs. The solution to both of these problems is the idea of canonical types.

Canonical Types

Every instance of the Type class contains a canonical type pointer. For simple types with no typedefs involved (e.g. "int", "int*", "int**"), the type just points to itself. For types that have a typedef somewhere in their structure (e.g. "foo", "foo*", "foo**", "bar"), the canonical type pointer points to their structurally equivalent type without any typedefs (e.g. "int", "int*", "int**", and "int*" respectively).

This design provides a constant time operation (dereferencing the canonical type pointer) that gives us access to the structure of types. For example, we can trivially tell that "bar" and "foo*" are the same type by dereferencing their canonical type pointers and doing a pointer comparison (they both point to the single "int*" type).

Canonical types and typedef types bring up some complexities that must be carefully managed. Specifically, the "isa/cast/dyncast" operators generally shouldn't be used in code that is inspecting the AST. For example, when type checking the indirection operator (unary '*' on a pointer), the type checker must verify that the operand has a pointer type. It would not be correct to check that with "isa<PointerType>(SubExpr->getType())", because this predicate would fail if the subexpression had a typedef type.

The solution to this problem are a set of helper methods on Type, used to check their properties. In this case, it would be correct to use "SubExpr->getType()->isPointerType()" to do the check. This predicate will return true if the canonical type is a pointer, which is true any time the type is structurally a pointer type. The only hard part here is remembering not to use the isa/cast/dyncast operations.

The second problem we face is how to get access to the pointer type once we know it exists. To continue the example, the result type of the indirection operator is the pointee type of the subexpression. In order to determine the type, we need to get the instance of PointerType that best captures the typedef information in the program. If the type of the expression is literally a PointerType, we can return that, otherwise we have to dig through the typedefs to find the pointer type. For example, if the subexpression had type "foo*", we could return that type as the result. If the subexpression had type "bar", we want to return "foo*" (note that we do not want "int*"). In order to provide all of this, Type has a getAsPointerType() method that checks whether the type is structurally a PointerType and, if so, returns the best one. If not, it returns a null pointer.

This structure is somewhat mystical, but after meditating on it, it will make sense to you :).

The QualType class

The QualType class is designed as a trivial value class that is small, passed by-value and is efficient to query. The idea of QualType is that it stores the type qualifiers (const, volatile, restrict) separately from the types themselves: QualType is conceptually a pair of "Type*" and bits for the type qualifiers.

By storing the type qualifiers as bits in the conceptual pair, it is extremely efficient to get the set of qualifiers on a QualType (just return the field of the pair), add a type qualifier (which is a trivial constant-time operation that sets a bit), and remove one or more type qualifiers (just return a QualType with the bitfield set to empty).

Further, because the bits are stored outside of the type itself, we do not need to create duplicates of types with different sets of qualifiers (i.e. there is only a single heap allocated "int" type: "const int" and "volatile const int" both point to the same heap allocated "int" type). This reduces the heap size used to represent bits and also means we do not have to consider qualifiers when uniquing types (Type does not even contain qualifiers).

In practice, on hosts where it is safe, the 3 type qualifiers are stored in the low bit of the pointer to the Type object. This means that QualType is exactly the same size as a pointer, and this works fine on any system where malloc'd objects are at least 8 byte aligned.

The CFG class

The CFG class is designed to represent a source-level control-flow graph for a single statement (Stmt*). Typically instances of CFG are constructed for function bodies (usually an instance of CompoundStmt), but can also be instantiated to represent the control-flow of any class that subclasses Stmt, which includes simple expressions. Control-flow graphs are especially useful for performing flow- or path-sensitive program analyses on a given function.

Basic Blocks

Concretely, an instance of CFG is a collection of basic blocks. Each basic block is an instance of CFGBlock, which simply contains an ordered sequence of Stmt* (each referring to statements in the AST). The ordering of statements within a block indicates unconditional flow of control from one statement to the next. Conditional control-flow is represented using edges between basic blocks. The statements within a given CFGBlock can be traversed using the CFGBlock::*iterator interface.

A CFG object owns the instances of CFGBlock within the control-flow graph it represents. Each CFGBlock within a CFG is also uniquely numbered (accessible via CFGBlock::getBlockID()). Currently the number is based on the ordering the blocks were created, but no assumptions should be made on how CFGBlocks are numbered other than their numbers are unique and that they are numbered from 0..N-1 (where N is the number of basic blocks in the CFG).

Entry and Exit Blocks

Each instance of CFG contains two special blocks: an entry block (accessible via CFG::getEntry()), which has no incoming edges, and an exit block (accessible via CFG::getExit()), which has no outgoing edges. Neither block contains any statements, and they serve the role of providing a clear entrance and exit for a body of code such as a function body. The presence of these empty blocks greatly simplifies the implementation of many analyses built on top of CFGs.

Conditional Control-Flow

Conditional control-flow (such as those induced by if-statements and loops) is represented as edges between CFGBlocks. Because different C language constructs can induce control-flow, each CFGBlock also records an extra Stmt* that represents the terminator of the block. A terminator is simply the statement that caused the control-flow, and is used to identify the nature of the conditional control-flow between blocks. For example, in the case of an if-statement, the terminator refers to the IfStmt object in the AST that represented the given branch.

To illustrate, consider the following code example:

int foo(int x) {
  x = x + 1;

  if (x > 2) x++;
  else {
    x += 2;
    x *= 2;
  }

  return x;
}

After invoking the parser+semantic analyzer on this code fragment, the AST of the body of foo is referenced by a single Stmt*. We can then construct an instance of CFG representing the control-flow graph of this function body by single call to a static class method:

  Stmt* FooBody = ...
  CFG* FooCFG = CFG::buildCFG(FooBody);

It is the responsibility of the caller of CFG::buildCFG to delete the returned CFG* when the CFG is no longer needed.

Along with providing an interface to iterate over its CFGBlocks, the CFG class also provides methods that are useful for debugging and visualizing CFGs. For example, the method CFG::dump() dumps a pretty-printed version of the CFG to standard error. This is especially useful when one is using a debugger such as gdb. For example, here is the output of FooCFG->dump():

 [ B5 (ENTRY) ]
    Predecessors (0):
    Successors (1): B4

 [ B4 ]
    1: x = x + 1
    2: (x > 2)
    T: if [B4.2]
    Predecessors (1): B5
    Successors (2): B3 B2

 [ B3 ]
    1: x++
    Predecessors (1): B4
    Successors (1): B1

 [ B2 ]
    1: x += 2
    2: x *= 2
    Predecessors (1): B4
    Successors (1): B1

 [ B1 ]
    1: return x;
    Predecessors (2): B2 B3
    Successors (1): B0

 [ B0 (EXIT) ]
    Predecessors (1): B1
    Successors (0):

For each block, the pretty-printed output displays for each block the number of predecessor blocks (blocks that have outgoing control-flow to the given block) and successor blocks (blocks that have control-flow that have incoming control-flow from the given block). We can also clearly see the special entry and exit blocks at the beginning and end of the pretty-printed output. For the entry block (block B5), the number of predecessor blocks is 0, while for the exit block (block B0) the number of successor blocks is 0.

The most interesting block here is B4, whose outgoing control-flow represents the branching caused by the sole if-statement in foo. Of particular interest is the second statement in the block, (x > 2), and the terminator, printed as if [B4.2]. The second statement represents the evaluation of the condition of the if-statement, which occurs before the actual branching of control-flow. Within the CFGBlock for B4, the Stmt* for the second statement refers to the actual expression in the AST for (x > 2). Thus pointers to subclasses of Expr can appear in the list of statements in a block, and not just subclasses of Stmt that refer to proper C statements.

The terminator of block B4 is a pointer to the IfStmt object in the AST. The pretty-printer outputs if [B4.2] because the condition expression of the if-statement has an actual place in the basic block, and thus the terminator is essentially referring to the expression that is the second statement of block B4 (i.e., B4.2). In this manner, conditions for control-flow (which also includes conditions for loops and switch statements) are hoisted into the actual basic block.