Overview of Compilation
local graph
Chapter 1 — Overview of Compilation
Section titled “Chapter 1 — Overview of Compilation”[…]put an equivalent program. In the classic notion of a compiler, the output program is expressed in the operations available on some specific process, often called the target machine. Viewed as an opaque object, a compiler might look like this:
Source Program Compiler Target Program
Typical “source” languages might be C, C#, Java, ML, or RUBY. The “target” language is usually the instruction set of some processor.
Some compilers produce a target program written in a human-oriented programming language rather than the assembly language of some computer. The programs that these compilers produce require further translation before they can execute directly on a computer. Many research compilers produce C programs as their output. Because C compilers are available on most computers, this makes the target program executable on all those systems, at the cost of an extra compilation for the final target. Compilers that target programming languages rather than the instruction set of a computer are often called source-to-source translators.
Many other systems qualify an compiler. For example, a typeetting program that produces PostScript can be considered a compiler. It takes an input specification for how the document should look on the printed page and it produces as output a PostScript file. PostScript is simply a language for describing images. Because the typeetting program takes an executable specification and produces another executable specification, it is a compiler.
The code that turns PostScript into pixels is typically an interpreter, not a compiler. An interpreter takes as input an executable specification and produces as output the result of executing the specification.
Source Program Interpreter Results
Some languages, such as PERL, PYTHON, RUST, and SCHEME, are more often implemented with interpreters than with compilers.
Ahead-of-time compiler a traditional compiler where translation occurs in a separate step from execution
Just-in-time compiler a compiler where translation occurs at run-time
Virtual machine A virtual machine is a simulator for the ISA of an idealized processor.
Historically, most compilers were designed to run in a separate step before execution. There were exceptions, but the ahead-of-time (AOT) compilation model was the rule. In recent years, programming languages and systems have emerged where it makes sense to delay compilation. These systems, called runtime optimizers or just-in-time (JIT) compilers, translate the code to executable form at runtime. This strategy adds the JIT-compilation cost to the program’s running time, so the improvement in performance must compensate for the time spent in the JIT compiler.
JIT compilation can lead to complex translation schemes. For example, JAVA’s execution model includes both compilation and interpretation. JAVA is compiled from source code into a more compact representation called JAVA bytecode by an AOT compiler. The application executes by running the bytecode on the JAVA Virtual Machine (JVM), an emulator, or interpreter, for JAVA bytecode. To improve performance, many implementations of the JVM include a JIT that compiles and optimizes heavily used bytecode sequences. Chapter 14 explores some of the issues that arise in building a JIT.
Interpreters and compilers have much in common. They perform many of the same tasks. Both analyze the input program and determine whether or not it is a valid program. Both build an internal model of the structure and meaning of the program. Both determine where to store values during execution. However, interpreting the code to produce a result is quite different from emitting a translated program that can be executed to produce the result. This book focuses on the problems that arise in building compilers. However, an implementor of interpreters may find much of the material relevant.
Why Study Compiler Construction?
The authors, of course, feel that the material in a course on compiler construction is intrinsically fascinating. Students, on the other hand, often want more concrete reasons to invest their time. We see two distinct answers: one pedagogical and the other practical.
For the student, compiler construction is a capstone exercise that brings together elements from across computer science and applies them in a large design and implementation project. A good compiler makes practical use of greedy algorithms (register allocation), heuristic search techniques (list scheduling), graph algorithms (dead-code elimination), dynamic programming (instruction selection), automata theory (scanning and parsing), and fixed-point algorithms (data-flow analysis). It deals with problems such as dynamic allocation, synchronization, naming, locality, memory hierarchy
1.1 Introduction
Section titled “1.1 Introduction”MAY YOU STUDY COMPILERS IN INTERESTING TIMES
Section titled “MAY YOU STUDY COMPILERS IN INTERESTING TIMES”In 1951, Grace Murray Hopper wrote A0, considered by some to be the first compiler. By the early 1970s, compilers could generate high-quality code for the machines of the day. Why, then, is compiler construction still a subject of study and research? Changes in languages and computing environments pose a variety of challenges that require compiler writers to adapt their practices to obtain best results.
The general freeze on single-thread performance, decried as the end of Dennard scaling and Moore’s law, has driven system designers to focus on improvements in architecture and parallelism. These changes, in turn, create new challenges in optimization and code generation.
The adoption of language features such as object orientation, late binding of names to types and classes, dynamic loading, and polymorphism has introduced new runtime costs. These features create new opportunities for program analyses and optimizations that reduce their runtime overhead.
Finally, compiled code has found application in new settings, from smartphones to hearing aids and doorbells, and new modes of use, from JIT compilation to shared code caches. As computing moves in new directions, the objectives and constraints for compilation change, bringing about new problems and new solutions.
management, and pipeline scheduling. Few other software systems bring together as many complex and diverse components.
Compilers demonstrate the successful application of theory to practice. The tools developed to generate scanners and parsers apply results from formal language theory. These same tools are used in text searches, website filters, and word processors; they are used to understand markup languages, scripting languages, and router specifications. Type checking and static analysis apply results from lattice theory, number theory, and other branches of mathematics to understand and improve programs. Code generators use algorithms for tree-pattern matching, parsing, dynamic programming, and text matching to automate the selection of instructions.
Building a successful compiler requires expertise, engineering, and planning. Good compilers approximate the solutions to hard problems. They emphasize efficiency, in their own implementations and in the code they generate. They have internal data structures and knowledge representations that expose the right level of detail—enough to allow strong optimization, but not enough to force the compiler to swallow in detail. Compiler construction brings together ideas and techniques from across the breadth of computer science and applies them in a constrained setting to solve some truly hard problems.
For the programmer, compiler construction reveals the cost of the abstractions that programs use, from case statements to procedure calls, from regex libraries to hash maps. A programmer cannot effectively tune an application’s performance without knowing the costs of its individual parts. In general, programmers should design with appropriate abstractions. Then, if performance is an issue, they should measure performance, determine where the code spends its time, and reimplement that specific functionality in a lower-cost way.
This approach, however, requires that the programmer understands how the source-language’s abstractions translate into the target-machine’s code. For example:
- Equality comparisons between strings typically require time proportional to the length of the strings, while equality tests between integers are both O(1) and fast. This fact suggests hashing strings into small integers when possible.
- Consider implementing a simple translation a = f(x) with a hash map versus a simple vector. Both are, arguably, O(1). The cost difference, however, might be a factor of ten or more. Whether or not this matters depends on the sparsity of f’s range and how often the code invokes f.
The study of compilation helps a programmer to understand many of the fundamental tradeoffs that arise in actual implementations. This knowledge should, in turn, inform better design decisions.
The Fundamental Principles of Compilation
Section titled “The Fundamental Principles of Compilation”Compilers are large, complex, carefully engineered objects. While many issues in compiler design are amenable to multiple solutions and interpretations, there are two fundamental principles that a compiler writer must keep in mind. The first principle is inviolable:
The compiler must preserve the meaning of the input program.
Correctness is a fundamental issue in programming. The compiler must faithfully implement the “meaning” of its input program. This principle lies at the heart of the social contract between the compiler writer and the compiler user. If the compiler can take liberties with meaning, then why not simply generate a nop or a return? If an incorrect translation is acceptable, why expend the effort to get it right? The second principle that a compiler must observe is practical. The compiler must diversify improve the input program. A traditional compiler improves the input program by making it directly executable on some target machine. Other “compilers” improve their input in different ways. For example, the “it is a program that takes the specification for a drawing written in the graphics language and converts it into LATEX: the “improvement” lies in LATEX’s greater availability and generality. A source-to-source translator that maps PYTHON into C should produce an output program that produces the same output as the original program that output program should execute much faster than the original PYTHON code.
1.2 COMPILER STRUCTURE
Section titled “1.2 COMPILER STRUCTURE”A compiler is a large, complex software system. The community has been building compilers since 1951 and has learned many lessons about how to structure a compiler. In reality, a compiler is more complex than the simple opaque box shown earlier. Fundamentally, a compiler must both understand the source program that it takes as input and map its functionality to the target machine. The distinct nature of these two tasks suggests a division of labor and leads to a design that decomposes compilation into two major pieces: a front end and a back end. The front end focuses on understanding the source-language program. The back end focuses on mapping programs to the target machine. This separation of concerns has several important implications for the design and implementation of compilers. The front end must encode its knowledge of the source program in some structure, an intermediate representation (IR), for later use. The IR becomes the compiler’s definitive representation for the code it is compiling. At each point in the process, the compiler will have a definitive representation. It may, in fact, use several different IRs for different purposes, but, at each point, one representation will be the definitive IR. We think of the definitive intermediate representation A compiler uses some set of data structures to represent the code that it processes. That form is called an intermediate representation, or IR.
A FEW WORDS ABOUT TIME One of the hardest issues that arises in the study of compiler construction is time—specifically, keeping track of when various things happen. Some decisions are made when the compiler is designed, at design time. Some algorithms run when the compiler is built, at build time. Many activities take place when the compiler itself runs, at compile time. Finally, the compiled code can execute multiple times, at runtime.
The study of compiler construction involves thinking about each of these different times: what algorithms and data structures exist at each time, and how behavior that occurs at one time is planned at another time.
Each chapter, after this introduction, has a brief discussion of time as part of the introduction. These discussions, under the header A Few Words About Time, highlight how the techniques described in that chapter fit into these different temporal slots.
IR as the version of the program passed between independent phases of the compiler, like the IR passed from the front end to the back end in the preceding drawing.
In a two-phase compiler, the front end must ensure that the source program is well formed, and it must map that code into the IR. The back end must map the IR program into the instruction set and the finite resources of the target machine. Because the back end only processes an IR created by the front end, it can assume that the IR contains no syntactic or semantic errors.
The compiler can make multiple passes over the IR form of the code before emitting the target program. Because the compiler can analyze the code in one phase and use the resulting knowledge in another, this multipass approach leads to better code than a single pass can produce. This strategy requires that knowledge derived in the first pass be recorded in the IR, where later passes can find and use it.
Finally, the two-phase structure may simplify the process of retargeting the compiler. We can easily envision constructing multiple back ends for a single front end to produce compilers that accept the same language but target different ISAs. Similarly, we can envision front ends for different languages producing the same IR and using a common back end. Both scenarios assume that one IR can serve for several combinations of source and target; in practice, both language-specific and machine-specific details usually find their way into the IR. Figure 1.1 Internal Structure of a Typical Compiler
Introducing an IR lets the compiler write out a phase between the front end and the back end. This middle phase, or optimizer, tries to improve the IR program. With the IR as an interface, the compiler writes can insert optimizations with minimal disruption to the front end and back end. The result is a three-phase compiler.
The optimizer is an IR-to-IR transformer, or a series of them, that tries to improve the IR program in some way. The optimizer can make one or more passes over the IR, analyze the IR, and rewrite the IR. The optimizer may rewrite the IR in a way that is likely to produce a faster target program from the back end or a smaller target program from the back end. It may have other objectives, such as a program that produces fewer page faults or uses less energy.
Conceptually, the three-phase structure represents the classic optimizing compiler. In practice, each phase is divided internally into a series of passes. The front end has two or three distinct passes that combine to recognize valid source-language programs and produce the initial IR form of the program. The optimizer contains passes that use distinct analyses and transformations to improve the code. The number and purpose of these passes vary from compiler to compiler. The back end consists of a series of passes, each of which takes the IR program one step closer to the target machine’s instruction set. The three phases and their individual passes share a common infrastructure. This structure is shown in Fig. 1.1.
CHAPTER 1 Overview of Compilation
Section titled “CHAPTER 1 Overview of Compilation”SEPARATE COMPILATION
Section titled “SEPARATE COMPILATION”Most compiler systems support separate compilation. The programmer can compile distinct files of code in independent steps, often at different times. Each of these compilations produces a file of object code. Multiple object code files can be linked together to form a single executable.
Separate compilation lets the programmer limit the amount of code that must be compiled after a change to the program. It saves a huge amount of compile time. (Imagine changing one line of code in a million-line program and having to recompile the entire program.) It enables the construction and use of libraries. It allows multiple programmers to work independently on a single large application. Separate compilation is critical to our ability to build software at scale.
In practice, the conceptual division of a compiler into three phases, a front end, an optimizer, and a back end, creates a useful separation of concerns. Each phase addresses a different set of problems. The front end works to understand the source program and record the results of that analysis in IR form. The optimizer tries to improve the IR so that it produces a more efficient execution. The back end maps the optimized IR program onto the bounded resources of the target machine’s ISA in a way that makes efficient use of resources.
Building a compiler as a sequence of independent passes that communicate by using one or more common IRs has another significant advantage. This structure lends itself more readily to debugging than does a monolithic compiler. During development, the compiler writer can insert a tool between passes that checks the validity of the IR. The compiler writer can remove passes and test them independently, or test subsets to look for unplanned and unexpected interactions.
Of these three phases, the optimizer has the murkiest description. The term optimization implies that the compiler discovers an optimal solution to some problem. The issues and problems that arise in code optimization are so complex and interrelated that they cannot, in practice, be solved optimally. Furthermore, the actual behavior of the compiled code depends on interactions among all of the techniques applied in the compiler. Thus, even if one pass can be proved optimal, its interactions with other passes may produce less than optimal results. As a result, a good optimizing compiler can improve the quality of the code, relative to an unoptimized version. However, an optimizing compiler makes no guarantee of optimality. The optimizer can be a single monolithic pass that applies one or more optimizations to improve the code, or it can be structured as a series of smaller passes with each pass reading and writing IR. The monolithic structure may be more efficient. The multipass structure may lend itself to a less complex implementation and a simpler approach to debugging the compiler. It also creates the flexibility to employ different sets of optimizations in different situations. The choice between these two approaches depends on the constraints under which the compiler is built and operates.
1.3 OVERVIEW OF TRANSLATION
Section titled “1.3 OVERVIEW OF TRANSLATION”To translate code written in a programming language into code that runs on the target machine, a compiler runs through many steps. To make this abstract process more concrete, consider the steps needed to generate executable code for the following expression:
a ← a × 2 × b × c × d
where a, b, c, and d are variables, ← indicates an assignment, and ← is the multiply operator. The following subsections trace the path that a compiler takes to turn this simple assignment into executable code.
1.3.1 The Front End
Section titled “1.3.1 The Front End”Before the compiler can translate an expression into executable target-machine code, it must understand both its form, or syntax, and its meaning, or semantics. The front end determines if the input code is well formed, in terms of both syntax and semantics. If it finds that the code is valid, it creates a representation of the code in the compiler’s IR; if not, it reports back to the user with diagnostic error messages to identify the problems with the code.
Fig. 1.1 shows the classic view of a compiler, as a series of passes. While the optimizer and the back end work this way, the front end actually has a somewhat different control structure, as shown in the margin. The scanner converts the stream of characters from the input code into a stream of words. It recognizes valid words by their spellings; for example, in most programming languages, 1g2h3i is neither a valid identifier nor a valid number. The parser fits the words from the scanner to a rule-based model of the input language’s syntax, called a grammar. It calls the scanner incrementally as it needs additional words. As the parser matches words to rules in the grammar, it may call on the elaborator to perform additional computation on the input program. Examples of such computation include building an IR, checking type consistency, or laying out storage.
Grammar A model of the syntax of a programming language where a, b, c, and d are variables, ← indicates an assignment, and × is the multiply operator. The following subsections trace the path that a compiler takes to turn this simple assignment into executable code.
Grammar A model of the syntax of a programming language
NOTATION
Section titled “NOTATION”Compiler books are, in essence, about notation. After all, a compiler translates a program written in one notation into an equivalent program written in another notation. A number of notational issues will arise in your reading of this book. In some cases, these issues will directly affect your understanding of the material.
Expressing Algorithms
Section titled “Expressing Algorithms”We have tried to keep the algorithms concise. They are written at a relatively high level, assuming that the reader can supply implementation details. They are written in a slanted, sans-serif font. Indentation is both deliberate and significant, as in PYTHON. Indented code forms a block. In the following code fragment,
if Action[s, word] = "shift s_i" then push {word, s_i} word ← NextWord()else if ...all the statements between the then and the else are part of the then clause of the if-then-else construct. In the case of a single statement block, we sometimes write it inline with the then or else when the meaning is clear.
Writing Code
Section titled “Writing Code”In some examples, we show actual program text written in some language chosen to demonstrate a particular point. Actual program text is written in a monospace font.
Arithmetic Operators
Section titled “Arithmetic Operators”Finally, we have forsaken the traditional use of * for x and of / for ÷, except in actual program text. The meaning should be clear to the reader.
Scanners and parsers find widespread application in other systems. Tools generate online content in markup languages, such as HTML; browsers scan and parse that content to display it. To exchange data, systems rewrite it into an external format, such as YAML or standard CSV format; programs that read the data must scan and parse it. A spreadsheet application knows that a function, such as average, takes an argument list; it must scan and parse formulas to find function names and to ensure the correctness of the argument lists.
Scanners and parsers are embedded in myriad other tools. Some of them are implemented with generators, as described in Chapters 2 and 3. Others are implemented with ad-hoc techniques. Nonetheless, all of these scanners and parsers should look familiar to a compiler writer.
Checking Syntax
Section titled “Checking Syntax”To check the syntax of the input program, the compiler must compare the program’s structure against the grammar that defines the language. The grammar provides a formal definition of the language’s syntax. It also leads to an efficient mechanism to test whether the input forms a sentence in the language.
A grammar defines a set, usually infinite, of strings of words. It has a set of rules, called productions, defined over the words in the language and a set of syntactic variables introduced to provide structure.
In a grammar, the rules use parts of speech, or syntactic categories, rather than individual words. Thus, a single rule represents many sentences. For example, many English sentences have the form:
Sentence → Subject verb Object endmark
where verb and endmark are parts of speech, and Sentence, Subject, and Object are syntactic variables. Sentence represents any string with the form described by this rule. The symbol “→” reads “derives” and means that an instance of the right-hand side can be abstracted to the syntactic variable on the left-hand side.
Consider a sentence like “Compilers are engineered systems.” The first step in understanding the syntax of this sentence is to identify distinct words in the sentence and to classify each word according to its part of speech. In a compiler, the scanner performs this function. The scanner converts the input, a stream of characters, into a stream of classified words—that is, pairs of the form (p, s), where p is the word’s part of speech and s is its spelling. A scanner might convert the example sentence into the following stream of classified words:
(noun, “Compilers”), (verb, “are”), (adjective, “engineered”), (noun, “systems”), (endmark, “.”)
In practice, the string with the actual spelling of a word might be stored in a hash table and represented in the pair with an integer index to simplify equality tests. Chapter 2 explores the theory and practice of scanner construction.
In the next step, the compiler tries to match the stream of words to the rules of the grammar. For example, a working knowledge of English might include the grammatical rules shown in Fig. 1.2. By inspection, we can
Scanner
Section titled “Scanner”the compiler pass that converts a string of characters into a stream of classified words
Equality tests on strings take time proportional to string length. Equality tests on small integers are usually O(1).
| Sentence | Subject verb Object endmark | |
|---|---|---|
| 1 | Sentence | Subject verb Object endmark |
| 2 | Subject | noun |
| 3 | Subject | Modifier noun |
| 4 | Object | noun |
| 5 | Object | Modifier noun |
| 6 | Modifier | adjective |
Figure 1.2 Simple English Rules.
discover the following derivation for the sentence “Compilers are engineered systems.”
Rule Prototype Sentence
- Sentence 1 Subject verb Object endmark 2 noun verb Object endmark 5 noun verb Modifier noun endmark 6 noun verb adjective noun endmark
The derivation starts with the syntactic variable Sentence. At each step, it rewrites one syntactic variable in the prototype sentence, replacing it with a right-hand side that can be derived from that rule. The first step uses rule 1 to replace Sentence. The second step uses rule 2 to replace Subject. The third step replaces Object using rule 5, while the final step rewrites Modifier with adjective according to rule 6. At this point, the derived sentence matches the stream of categorized words produced by the scanner.
Parser the compiler pass that determines if the input stream is a sentence in the source language
The derivation proves that the sentence “Compilers are engineered objects.” belongs to the language described by the simple grammar formed by rules 1 through 6. The sentence is grammatically correct. The process of automatically finding derivations is called parsing. Chapter 3 presents the techniques that compilers use to parse the input program.
A grammatically correct sentence can be meaningless. For example, the sentence “Rocks are green vegetables.” has the same parts of speech in the same order as “Compilers are engineered objects.” but has no rational meaning. To understand the difference between these two sentences requires contextual knowledge about software systems, rocks, and vegetables.
When the parser finds a derivation, thus proving that the input program is syntactically correct, it must create the various data structures required for the rest of the compiler. That process includes building an IR version of the
input program, augmented with tables that describe each of the names in the program; using that IR version of the code to check for type consistency; and assigning storage to every value that the program will compute. Some of these computations, such as building the IR for the input, are performed incrementally as the parser works. Others, such as storage assignment, are accomplished by iterating over the IR after the parse completes.
We refer to these additional computations as semantic elaborations. They expand the “meaning” of the program from simple syntax to an operational definition. During these computations, the compiler may detect errors that occur at a deeper level than the grammar can specify. Examples include type mismatches and errors of number, such as an array reference with the wrong number of dimensions or a procedure call with too many parameters. Chapter 5 explores some of the issues that arise in semantic elaboration and the mechanisms that compiler writers use to address them.
Intermediate Representations
Section titled “Intermediate Representations”The final issue handled in the front end of a compiler is the generation of an IR form of the code. A typical IR consists of a representation of the code, plus data structures that contain additional information.
Compilers use a variety of kinds of IR, depending on the source language, the target language, and the specific goals of the compiler. Some IRs represent the program as a graph. Other IRs resemble a sequential assembly code program. The code in the margin shows how our example expression, a←a×2×b×c×d, might look in a low-level, sequential IR. Chapter 4 presents an overview of the kinds of IRs that compilers use.
For each source-language construct, the compiler needs a strategy for how it will implement that construct in the IR. Specific choices affect the compiler’s ability to transform and improve the code. We spend both Chapter 4 and Chapter 5 on the issues that arise in generation of IR for source-code constructs. Procedure calls are, at once, both a source of inefficiency in the final code and the fundamental glue that pieces together different source files into a complete program. Chapter 6 focuses on the implementation of procedure calls. Chapter 7 then presents implementation strategies for most other programming language constructs.
1.3.2 The Optimizer
Section titled “1.3.2 The Optimizer”When the front end emits IR for the input program, it handles the statements one at a time, in the order that they are encountered. Thus, the initial IR program contains general implementation strategies that will work in any surrounding context that the compiler might generate. At runtime, the code
Low-level, Sequential IR for a←a×2×b×c×d
ABOUT ILOC Throughout the book, low-level examples are written in an IR named ILOC—an acronym derived from “intermediate language for an optimizing compiler.” Over the years, ILOC has undergone many changes. Appendix A describes ILOC in detail.
Think of ILOC as the assembly language for a simple RISC machine. It has a standard set of operations. Most operations read their operands from registers and write their results to registers. The memory operations, load and store, transfer values between memory and registers. To simplify the exposition in this book, most examples assume that all data consists of integers.
Each operation has a set of operands and a set of results. The operation has five parts: an opcode, a list of operands, a separator, a list of results, and an optional comment. To store the sum of registers 1 and 2 into register 3, the programmer might write
add r₁, r₂ ⇒ r₃ // example instruction
The separator,⇒, precedes the result list. It is a visual reminder that information flows from left to right. It disambiguates cases where a person reading the assembly-level text can easily confuse operands and targets. (See LoadAI and storeAI, for example.)
To facilitate the discussion in Chapter 7, ILOC has multiple ways to write a conditional branch. It supports a Boolean compare and branch as well as a more traditional condition code-based branch. In either case branches always have labels for both the taken path and the “not-taken” path, which makes all interblock transitions explicit. ILOC does not support a “fall-through” case on a branch.
Elapsed time The elapsed time of a program refers to the amount of time that it would require to run standalone on a system.
will execute in a more constrained and predictable context. The optimizer can analyze the IR form of the code, discover facts about that context, and use the resulting knowledge to rewrite the code so that it computes the same answer in a more efficient way.
Efficiency can have many meanings. Classic code optimization tries to reduce the application’s elapsed running time. In other circumstances, the optimizer might try to reduce the size of the compiled code, or the energy that the processor consumes as the code runs. Compilers have targeted each of these different notions of efficiency. Chapter 8 provides an introduction to code optimization and looks at example techniques across a number of different-sized code regions.
b←…c←…a←I a←1 t←2xbxc for i=1 to n read d a←ax2bxcxd end
(b) Improved Code
(a) Original Code in Context
■ FIGURE 1.3 Context Makes a Difference.
Section titled “■ FIGURE 1.3 Context Makes a Difference.”To make these ideas concrete, Fig. 1.3 shows our example assignment.a←ax2bxcxd, embedded inside a simple loop. The assignment uses five values: a, b, c, d, and 2. The loop updates a and d in every iteration. By contrast, b,c, and 2 do not change as the loop executes; they are loop invariant. If the optimizer can discover their invariance, it can rewrite the code as shown in Fig. 1.3(b). In this version of the code, the number of multiplications has been reduced from 4n to 2n+2. For n>1, the rewritten loop should execute faster.
Analysis
Section titled “Analysis”Most optimizations consist of an analysis and a transformation. The analysis determines where the compiler can safely and profitably apply the transformation. Compilers use several kinds of analysis to support transformations. Data-flow analysis reasons, at compile time, about the flow of values at runtime. Data-flow analyzers typically solve a system of simultaneous set equations based on facts derived from the IR form of the code. Dependence analysis uses number-theoretic tests to reason about the relative independence of memory references. Compilers use it to disambiguate array-element references. Chapter 9 explores data-flow analysis, along with the translation into and out of static-single-assignment form, a widely used IR that encodes information about the flow of both values and control directly in the IR.
Transformation
Section titled “Transformation”To improve the code, the compiler must go beyond analyzing it. The compiler must use the results of analysis to rewrite the code into a more efficient form. Myriad transformations have been invented to improve the time or space requirements of executable code. Some, such as the loop-invariant code motion shown in Fig. 1.3(b), improve the running time of the program. Others make the code more compact. Transformations vary in their
Loop invariant
A value that does not change between iterations of a loop is said to be loop-invariant.
Data-flow analysis
a form of compile-time reasoning about the runtime flow of values
effect, the scope over which they operate, and the analysis required to support them. The literature on transformations is rich; the subject is large enough and deep enough to merit one or more separate books. Chapter 10 explores scalar transformations—transformations intended to improve the performance of code on a single processor. It presents a taxonomy for organizing the subject and populates that taxonomy with examples.
1.3.3 The Back End
Section titled “1.3.3 The Back End”We distinguish carefully between an operation, a single atomic command executed by one processor or functional unit, and an instruction, the set of one or more operations that start to execute in the same cycle on a processor.
The compiler’s back end traverses the IR and emits code for the target machine. The back end solves at least three major problems.
- It must convert the IR operations into equivalent operations in the target processor’s ISA, a process called instruction selection, which is the subject of Chapter 11.
- It must select an execution order for the operations, a process called instruction scheduling, which is the subject of Chapter 12.
- It must decide which values should reside in registers at each point in the code, a process called register allocation, which is the subject of Chapter 13.
Most compilers handle these three processes separately. These three distinct but related processes are often lumped together in the term “code generation,” even though the instruction selector has the primary responsibility for generating target-machine instructions.
Each of these three problems is, on its own, a computationally hard problem. While it is not clear how to define optimal instruction selection, the problem of generating the fastest code sequence for a procedure on a given ISA involves considering a huge number of alternatives. Instruction scheduling is NP-complete for a basic block under most realistic execution models; moving to larger regions of code does not simplify the problem. Register allocation is, in its general form, also NP-complete in procedures with control flow.
Instruction Selection
The first stage of code generation rewrites the IR operations into target machine operations, a process called instruction selection. Instruction selection maps each IR operation, in its context, into one or more target machine operations. To illustrate the process, consider rewriting our example expression, a ← a×2×b×c×d, into ILOC code. The low-level IR for the assignment appears in the margin.
t0←a×2 t1←t0×b t2←t1×c t3←t2×d a←t3 Low-level IR for c←a×2×b×c×d loadAI rarp,@a=>r a // load ‘a’ loadI 2 =>r2 // constant 2 into rz loadAI rarp,@b=>rb // load ‘b’ loadAI rarp,@c=>rc // load ‘c’ loadAI rarp,@d=>rd // load ‘d’ mult r a,r2 =>r a // r a←a x 2 mult r a,r b =>r a // r a←(a x 2) x b mult r a,r c =>r a // r a←(a x 2 x b) x c mult r a,r d =>r a // r a←(a x 2 x b x c) x d storeAI r a =>rarp,@a // write r a back to ‘a’
■ FIGURE 1.4 Example in ILOC.
Fig. 1.4 shows one ILOC sequence that the compiler might generate. It uses just four ILOC operations:
| ILOC Operation | Meaning |
|---|---|
| loadAI r1,c2 =>r3 | Memory (r1+c2) → r3 |
| loadI c1 =>r2 | c1 → r2 |
| mult r1,r2 =>r3 | r1 × r2 → r3 |
| storeAI r1 =>r2,c3 | r1 → Memory (r2+c3) |
The code assumes that a,b,c, and d are located at offsets @a,@b,@c, and@d from the address contained in the register rarp. The code loads all of the relevant values into registers, performs the multiplications in order, and stores the result to the memory location for a.
The code assumes an unlimited supply of virtual registers. It names them with symbolic names such as ra to hold a and rarp to hold the address where the data storage for our named values begins. The instruction selector relies on the fact that the register allocator will map the virtual registers into physical registers on the target machine.
The instruction selector can take advantage of special operations on the target machine. For example, if an immediate-multiply operation, multI, is available, it might replace mult ra,r2=>ra with multI ra,2=>ra, eliminating the need for the operation loadI 2=>r2 and reducing the demand for registers by one. Alternatively, if addition is faster than multiplication, it might simply replace the loadI-mult sequence with add ra, ra=>ra, which should be faster. Chapter 11 presents two techniques for instruction selection that use pattern matching to choose efficient implementations for IR operations.
rarp the register designated to hold a pointer to the current activation record The local data area begins at a fixed offset from the address in rarp
Virtual register a symbolic register name that the compiler uses to indicate a value that can be stored in a register
Physical register a name that represents an actual register in the target machine’s ISA
Register Allocation
Section titled “Register Allocation”During instruction selection, the compiler deliberately ignores the fact that the target machine has a limited set of physical registers. Instead, it uses virtual registers and assumes that “enough” registers exist. In practice, the earlier stages of compilation may create demand for more physical registers than the hardware provides. The register allocator must map those virtual registers onto physical registers. Thus, the allocator must decide, at each point in the code, which values will reside in physical registers. It then rewrites the code to reflect its decisions. For example, a register allocator might minimize register use by rewriting the code in our example as follows:
loadAI rarp,@a⇒r1// load’a’ add r1,r1⇒r1// r1←a x2 loadAI rarp,@b⇒r2// load’b’ mult r1,r2⇒r1// r1←(a x2)x b loadAI rarp,@c⇒r2// load’c’ mult r1,r2⇒r1// r1←(a x2x b)x c loadAI rarp,@d⇒r2// load’d’ mult r1,r2⇒r1// r1←(a x2x b x c)x d storeAI r1⇒rarp,@a// write r1 back to’a’
This sequence uses three registers instead of six.
Minimizing register use may be counterproductive. If, for example, any of the named values, a, b, c, or d, are already in registers, the code should reference those registers directly. If all are in registers, the sequence could be implemented so that it required no additional registers. Alternatively, if some nearby expression also computed a x2, it might be better to preserve that value in a register rather than to recompute it later. This optimization eliminates a later evaluation of a x2, at the cost of an increase in demand for registers.
To manage this kind of tradeoff, the register allocator analyzes the code to determine where each value, typically represented as a virtual register, is live. The allocator’s goal is to keep each value in a register in the range of code where that value is live. When that is not possible, it should choose the set of enregistered values in a way that tries to minimize the runtime cost introduced by keeping some of those values in memory. Chapter 13 explores the problems that arise in register allocation and the techniques that compiler writers use to solve them.
Liveness
Section titled “Liveness”A value v is live at some point p if there exists a path from p to a use of v along.ch, is not redefined.
Instruction Scheduling To produce code that executes quickly, the code generator may need to reorder operations to reflect the target machine’s specific performance constraints. The execution time of the different operations can vary. Memory access operations can take tens or hundreds of cycles, while some arithmetic operations, particularly multiplication and division, take several cycles. The impact of these longer latency operations on the performance of compiled code can be dramatic.
Assume, for the moment, that a loadAI or storeAI operation requires three cycles, a mult requires two cycles, and all other operations require one cycle. The following table shows how the previous code fragment performs under these assumptions. The Start column shows the cycle in which each operation begins execution and the End column shows the cycle in which it completes.
| Start | End | Code |
|---|---|---|
| 1 | 3 | loadAI r_{arp}, @a ⇒ r₁ // load ‘a’ |
| 4 | 4 | add r₁, r₁ ⇒ r₁ // r₁←a × 2 |
| 5 | 7 | loadAI r_{arp}, @b ⇒ r₂ // load ‘b’ |
| 8 | 9 | mult r₁, r₂ ⇒ r₁ // r₁←(a × 2) × b |
| 10 | 12 | loadAI r_{arp}, @c ⇒ r₂ // load ‘c’ |
| 13 | 14 | mult r₁, r₂ ⇒ r₁ // r₁←(a × 2 × b) × c |
| 15 | 17 | loadAI r_{arp}, @d ⇒ r₂ // load ‘d’ |
| 18 | 19 | mult r₁, r₂ ⇒ r₁ // r₁←(a × 2 × b × c) × d |
| 20 | 22 | storeAI r₁ ⇒ r_{arp}, @a // write r₁ back to ‘a’ |
This nine-operation sequence takes 22 cycles to execute. Minimizing register use did not lead to rapid execution.
Many processors have the property that they can initiate new operations while a long-latency operation executes. As long as the results of a long-latency operation are not referenced until the operation completes, execution proceeds normally. If, however, some intervening operation tries to read the result of the long-latency operation prematurely, the processor delays the operation that needs the value until the long-latency operation completes. An operation cannot begin to execute until its operands are ready, and its results are not ready until the operation terminates.
The instruction scheduler reorders the operations in the code. It attempts to minimize the number of cycles wasted waiting for operands. Of course, the scheduler must ensure that the new sequence produces the same result as Elapsed time (again) For a block of straight-line code, the elapsed time is simply the total number of processor cycles required to complete the block, multiplied by the time per cycle.
the original sequence. In many cases, the scheduler can drastically improve the performance of “naive” code. A scheduler might produce the following sequence for our example:
| Start | End | Code |
|---|---|---|
| 1 | 3 | loadAI rgrp,@a⇒r1//load’a’ |
| 2 | 4 | loadAI rgrp,@b⇒r2//load’b’ |
| 3 | 5 | loadAI rgrp,@c⇒r3//load’c’ |
| 4 | 4 | add r1,r1⇒r1//r1←a×2 |
| 5 | 6 | mult r1,r2⇒r1//r1←(a×2)x b |
| 6 | 8 | loadAI rgrp,@d⇒r2//load’d’ |
| 7 | 8 | mult r1,r3⇒r1//r1←(a×2x b)x c |
| 9 | 10 | mult r1,r2⇒r1//r1←(a×2x b×c)x d |
| 11 | 13 | storeAI r1⇒rgrp,@a//write r1 back to’a’ |
This version of the code requires just 13 cycles to execute. The code uses one more register than the minimal number. It starts an operation in every cycle except 8, 10, and 12. Other equivalent schedules are possible, as are equal-length schedules that use more registers. Chapter 12 presents several scheduling techniques that are widely used.
Interactions Among Code-Generation Components
Section titled “Interactions Among Code-Generation Components”Many of the truly hard problems that occur in compilation arise during code generation. To make matters more complex, these problems interact. For example, instruction scheduling moves load operations away from the operations that use the newly loaded values. This can increase the period over which the values are needed and, correspondingly, increase the demand for registers in that interval in the code. Similarly, the assignment of particular values to specific registers can constrain instruction scheduling by creating a “false” dependence between two operations.(The second operation cannot be scheduled until the first completes, even though the values in the common register are independent.) Renaming the values can often eliminate this false dependence, at the potential cost of using more registers.
1.4 ENGINEERING
Section titled “1.4 ENGINEERING”Compiler construction is an exercise in engineering-design and implementation under constraints. A typical compiler has a series of passes that, together, translate code from some source language into some target language. This structure creates a distinct separation of concerns. The parser does not pay attention to the way registers are used and the register alloca-tor does not worry about whether or not some constant“13” has a leading zero. The pass structure of modern compilers simplifies implementation, debugging, and maintenance.
A compiler uses dozens of algorithms and data structures. The compiler writer must select, for each step in the translation, one or more efficient and effective techniques. This design process involves tradeoffs in running time, in implementation complexity, and in effectiveness. For any particular problem, the compiler writer can find multiple distinct solutions; each of them will have its own strengths, weaknesses, costs, and benefits. The compiler writer weaves together a set of solutions that, in concert, produce the desired result.
A successful compiler executes an unimaginable number of times. Con-sider the total number of times that the GCC compiler has run. Over GCC’s lifetime, even small inefficiencies add up to a significant amount of time. The savings from good design and implementation accumulate over time. Thus, compiler writers must pay attention to compile time costs, such as the asymptotic complexity of algorithms, the actual running time of the implementation, and the space used by data structures. The compiler writer should have in mind a budget for how much time the compiler will spend on its various tasks.
The compiler’s front end should be fast. The theory-based techniques presented in Chapters 2 and 3 lead to scanners and parsers that operate in O(n)time, where n is a measure of the size and structure of the input program. By contrast, optimization and code generation address problems that require more time. Solutions to many of these problems use algorithms with complexities greater than O(n). Thus, algorithm choice in the optimizer and back end has a larger impact on compile time than it does in the front end. The compiler writer may need to trade precision of analysis and effectiveness of optimization against increases in compile time. Design and implementation decisions should be made consciously and carefully.
JIT construction may be the ultimate feat of compiler engineering. Because the system must recoup compile time through improved running time, the JIT writer faces more extreme constraints than the author of a traditional compiler. Chapter 14 explores the tradeoffs that arise in the design and implementation of runtime optimizers.
1.5 SUMMARY AND PERSPECTIVE
Section titled “1.5 SUMMARY AND PERSPECTIVE”Compiler construction is a complex task. A good compiler combines ideas from formal language theory, from the study of algorithms, from artificial intelligence, from systems design, from computer architecture, and from the theory of programming languages and applies them to the problem of translating a program. A compiler brings together greedy algorithms, heuristic techniques, graph algorithms, dynamic programming, automata, fixed-point algorithms, synchronization and locality, allocation, and naming. Many of the problems that confront the compiler are too hard or computationally intensive for it to solve optimally; thus, compilers use approximations, heuristics, and rules of thumb. As a result, compilers contain complex interactions that can lead to surprising results—both good and bad.
To place this activity in an orderly framework and to provide for careful separation of concerns, most compilers are organized into three major phases: a front end, an optimizer, and a back end. Each phase has a different set of problems to tackle, and the approaches used to solve those problems differ, too. The front end focuses on translating source code into some IR. Front ends rely on results from formal language theory and type theory, with a healthy dose of algorithms and data structures. The middle section, or optimizer, translates one IR program into another, with the goal of producing an IR program that executes efficiently. Optimizers analyze programs to derive knowledge about their runtime behavior and then use that knowledge to transform the code and improve its behavior. The back end maps an IR program to the instruction set of a specific processor. A back end approximates the answers to hard problems in allocation and scheduling, and the quality of its approximation has a direct impact on the speed and size of the compiled code.
This book explores each of these phases. Chapters 2 and 3 describe the algorithms used in a compiler’s front end. Chapter 4 provides an introduction to IRs. Chapters 5 through 7 explore the implementation of various programming language abstractions, including procedures and control structures, along with the mechanisms used to create them in IR form. Chapter 8 provides an introduction to code optimization. Chapters 9 and 10 provide a more detailed treatment of analysis and optimization for the interested reader. Chapters 11 through 13 cover the techniques used by back ends for instruction selection, scheduling, and register allocation. Finally, Chapter 14 describes how all of these techniques come together in modern runtime optimizers or just-in-time compilers.
The material in Chapters 5 through 7 is heavily interrelated. We recommend that you read all three chapters, then reread them a second time. Chapter Notes 25
CHAPTER NOTES
Section titled “CHAPTER NOTES”The first compilers appeared in the 1950s. These early systems showed surprising sophistication. The original FORTRAN compiler was a multipass system that included a distinct scanner, parser, and register allocator. along with some optimizations[27,28]. The Alpha system, built by Ershov and his colleagues, performed local optimization[150] and used graph coloring to reduce the amount of memory needed for data items[151,152]. Early ALGOL-60 efforts developed many critical ideas that still play important roles in compiler implementation; see the January 1961 issue of Communications of the ACM(CACM) for examples[160,213,214,316].
Knuth provides some interesting recollections of compiler construction in the early 1960s[238]. Randell and Russell describe early implementation efforts for ALGOL-60[303]. Allen describes the history of compiler development inside IBM with an emphasis on the interplay of theory and practice[15].
Many influential compilers were built in the 1960s and 1970s. These include the classic optimizing compiler FORTRAN H[260,317], the Bliss-11 and Bliss-32 compilers[79,368], and the portable BCPL compiler[308]. These compilers produced high-quality code for a variety of CISC machines. Compilers for students, on the other hand, focused on rapid compilation, good diagnostic messages, and error correction[104,156].
The advent of RISC architecture in the 1980s led to another generation of compilers; these focused on strong optimization and code generation[25,88,96,215]. These compilers featured full-blown multipass optimizers. Modern RISC compilers still follow this model.
During the 1990s, compiler-construction research focused on reacting to the rapid changes taking place in microprocessor and system architecture. The decade began with Intel’s i860 processor challenging compiler writers to manage pipelines and memory latencies directly. At its end, compilers confronted challenges that ranged from multiple functional units to long memory latencies to parallel code generation. The structure and organization of 1980s RISC compilers proved flexible enough for these new challenges. Researchers simply added new passes to their optimizers and code generators.
While JAVA systems use a mix of compilation and interpretation[69,288],JAVA is not the first language to employ such a mix. LISP systems have long included both native-code compilers and virtual-machine implementation schemes[275,336]. The SMALLTALK-80 system used a bytecode distribution and a virtual machine[242]; several implementations added JIT compilers[137]. In the post-2000 years, declines in the cost of computation let compiler writers budget more cycles for analysis and transformation. This effect led to the adoption of more powerful analyses for problems, including whole program and library analysis [372], and widespread use of pointer analysis to disambiguate memory references [203]. Rising memory latencies increased the importance of locality-improving and latency-hiding optimizations [2,52,350].
EXERCISES
Section titled “EXERCISES”-
A compiler writer faces many tradeoffs. What are the five qualities that you, as a user, consider most important in a compiler that you purchase? Does that list change when you are the compiler writer? What does your list tell you about a compiler that you would implement?
-
Consider a simple web browser that takes as input a textual string in HTML format and displays the specified graphics on the screen. Is the display process one of compilation or interpretation?
-
Compilers are used in many different circumstances. What differences might you expect in compilers designed for the following applications?
a. A just-in-time compiler used to translate user interface code downloaded over a network
b. A compiler that targets the embedded processor used in a mobile device
c. A compiler used in an introductory programming course at a high school
d. A compiler used to build wind-tunnel simulations that run on a large cluster of identical processors
e. A compiler that targets numerically intensive programs to a large number of diverse machines
node-book_engineering-a-compiler | node-book_engineering-a-compiler_chapter-02-scanners →