Skip to content
ImagineWorld

Interprocedural Analysis

node_idnode-book_compilers-principles-techniques-and-tools_chapter-12-interprocedural-analysis
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleInterprocedural Analysis
pillar_membershipF — compiler_trinity
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph
  1. Sarkar, V. and G. Gao, “Optimization of array accesses by collective loop transformations,” Proc. 5th International Conference on Supercomputing (1991), pp. 194–205.

  2. R. Shostak, “Deciding linear inequalities by computing loop residues,” J. ACM, 28:4 (1981), pp. 769–779.

  3. Towle, R. A., Control and Data Dependence for Program Transformation, Ph.D. thesis, Department of Computer Science, University of Illinois Urbana-Champaign, 1976.

  4. Wolf, M. E. and M. S. Lam, “A data locality optimizing algorithm,” Proc. SIGPLAN 1991 Conference on Programming Language Design and Implementation, pp. 30–44.

  5. Wolfe, M. J., Techniques for Improving the Inherent Parallelism in Programs, Master’s thesis, Department of Computer Science, University of Illinois Urbana-Champaign, 1978.

Contributed by: Sorav Bansal, Indian Institute of Technology Delhi

A precise specification of the semantics (meaning) of a programming language is necessary to reason about the correctness of a program written in that language. Further, a compiler requires these language semantics to determine the legal space of transformations for a given input program. For example, consider a simple declaration statement “int x = 0” in an imperative programming language like C—we understand that this statement introduces a new integer variable “x” in the current scope; a memory region is allocated and the variable “x” refers to this memory region; this memory region is initialized with the zero value; and so on …

For the compiler developer, these semantics are necessary to be able to determine the corresponding code that needs to be generated for a declaration statement like “int x = 0”. For example, the compiler would typically emit assembly code that allocates memory region, and writes the value zero to it. The compiler would also associate location of this memory region with the variable name “x”; and generate code to this location whenever “x” is accessed. But during code generation and optimization, would a compiler know: how much memory to allocate for “x”; whether the address “x” needs to have any alignment restrictions, if “x” is allowed to be register allocated. The answers to these questions lie in the semantics of the programming language. For example, the C programming language semantics specify the minimum size of an integer object and its alignment requirements.

The semantics of a programming language are often specified as a set of rules in the natural language (e.g., English). For example, here is an excerpt from the C (C17) language standard that specifies the semantics of the C addition operator.

Example 12.1 In executing the fragment char c1, c2; /…/ c1= c1+ c2;

the “integer promotions” require that the abstract machine promotes the value of each variable to int size and then adds the two ints and truncates the sum. Provided the addition of two chars can be done without overflow, or with overflow wrapping silently to produce the correct result, the actual execution need only produce the same result, possibly omitting the promotions.

This excerpt specifies that when we add two characters(type “char”) in C, then both of them are promoted(i.e., sign extended) to the integer type before the addition, and the result is truncated back to the character type. This specification based on informal prose can often become confusing and difficult to parse. For example, while the excerpt talks about what happens in cases where overflow occurs, a precise understanding of these sentences may require the programmer to read the prior text, and is prone to misunderstand-ing. There are historical instances where the language manual’s informal specification of semantics has led to confusion and inconsistencies in the behaviour of different implementations. To avoid any ambiguities and confusion in the minds of the programmers and compiler developers, these semantic specifications need to have mathematical precision.

12.2 The Need for Specifying Programming Language Semantics

Section titled “12.2 The Need for Specifying Programming Language Semantics”

A compiler translates across multiple programming languages: the source language(e.g., C), the target language(e.g., assembly), and multiple IR(intermediate representation) languages. It is thus essential for a compiler to know a mathematically precise semantic specification for each of these languages it uses and supports.

12.2.1 A Compiler Transforms the Program Across Multiple Abstraction Levels

Section titled “12.2.1 A Compiler Transforms the Program Across Multiple Abstraction Levels”

Figure 12.1 demonstrates the gradual transformation of a program in a high-level source language to the low-level assembly language(through a series of IR languages). Each step in the transformation pipeline lowers the program from a higher-level-abstraction syntax to a lower-level-abstraction syntax, e.g., in the transformation from the Source to IR1,IR1 would typically specify the program logic using a lower-level abstraction(than Source). Figure 12.1 Language Pipeline

At any transformation step, an operation in the higher-level abstraction is typically translated into a sequence of multiple operations in the lower-level abstraction. For example, a C function call (an operation in the higher-level C syntax) is translated to a sequence of stack-push, stack-pop, and control-flow instructions (operations in the lower-level IR or assembly syntax).

12.2.2 The Need for Semantics at Each Abstraction Level

Section titled “12.2.2 The Need for Semantics at Each Abstraction Level”

Consider the following C program:

int foo(char i) { return pow (2, i) + 1; }

As the program is transformed from one language to another, its meaning must be preserved by the compiler, i.e., for identical inputs, the transformed program must produce (observable) outputs that are consistent with the outputs produced by the original program. For example, the meaning of the following IRk program (for some k) must match the meaning of the foo() C-source program shown above.

foo: i = sext i8 c to i32 ; sign-extend 8-bit “c” to 32-bit “i” push i ; push “i” on the stack push 2;pushconstant2onthestacki32r=callpow;callthepow()functiononthepushedargumer;a32−bitintegervalueisreturnedin"r"i32r2=add2 ; push constant 2 on the stack i32 r = call pow ; call the pow() function on the pushed argumer ; a 32-bit integer value is returned in "r" i32 r2 = add 1, r ; add constant 1 to r and return result to r2 return r2 ; return result in r2

By specifying the meanings of individual operations of the IRk syntax, such as “sext”, “push”, “call”, “add”, “return”, etc., we can show that the C program and the IRk program are equivalent, i.e., both programs produce identical outputs for identical inputs.

However, this raises the question: do we really need to provide the semantics for each level of abstraction? Or would it suffice to provide the semantics only for the lowest level of abstraction (i.e., the assembly language) and then specify the semantics of the higher abstraction levels by simply providing a translation for each operator in the higher-level syntax to the lower-level syntax. The problem with this latter method of providing semantics is that we limit the possible ways of translating the program from a higher-level syntax to a lower-level syntax. There is a lot of extraneous detail in the lower-level syntax, such as: what is the size of a character and an integer, what is the method of passing function call arguments, what is the direction of growth of the stack, etc. Most high-level languages permit flexibility in choosing these details at compilation time, and so if we use this method of specifying semantics, we risk overspecifying the semantics.

We are interested in specifying semantics such that they (1) capture the meaning of the program, i.e., they are correct; and (2) they are as general as possible, i.e., they provide freedom to the compiler to make implementation-level choices depending on the underlying architecture. For example, the latter requirement should allow the compiler to choose different stack layouts and growth directions depending on the target hardware architecture.

Exercise 12.2.1: Consider a programming language that provides two methods to allocate memory: (1) variable declaration, and (2) the “new” operator.

int v; // variable declaration int *n; //another variable declaration n = new int; //memory allocation through the “new” operator

One of the compilers implements a variable declaration by allocating space on the stack (in the assembly language), while the memory allocated through the “new” operator is allocated on the heap. However, another compiler may allocate both of these memory-allocation constructs on the heap.

How can the semantics of the programming language be designed so both these implementation choices are acceptable? Hint: Assume an abstract allocation function.

12.3 Formally Specifying Evaluation Rules through Inference Rules

Section titled “12.3 Formally Specifying Evaluation Rules through Inference Rules”

The semantics of a programming language are often described through evaluation rules. For example, an evaluation rule may specify that “if x evaluates to 2, and y evaluates to 3, then x + y evaluates to 5”. To formally specify such rules, we use a formal logical notation called inference rules which permit succinct and precise specification of the evaluation rules. An inference rule is usually given in the following standard form: Premise#1 Premise#2 Premise#n [name] Conclusion

This rule states that in the course of some logical derivation (or evaluation), if the given premises 1..n have been obtained, then the specified conclusion can be taken for granted as well. The “name” identifies the rule. The following inference rule, named 2-3-5 states that x + y can be assumed to be evaluated to 5 if x and y are individually evaluated to 2 and 3 respectively.

x evaluates-to 2 y evaluates-to 3 [2-3-5] x + y evaluates-to 5

Another notation for writing these inference rules is through the turnstile operator ⊥. For example, an inference rule may be specified using the ⊥ operator in a single line as:

(Premise#1), (Premise#2), …, (Premise#n) ⊥ Conclusion

This horizontal notation of the inference rule also states the same property: if the given premises 1..n have been obtained, then the specified conclusion can be taken for granted as well. These two notations of inference rules (vertical and horizontal) convey identical meanings, and can be used interchangeably. We use both horizontal and vertical notations in our ensuing discussion on inference rules.

Side note: in classical propositional logic, an inference rule could also simply be written using the implication (→) and logical-and (^) operators:

(Premise#1) ^ (Premise#2) ^ … ^ (Premise#n) → Conclusion

Exercise 12.3.1: Consider the following inference rule:

x evaluates-to C₁ y evaluates-to C₂ x+y evaluates-to C₁+C₂

Here, C₁ and C₂ represent arbitrary constants and x and y represent arbitrary expressions. Using the inference rule above, identify the evaluated value for the expression “(a+b) +c” assuming that “a”,“b”; and “c” individually evaluate to 3, 4, and 9 respectively.

12.4 Specifying Programming Language Semantics

Section titled “12.4 Specifying Programming Language Semantics”

There are multiple ways of specifying the semantics of a programming language. They are all equally precise and powerful in what they can specify, i.e., they neither under-specify nor over-specify. Yet, some ways of specifying the semantics are more suited for certain tasks than others. The three primary categorizations for the different ways of specifying programming language semantics are operational semantics, denotational semantics, and axiomatic semantics-and we discuss each of them below.

  1. Operational Semantics: The operational semantics describe the program execution via execution rules on an abstract machine. These are most useful for specifying implementations. Operational semantics can be further categorized into two types:big-step and small-step.

(a) Big-step Operational Semantics: In big-step operational semantics, the value(or effects) of an expression(or a statement) is specified in terms of its constituent expressions(or statements).

Here is an example of a big-step operational semantics rule for expression evaluation:

Context⊢e1:5Context⊢e2:7Context⊢e1+e2:12\frac{\text{Context}\vdash e_{1}:5\quad\text{Context}\vdash e_{2}:7}{\text{Context}\vdash e_{1}+e_{2}:12}

Figure 12.2 Big-step Operational Semantics

This evaluation rule in Fig. 12.2 states that:

● If under a certain “Context,” the expression “e1” evaluates to 5.

● And under the same “Context,” the expression “e2” evaluates to 7.

● Then, under the same “Context,” the expression “e1+e2” evaluates to 12.Notice that the evaluation of the expression “e1+e2” is specified in terms of the evaluation of its constituent expressions,“e1” and “e2”

(b) Small-step Operational Semantics: Small-step operational semantics specify how a single step(small step) is taken in the evaluation of a program. These are also commonly called reduction semantics, because they specify how a program is “reducing” to its value(or its effect). Here is an example of a small-step operational semantics rule for expression evaluation:

Context⊢e1→5Context⊢e1+e2→5+e2\frac{\text{Context}\vdash e_{1}\rightarrow 5}{\text{Context}\vdash e_{1}+e_{2}\rightarrow 5+e_{2}}

Figure 12.3 Small-step Operational Semantics This evaluation rule in Fig. 12.3 states that:

  • If under a certain “Context”, the expression “e₁” reduces to 5
  • Then, under the same “Context”, the expression “e₁ + e₂” reduces to “5 + e₂” Notice that unlike big-step semantics, a small-step operational semantics evaluation rule specifies a single step in the execution of the program. For example, this rule first evaluates the left-hand-side expression (of the “+” operator) before evaluating the right-hand-side. Such order of evaluation was missing in the big-step semantics rule example that we saw earlier.
  1. Denotational Semantics: The denotational semantics specify the meaning of a program as a mathematical function that specifies how an input is mapped to an output. This notation used to specify the mathematical function is usually rich enough to capture the meaning of diverse programs in that programming language. The following is an example of a semantic rule using denotational semantics.

Figure 12.4 Denotational Semantics

This denotational semantics rule in Fig. 12.4 specifies the meaning of an expression involving an assignment operation, “x = 0”. The meaning of an expression “e” is represented using “[ [e] ]”. A function is specified using the lambda operator, where λx.body represents a function that takes a single argument value, and evaluates the body on that argument by substituting “x” for the argument value. The denota semantics rule above states that, if the meaning of a variable “x” is a fun-takes as input a memory state “m”, and returns as output a tuple whose f₁ is a value (which is the address of “x” in memory, i.e., ADDRₓ) and th state itself, then the meaning of the assignment expression “x = 0” is ano-tion that also takes a memory state as input, and returns a tuple whose f₁ is the 0 value (the value that this expression evaluates to) and an updated me where the value 0 is written at ADDRₓ, denoted n[0/ADDRₓ].While denotational semantics are often elegant and quite useful for certain applications, they are often too detailed and complex; such complexity may sometimes be unnecessary for the purposes of compiler-based reasoning.

  1. Axiomatic Semantics: Axiomatic semantics define the meaning of a program through logical assertions about that program. For this reason, axiomatic semantics often form the basis of many program verification systems. Here is an example of an axiomatic semantics rule:

{x = X, y = Y, z = Z} x = 0 {x = 0, y = Y, z = Z}

Figure 12.5 Axiomatic Semantics

This axiomatic semantics rule in Fig. 12.5 is written as a hoare triple in the form “{precondition} program{postcondition}”. Here the “precondition” is a boolean-valued predicate that is assumed to be true before the execution of the “program”and “postcondition” is another boolean-valued predicate that would hold after the program finishes execution(if the “precondition” was true at the beginning of the program execution). The rule above states that if at the beginning of the execution, the variables “x”,“y”; and “z” hold arbitrary values “X”,“Y”; and “Z”; then after the execution of the program “x=0”; the new values of the “x”,“y”,“z” variables are “0”,“Y”; and “Z” respectively. This rule encodes the property that the assignment operation changes the value of variable “x” but leaves the values of the other two variables unchanged.

All the three ways of specifying semantics that we have discussed are equally general and precise in what they can be used to specify, but some are more suited for certain applications. Operational semantics(big-step or small-step) are typically used for reasoning about compiler-based transformations. We will next discuss big-step operational semantics in the context of a C/C++-like programming language.

Examples of Programming Language Semantics

Section titled “Examples of Programming Language Semantics”
  1. Consider the evaluation of a C expression “(x=0)+foo()” where “x” is a global variable and “foo” is a C function that may potentially access the memory object represented by variable “x”. The C language leaves the order of evaluation of the arguments to the “+” operator non-deterministic,i.e.,either the assignment-to-zero may execute before or after the call to function foo(). Such semantics are chosen to increase optimization opportunities.

  2. Consider the operator “map ls f” in a functional programming language that takes as input a list of elements “ls” and a function “f” and returns a new list whose elements are formed by applying the function “f” to the respective elements of the input list “ls”. The order in which the function “f” is applied to the elements of list “ls” is non-deterministic,e.g.,the middle element of the output list can be evaluated before or after the first element of the output list. This non-determinism in the semantics of the “map” operation allows the runtime to execute this operation in parallel.

  3. In some imperative languages, an uninitialized variable can non-deterministically assume any possible value(of the type of that variable).This allows a compiler to avoid having to generate initialization instructions for each variable declaration which facilitates several transformations such as register allocation.

  4. Many languages such as C/C++ involve non-deterministic semantics for error conditions such as arithmetic overflow, out-of-bounds memory accesses, etc. Such non-deterministic semantics are often based on undefined behaviour semantics, which are discussed in detail in Chapter 13. Programming Language Semantics

12.4.1 Big-Step Operational Semantics of a C/C++-like Programming Language

Section titled “12.4.1 Big-Step Operational Semantics of a C/C++-like Programming Language”

To provide a flavour of the typical semantics of a full-featured programming language, we next specify the operational semantics of a custom object-oriented imperative language that is somewhat similar to C/C++. The semantics of a full C++ language would involve several subtleties and details that may be irrelevant for our purposes of introduction to semantic specifications; hence, we use a simpler custom language and discuss its operational semantics.

To specify the big-step operational semantics, we use an evaluation judgment of the form “Ctx+ e:v”. This judgment states that in the given context “Ctx”, the expression “e” eval- uates to a value “v”. Here “e” represents an arbitrary expression tree(e.g.,“x+y”) and “v”represents a concrete value(e.g.,“7”).

The set of operational semantic rules should allow us to inductively construct such evaluation judgements. We previously saw an example of an operational semantics rule in Fig. 12.2, which allows us to construct the evaluation judgment of an expression containing the addition(+) operator(using the evaluation judgements of the two arguments of the addition operator).

When we use an evaluation judgment of the form “Ctx+ e:v”, a central question is “what information is captured in the context Ctx”. In our language, the context needs to capture at least the set of variable declarations that are active at the time of the expression eva-ation. For example, the expression “x+5” should evaluate to a value only if the relev context at the time of this evaluation contains a declaration, type, and value for the able “x”.

For example, in a particular context “Ctx1”, a variable “x” may be mapped to a val “2” and another variable “y” may be mapped to a value “3”. Thus, our operational semantics rules should be able to derive the evaluation judgment “Ctx1+ x+y:5”. On the other hand, if a different context “Ctx2” maps “x” to “20” and “y” to “30”; then we should instead be able to derive “Ctx2+ x+y:50”.

In our custom imperative programming language, the variables are mutable, i.e., their values can be changed at runtime(similar to C/C++). In other words, the variables represent memory locations, and the values at those memory locations may be read or written at runtime. Thus, to track variables with their values, we use:

  1. A Variable Environment(or just Environment) which specifies the location in memory that a variable represents. Thus, an environment keeps track of “where in memory

the variable is”. Said differently, the variable environment maps variables to locations,i.e., it keeps track of which variables are in scope and tells us where those variables are. An example state of a variable environment is “E=[x: l1, y: l2]”-here,“E” encodes the state where two variables “x” and “y” are available in the scope and they represent memory locations “l1” and “l2” respectively. Here “x” and “y” represent variable names and “l1” and “l2” represent locations in the memory store. The state of the environment at any point in the program execution is determined using the scoping rules of that language.

  1. A Memory Store(or just Store) that maps locations to their current values. Thus, the store keeps track of “what is in the memory”. An example state of a store is “S=[l1→5,l2→7,l3→9]”. If we assume that a variable “x” is mapped to location “l1” in the environment “E”, then the value of expression “x” is formed by looking up the value of “l1” in S, which is 5.

Unlike the variable environment where only those variables are mapped which are currently in scope, the memory store maps locations that may or may not be referred to by the current scope. For example, the evaluation of the expression “*x” would require lookups to two store locations at potentially distinct locations(one for “x”and another for “*x”), where the second location(“*x”) is not necessarily associated with any variable in the current scope.

To encode memory updates, a store S can be updated at a memory location “l”with a new value “v”.This is represented by a new Store S’ such that S’(l1)=12 and S’(l)=S(l) for all l≠l1. This update operation can also be expressed in shorthand as S’=S[12/l1],i.e.,S’ is “S such that l1 is updated with value 12”.

The context, used in the semantics of our language, thus needs to include both the current variable environment E and the current memory store S. Notice that the specifications of the context are kept as abstract as possible, e.g., we do not specify how a memory store is implemented, or how locations and values are represented. For example, a memory store may be represented through a byte-addressable or word-addressable memory;further, it may support up to 232 or 264 addresses; and so on… We leave these choices to the implementation environment, e.g., the compiler, OS, interpreter, hardware, etc. As discussed earlier, this abstract specification is important because it allows generality by allowing multiple implementation choices.

The semantics also need to specify the set of possible values that may be constructed during the course of a program’s execution. For example, our programming language may construct integer values (3,5,7,…),floating point values (3.0,4.5,-0.0,…),location values(l1,l2,…),etc. As we noted earlier, the semantics only specify the set of possible values

The context, used in the semantics of our language, thus needs to include both the current variable environment E and the current memory store S. Notice that the specifications of the context are kept as abstract as possible, e.g., we do not specify how a memory store is implemented, or how locations and values are represented. For example, a memory store may be represented through a byte-addressable or word-addressable memory;further, it may support up to 232 or 264 addresses; and so on… We leave these choices to the implementation environment, e.g., the compiler, OS, interpreter, hardware, etc. As discussed earlier, this abstract specification is important because it allows generality by allowing multiple implementation choices. Programming Language Semantics and do not specify their representation,e.g., depending on the implementation. a location may be represented as a single 32-bit value(e.g., to specify pointers through memory addresses) or tuples of multiple 32-bit values(e.g., to specify segments and offsets).

In addition to these simple values, our language allows the construction of object values constructed through keywords such as “struct” or “class”. For example. an object of “struct X” may be represented as “X(a1=1, a2=1,…, aN=1N)”. Here “a1”,“a2”,…,“aN” represent the fields(also called attributes) of “struct S” and “l1”,“l2”…,“lN” denote the memory store locations that the fields of this object value represent. In other words, the “a1” attribute of this object is stored at location “l1”,“a2” is stored at “l2”; and so on… Again, this definition of object values avoids specifying implementation-level details such as the object layout(i.e., the relation between the locations of different attributes), the object size, etc. This is consistent with our goal of maintaining generality and abstraction in our specification of the programming language semantics.

Further, we will use a special value called “void” in our programming language. No operations can be performed on the “void” value, and implementations are free to use any representation for the “void” value. The “void” value helps us assign semantics to expressions and statements that do not generate any usable value; we say that such expressions and statements evaluate to the “void” value. This “void”value in our programming language is similar to the “void” value in C/C++ and the “unit” value in functional programming languages like OCaml.

As discussed earlier, we use evaluation judgements of the form “Ctx+ e:v” to the big-step operational semantics of our programming language. We use two state elements to define the context “Ctx”, namely the Variable Environment “E”Memory Store “S”. Further, just like C/C++, our language allows expressions and sments to exhibit side effects, i.e., the evaluation of an expression or a statement cou cause changes to the memory state(e.g., due to an assignment or an increment operation To capture this, we revise our evaluation judgment so that an expression “e” evaluation returns not just a value but also an Updated Memory Store S’.

E,S⊢e:v, S′E,S\vdash e:v,\,S^{\prime}

This evaluation judgment in Fig. 12.6 states that:

  • Given the current variable environment “E”.

  • Given the current store “S”. If the evaluation of “e” terminates, then:

  • The new value of “e” is “v”.

  • The new store is S’.

Here, “E”, and “S” together form the context under which the expression “e” is evaluated. Notice that the value “v” and the new store S’ is the result of the evaluation if the evaluation of “e” terminates. This antecedent (that requires termination) in the meaning of the evaluation judgment is quite important—as we will see later, we allow an expression to contain loops, and thus it is possible that an expression never terminates, in which case this evaluation judgment cannot be used to identify the evaluated results.

Further, the evaluation judgment form implicitly encodes the fact that the evaluation of any expression “e” does not have any effect on the current variable environment “E”. However, as we have said earlier, the evaluation may potentially update the memory store, as captured by the new memory store S’. The side-effects on the memory, caused due to an expression evaluation, are captured in the returned store S’.

Exercise 12.4.1: Consider a programming language that implements only immutable variables. In this language, you need to initialize a variable during its declaration. Once initialized the value stored in the variable can never be changed. For example, here is a program that reads three integers and computes their sum:

int a = read_integer(); int b = read_integer(); int c = read_integer(); int d = a + b int e = d + c print e

The evaluation judgment in our custom programming language (that supports mutable variables) involves both a variable environment “E” and a memory store “S”. How would you change the evaluation judgment for this language that supports only immutable objects?

12.5 Evaluation Judgment Rules for Simple Operations

Section titled “12.5 Evaluation Judgment Rules for Simple Operations”

We now begin discussing examples of evaluation judgment rules, starting from the rules for simple operations of our custom imperative programming language. We will not exhaustively enumerate all the required evaluation judgments, but we will enumerate enough rules to provide a flavour of how these rules are specified and the associated subtleties.

12.5.1 Evaluation Judgment Rules for Constants

Section titled “12.5.1 Evaluation Judgment Rules for Constants”

Among the simplest evaluation rules are the rules for constant value expressions. We begin by providing the evaluation judgment rules for the “true” and “false” constant boolean values.

[bool-true]

E,S+true:bool(true),S

[bool-false]

E,S+false:bool(false),S

Figure 12.7 Boolean Constant Evaluation Rules

These rules simply state that under any context “E, S”, the “true” expression evaluates to the boolean value TRUE, represented as “bool(true)”. A similar rule is shown for the “false” expression. Notice that the store “S” returned by these constant expressions(on the right) is the same as the original store S(which is a part of the context on the left).This encodes the fact that the evaluation of these constant values does not involve any side-effects.

Similar rules are required for constants of other types, such as integer and float types. We show the evaluation judgment for an integer constant in Fig. 12.8.

i isanintegerliteralE,S⊢ i:int(i),S[ int]\frac{i\text{ isanintegerliteral}}{E\text{,}S\vdash\text{ i:int}(i)\text{,}S}[\text{ int}]

Figure 12.8 Integer Constant Evaluation Rule

12.5.2 Evaluation Judgment Rules for Variables

Section titled “12.5.2 Evaluation Judgment Rules for Variables”

If the variable environment “E” contains a variable identifier “x” and maps it to some location lxl_{x} , then the evaluated value of this variable is identified by looking up the memory store “S” at location “lx”. This evaluation involves no side-effects, i.e., the returned memory store is identical to the initial memory store. This is captured by the following evaluation judgment in Fig. 12.9.

E(id)=lidS(lid)=vE,S⊢id:v,S[id]\frac{E\left( id\right)=l_{id}\quad S\left(l_{id}\right)=v}{E\text{,}S\vdash id\text{:}v\text{,}S}\left[id\right]

Figure 12.9 Variable Evaluation Rule

In this evaluation rule in Fig. 12.9,“id” represents an arbitrary variable identifier(e.g.,“x”). This judgment states that:

  • If the Variable Environment “E” maps the variable identifier “id” to a location “l id”
  • If the Memory Store “S” maps the location “l id” to a value “v”
  • Then, under the context of any variable environment “E”(which maps “id” to “l id”),and memory store “S”(which maps “l id” to “v”), the evaluation of “id” returns the value “v” and an unmodified store “S”(if the evaluation terminates).

Notice that the value “v” could either be a simple value(e.g., integer, float, pointer etc.) or an object value(an object of a user-defined type,e.g.,struct/class).The evaluation of a variable identifier into a constant value does not modify the memory store in any way,i.e., the resulting memory store “S” is identical to the original memory store that was a part of the evaluation context. As we have discussed previously, these evaluation rules preserve generality by not specifying the representation of the location(l id), the value(v), the store(S),etc.

We emphasize the antecedent again: the evaluation judgment encodes the return value and the returned store only if the evaluation terminates. While this will be a constant feature of all our evaluation rules, we will omit the antecedent in the future discussion unless it is relevant(e.g., when we discuss the evaluation of loop operations). Even though we omit to discuss this important antecedent in the future(for brevity),it remains an important and critical part of the evaluation judgment and we will revisit it again when we discuss loop operations such as the while-loop.

12.5.3 Evaluation Judgment Rule for the Assignment Operator

Section titled “12.5.3 Evaluation Judgment Rule for the Assignment Operator”

The assignment operator constructs an expression in our language(just like it does in C/C++). The evaluation of the assignment operation returns a value(the value that was assigned) and also involves a side-effect(update to the memory store at the address specified by the LHS of the assignment operation). The exact semantics of the assignment operation in our language are captured by the following evaluation judgment.

E,S⊢e:v,S1E(id)=lidS2=S1[v/lid]E,S⊢id:=e:v,S2\begin{array}{c}{ E,S\vdash e:v,S_{1}}\\{ E(id)=l_{id}}\\{S_{2}=S_{1}[v/l_{id}]}\\{E,S\vdash id:=e:v,S_{2}}\\\end{array}

[assignment]

Figure 12.10 Assignment Evaluation Rule

The evaluation judgment in Fig. 12.10 states that:

  • If under an arbitrary context “E, S”, an expression “e” evaluates to a value “v” and a store S1.

  • If the variable identifier “id” is mapped to a location “l id” in the Variable Environment “E”. Programming Language Semantics

  • And if S2 represents a memory store such that it is identical to S1 except at the location “1id”(where it is updated with the value “v”).

  • Then, under the same environment “E,S”; the assignment expression “id:=e” eval- uates to the value “v”(the value to which “e” evaluated”) and also returns the store S2(which contains the updated mapping for “1id” to “v”).

It is important to note that the store “S2” is obtained by updating “S1”; and “S1” in turn is obtained from the evaluation of “e”(recall that “e” could have had its own side-effects).This encoding has subtle ramifications:it ensures that the expression “e” must be evaluated(and its side-effects applied) before the application of the side effect of the assignment operation itself. For example, consider the expression “x:=y:=3” that evaluates to the value “3” while causing side-effecting writes to the variables “x” and “y”; the semantic rule shown above ensures that the side-effect due to “y:=3” is applied before the side-effect due to “x:=…” In this example, this order of application of side-effects may not matter if “x” and “y” represent distinct locations but consider the following example instead.

In the evaluation of “*x:=y:=V”; consider the case where “x” and “y” represent the same memory store location. In this case, our evaluation rule specifies that first “y” is updated with value “V” and then “*x” is evaluated. Thus,“*x” would evaluate to “*V” in the case where “x” and “y” refer to the same memory location. On the other hand, if the evaluation order enforced that the address of “*x” was evaluated before the evaluation of “y:=V”; the result would be different.

Such subtleties are easy to overlook in an informal exposition of the program language semantics, but are captured with mathematical precision by this formal n

12.5.4 Evaluation Judgment Rule for Binary Operations

Section titled “12.5.4 Evaluation Judgment Rule for Binary Operations”

Binary operations include arithmetic operations(add, subtract, multiply, etc.) operations(and, or,…), bit-shift operations, etc. We use “+” as a generic placeholder represent any of these binary operations, both in the programming language syntax and in the corresponding semantics. We show the evaluation judgment for the specification of the operational semantics for the binary operator below.

E,S⊢e1:v1,S1E,S1⊢e2:v2,S2E,S⊢e1+e2:v1+v2,S2[add]\begin{array}{c}{ E,S\vdash e_{1}:v_{1},S_{1}}\\ {E,S_{1}\vdash e_{2}:v_{2},S_{2}}\\ {\frac{E,S\vdash e_{1}+e_{2}:v_{1}+v_{2},S_{2}}{[add]}}\\\end{array}

Figure 12.11 Binary operations semantics

This evaluation rule in Fig. 12.11 states:

  • If under an arbitrary context “E,S”; an arbitrary expression e1e_{1} evaluates to value v1v_{1}and store S1S_{1} .

  • If under the context “E,S1,” another arbitrary expression e2 evaluates to value v2 and store S2.

  • Then, under the original context “E, S,” the evaluation of “e1+ e2” yields the value v1+v2 and store S2.

Notice again that the evaluation of expression “e2” is performed in the context of the updated store S1(which is obtained after evaluating the expression “e1”). Thus, this rule encodes the fact that the expression “e1” is evaluated first(including its side-effects),and then the expression “e2” is evaluated in the context of the updated store(yielded by “e1”‘s evaluation). This is also called the left-to-right evaluation order.

To see why the evaluation order is consequential, consider the evaluation of the expression((x=3)+(*y=4)), and consider a context where E={ x→l1,y→l2} and a store S={l1 ⁣:…,l2 ⁣:l1} \{l_{1}\colon\ldots,l_{2}\colon l_{1}\}\,-notice that in this case, both “x” and “*y” evaluate to the same location value “l1.” In this example, the left-to-right evaluation order ensures that the final value at location “l1”(in the returned memory store) is “4”. On the other hand, if the evaluation order was right-to-left, then the final value at location “l1” would have been “3”.

The “+” operator in this discussion represents any arithmetic/logical/bit-shift binary operator. Similar semantics can also be constructed for unary operations, such as negation, logical-not, etc. Unlike binary operations, unary operations do not involve any order-of-evaluation subtleties.

12.5.5 Evaluation Judgment Rule for the Sequencing Operator

Section titled “12.5.5 Evaluation Judgment Rule for the Sequencing Operator”

The sequence operator(e.g., semicolon in C/C++) is commonly used in imperative programming languages to encode a sequence of expressions(or statements). For example,“e1;e2” represents a program where the expression “e1” is evaluated before evaluating “e2”-in other words,“e1” is sequenced before “e2.”

E,S⊢e1:v1,S1E,S\vdash e_{1}:v_{1},S_{1} E,S1⊢e2:v2,S2E,S⊢e1;e2:v2,S2[sequence]\frac{E,S_{1}\vdash e_{2}:v_{2},S_{2}}{E,S\vdash e_{1};e_{2}:v_{2},S_{2}}\text{[sequence]}

Figure 12.12 Sequence Operations Evaluation Rule

The evaluation judgment for the semicolon sequencing operator(shown in Fig. 12.12)states:

  • If under an arbitrary context “E, S,” an arbitrary expression “e1” evaluates to value “v1” and stores “S1”

  • And if under the context “E,S1”(where “S1” is the store returned after the evaluation of “e1”), another arbitrary expression “e2” evaluates to value “v2” and store “S2”

Programming Language Semantics 915

· Then, under the original context “E, S”, the expression(or statement) formed by sequencing the two expressions “e1; e2” evaluates to the value “v2”(the value yielded by the second expression “e2”) and the memory store “S2.”

Notice that the semantics of our custom language evaluate the sequenced expression to both a returned value(“v2”) and a memory store(“S2”). In other languages like C/C++,such sequences of expressions are deemed to evaluate to only the “void” value(and not the value returned by the last expression in the sequence). This can be easily modeled by modifying the evaluation judgment such that “e1; e2” returns “void,S2”(instead of “v2.S2”) in the conclusion of the inference rule shown above.

12.5.6 Evaluation Judgment Rule for the Block Operator

Section titled “12.5.6 Evaluation Judgment Rule for the Block Operator”

Programming languages support the creation of a new block(scope) of statements(or expressions). We use the curly braces to demarcate a new block(or scope) of expressions.

E,S⊢e:v,S1E,S⊢{e}:v,S1[block]\begin{align*}\frac{E,S\vdash e:v,S_{1}}{E,S\vdash\{e\}:v,S_{1}}[block]\end{align*}

Figure 12.13 Expression Block Evaluation Rule

The evaluation statement states that if under an arbitrary context “E, S”, an arbitrary expression “e” evaluates to value “v” and stores “S1,”then the same expression is enclosed in a new block(using “{” and “}”) also evaluates to the same value “v” and stor “S1.”We will later use this block operator to also support variable declarations.

Consider the example expression{x:=7+5;4;}We are interested in applying the ev uation rules we have learned so far. Let’s assume that this expression is evaluated unde context “E, S”; where the variable environment E={…,x:l,x,…},and the memory store S={…,l,0,…}(i.e., the variable environment maps the variable “x” to the location “l”and the memory store maps the location “l”to the value “0”).

E,S⊢{X:=7+5;4}:?,?E,S\vdash\{X:=7+5;4\}:?,?

Figure 12.14 Expression Block Evaluation Example

The first step in the evaluation of this expression involves the application of the “block”evaluation rule.

X:7+5;4:v1,S1E,S⊢{X:7+5,4}:v1,S1[block]\begin{align*}\frac{X:7+5;4:v_{1},S_{1}}{E,S\vdash\{X:7+5,4\}:v_{1},S_{1}}\left[block\right]\end{align*}

The next step involves the application of the “sequence” evaluation rule

E, S X := 7 + 5 : v2, S2 E, S2 X := 4 : v1, S1 [sequence] E, S X := 7 + 5 : v2, S2 E, S2 X := 4 : v1, S1 [block] E, S X := 7 + 5 : 4 : v1, S1 E, S X := {X := 7 + 5; 4} : v1, S1

The next step involves applying the addition rule to the first part of the sequence antecedents.

E, S X := 7 + 5 : v2, S E [X] = lx S2 = S [v2/lx] [assignment] E, S X := 7 + 5 : v2, S2 E, S2 X := 4 : v1, S1 [const] [sequence] E, S X := 7 + 5 : 4 : v1, S1 [block] E, S X := {X := 7 + 5; 4} : v1, S1

Exercises for Section 12.5 Exercise 12.5.1: Using the evaluation rules described so far, show the evaluation of the expression “X := Y := Z + 4” under the context “E,S” where “E = {…, X → lX, Y → lY, Z → lZ, … }” and “S = {…, lX → 3, lY → 4, lZ → 9, … }”. Exercise 12.5.2: Change the “[add]” evaluation rule so that it enforces a right-to-left evaluation order (instead of the current left-to-right evaluation order).

12.6 Evaluation Judgment Rules for Control Flow So far, we have discussed the evaluation rules for expressions formed by unary, binary, assignment, and sequence operations. We now discuss control-flow constructs, of which a canonical example is the “if-then-else” construct. Programming Language Semantics

12.6.1 Evaluation Judgment Rules for If-Then-Else

Section titled “12.6.1 Evaluation Judgment Rules for If-Then-Else”

E,S if e1 then e2 else e3:?,?

Figure 12.15 If-Then-Else Evaluation Rule Template

Under an arbitrary evaluation context,“E,S”,we are interested in identifying the returned value and memory store for the “if e1 then e2 else e3” expression, for arbitrary expressions “e1”,“e2”,and “e3”. In our custom programming language, we assume that the scalar value returned by the evaluation of an if-then-else construct is always “void”,i.e..it cannot be used further in any operation. Thus, the primary remaining unknown is the returned memory store.

E,S if e1 then e2 else e3: void,?

Figure 12.16 If-Then-Else Evaluation Rule Value Is Void

As we have been doing previously, we will inductively specify the returned values based on the values evaluated for the expressions for “e1”,“e2”,and “e3” under their respective evaluation contexts. Informally, the evaluation of this if-then-else expression should first involve the evaluation of “e1”; and depending on the returned value for “e1”(true or false),one of “e2” or “e3” should be evaluated. We formally encode this through two separate inference rules for evaluation, one for each case,i.e.,“e1” evaluating to true false.

E,S if e1 then e2 else e3: void, S2[ite-true]

Figure 12.17 If-Then-Else True Evaluation Rule

The first case specifies the evaluated result when “e1” evaluates to value true and store “S1”(under the evaluation context “E,S”). Because “e1” evaluates to true, we will next evaluate the “then” clause expression,i.e.,“e2” under the returned store “S1”. If “e2” thus evaluates to an arbitrary return value “v” and store “S2”,then the entire if-then-else expression returns the value “void” and store “S2”. Notice that the memory store “S2” returned by the if-then-else expression is identical to the memory store returned by the evaluation of the expression “e2”(under the context “E,S1”). Also, notice that the returned value “v”, obtained by evaluating “e2”,is ignored; instead, the “void” value is returned by the if-then-else operation.

A similar evaluation rule is used for the case when “e1” evaluates to false, in which case “e3” is evaluated instead of “e2”(shown in Fig. 12.18).

E, S⊢e1:bool(false), S1[ite−false]E, S1⊢e3:v, S2E, S⊢if e1 then e2 else e3:void, S2\begin{array}{c}{\frac{E,\,S\vdash e_{1}:bool(false),\,S_{1}}{[ite-false]}}\\{\frac{E,\,S_{1}\vdash e_{3}:v,\,S_{2}}{E,\,S\vdash if\,e_{1}\,then\,e_{2}\,else\,e_{3}:void,\,S_{2}}}\end{array}

Figure 12.18 If-Then-Else False Evaluation Rule

In both rules, the order of evaluation involves evaluating “e1” before evaluating either the then-clause or the else-clause: this is captured by using the memory store S1 in the evaluation context of “e2” and “e3” respectively.

12.6.2 Evaluation Judgment Rules for the Ternary Operator

Section titled “12.6.2 Evaluation Judgment Rules for the Ternary Operator”

Languages like C/C++ also support an operation of the form “a?b:c”,which is also called the ternary operator. If “a” evaluates to “true”,then this expression evaluates to “b”;else it evaluates to “c”.The ternary operator is very similar to if-then-else with an important difference: unlike if-then-else, the ternary operation also returns a non-void scalar value(which could be either “b” or “c”). As such, the semantics of the ternary operator provide a nice contrast to the semantics of the if-then-else operation. We again use two different evaluation rules to specify the semantics of the ternary operator.

E, S⊢e1:bool(true), S1E, S⊢e1 ? e2:e3:v, S2 [ternary−true]\begin{array}{l}{\frac{E,\,S\vdash e_{1}:bool(true),\,S_{1}}{E,\,S\vdash e_{1}\,?\,e_{2}:e_{3}:v,\,S_{2}}\,[ternary-true]}\\ \end{array}

Figure 12.19 Ternary Operator True Evaluation Rule

The evaluation rule states:

  • If under an arbitrary evaluation context “E,S”,the expression “e1” evaluates to the boolean value “true” and a memory store “S1.”

  • If under the evaluation context “E,S1”,the expression “e2” evaluates to a value “v”and stores “S2.”

  • Then, the expression “e1?e2:e3” evaluates to the value “v” and memory store “S2.”

A similar rule for ternary-false is shown below.

E, S⊢e1:bool(false), S1E, S⊢e1 ? e2:e3:v, S2\begin{array}{c}{\frac{E,\,S\vdash e_{1}:bool(false),\,S_{1}}{E,\,S\vdash e_{1}\,?\,e_{2}:e_{3}:v,\,S_{2}}}\\ \end{array}

Figure 12.20 Ternary Operator False Evaluation Rule The primary difference between the “ite-true” (“ite-false”) and the “ternary-true” (“ternary-false”) rules is that the ternary-true rule also returns the scalar value “v” for the ternary operation (unlike the if-then-else operation that always returns the “void” value). This scalar return value is the same as the value returned by the selected expression (“e₂” or “e₃”) depending on the boolean value evaluated for the expression “e₁”.

12.6.3 Evaluation Judgment Rules for the While Loop

Section titled “12.6.3 Evaluation Judgment Rules for the While Loop”

E, S→e₁ : bool(false), S₁ [while-false] E, S→ while (e₁) {e₂} : void, S₁

Figure 12.21 While False Evaluation Rule

The while loop involves two expressions: the loop condition (“e₁” in the evaluation rule shown in Fig. 12.21) and the loop body (“e₂” in the evaluation rule). The loop condition expression “e₁” evaluates to a boolean value depending on which, the abstract machine decides whether to execute another iteration of the loop body or not. The final return value of the while-loop expression involves the “void” value (the scalar value returned by “e₂” is ignored) and an updated memory store.

We specify the operational semantics of the while-loop construct using two different evaluation rules for the two distinct cases: (case 1) when the loop condition evaluates the “false” value under the current evaluation context; (case 2) when the loop condition evaluates to the “true” value under the current evaluation context.

The evaluation rule shown in Fig. 12.21 tackles the first case when the loop condition evaluates to “false”. If under an arbitrary evaluation context “E, S”, the expression “e₁” evaluates to a boolean scalar value “false” and a memory store “S₁”, then the expression “while (e₁) {e₂ }” evaluates to the “void” scalar value and the memory store “S₁”. This ensures that the side-effects due to the evaluation of the “e₁” expression are reflected in the final result, but the expression “e₂” is not evaluated in this situation.

The other case involves the situation where, under an arbitrary evaluation context “E, S”, the loop condition evaluates to the boolean condition “true” (and some memory store “S₁”), as shown in Fig. 12.22.

E, S→e₁ : bool(true), S₁ [while-true] E, S→ while (e₁) {e₂} : void, ?

Figure 12.22 While True Evaluation Rule (Partial1)

In this situation, after evaluating “e₁”, we will need to evaluate the loop body “e₂” under “S₁”, shown in Fig. 12.23.

E, S⊢e1:bool(true), S1E, S1⊢e2:v, S2E, S⊢while(e1) {e2}:void, ?[while-true]\begin{array}{l}\text{E, S}\vdash e_{1}:\text{bool}(\text{true}),\,\text{S}_{1}\\ \frac{\text{E, S}_{1}\vdash e_{2}:\text{v, S}_{2}}{\text{E, S}\vdash\text{while}(e_{1})\,\{e_{2}\}:\text{void},\,\text{?}}\quad[\text{while-true}]\\ \end{array}

Figure 12.23 While True Evaluation Rule(Partial2)

Subsequently, we need to again evaluate “e1”(under the memory store S2 returned by evaluating “e2”), and so on… The other way to say this is that if “e1” evaluates to “true”; then we evaluate “e2” and then evaluate the while-loop expression again, albeit under a potentially updated memory store S2.

\begin{array}{c}{\text{E, S}\vdash e_{1}:\text{bool}(\text{true}),\text{S}_{1}}\\ {\text{E, S}_{1}\vdash e_{2}:\text{v, S}_{2}}\\ \frac{\text{E, S}_{2}\vdash\text{while}(e_{1})\,\{e_{2}\}:\text{void, S}_{3}}{\text{E, S}\vdash\text{while}(e_{1})\,\{e_{2}\}:\text{void, S}_{3}}\quad[\text{while-true}]}\\ \end{array}

Figure 12.24 While True Evaluation Rule(Full)

The full evaluation rule, shown in Fig. 12.24, states:

  • If under an arbitrary evaluation context “E,S”, the expression “e1” evaluates to the boolean value “true” and a memory store “S1”

  • If under the evaluation context “E,S1,”the expression “e2” evaluates to some value “v” and a memory store “S2”

  • If under the evaluation context “E,S2,” the full while-loop expression “while(e1){e2}” evaluates to the “void” value, and a memory store “S3”(if the evaluation terminates)

  • Then, under the original evaluation context “E, S”, the while-loop expression “while(e1){e2}” evaluates to the “void” value, and the memory store “S3”(if the evaluation terminates).

Notice that this evaluation judgment rule is recursive, in the sense that the evaluation of the while-loop expression involves recursively evaluating the same while-loop in a different context. If this sequence of contexts is not carefully orchestrated to eventually cause the loop condition to evaluate to “false”; we may end up with infinite recursion. Thus, the antecedent of our evaluation judgment, i.e.,“if the evaluation terminates”; becomes particularly relevant in the while-loop evaluation rule-we define the semantics of the while-loop only if the evaluation terminates. In other words, we do not define the semantics for a while-loop expression if its evaluation does not terminate.

We emphasize again that even though we have been conveniently omitting to mention the antecedent,“if the evaluation terminates”; in many of our evaluation judgment rules(for brevity),it remains an important part of the semantics. For example, when we discuss the if-then-else rule, it is possible that the loop condition involves an expression that does Programming Language Semantics not terminate; in which case, our big-step operational semantics do not specify the meanings of such programs.

For example, a program like “while(x){y:=…}” may never terminate(where “x” and “y” are distinct variables), and thus its meaning is unspecified in our big-step operational semantics. What does it mean for a program to not have a meaning? This often implies that such programs, whose meaning is not available, are illegal programs: in other words.such programs must never be executed and so the onus of ensuring this rests with the programmer. We discuss such situations in more detail in our discussion on “Undefined Behaviour” in Chapter 13.

Exercise 12.6.1: Consider the expression “if((x:=3)==y){z:=x+y} else{z:=y}”. Evaluate this expression under the context “E,S”; where “E={…,x lx,y↦ly,z↦lz,…}l_{x},y\mapsto l_{y},z\mapsto l_{z},\ldots\} “and “S={...,lx↦0,ly↦3,lz↦4,...}\{...,l_{x}\mapsto 0,l_{y}\mapsto 3,l_{z}\mapsto 4,...\}”?

Exercise 12.6.2: Consider the expression “while(x>0){y:=y+x;x:=x-1}”. Evaluate this expression under the context “E,S” where “E={…,x lx,y↦lyl_{x},y\mapsto l_{y} ,…}” and “S={…,lx→3,ly→0,…}”?

Exercise 12.6.3: What happens if we evaluate the expression in Exercise 12.6.2 unu different context “E, S” where “E={…,x lx,y↦lyl_{x},y\mapsto l_{y} ,…}” and “S’={,…,lx l, ly↦0,...}l_{y}\mapsto 0,...\}”?

12.7 Evaluation Judgment Rules for Variable Declarations

Section titled “12.7 Evaluation Judgment Rules for Variable Declarations”
E,S⊢{T id=e1;e2}:?,?E,S\vdash\{T\,id=e_{1};e_{2}\}:?,?

Figure 12.25 Variable Declarations Evaluation Rule(Incomplete1)

So far, in all our evaluation judgment rules, the variable environment “E”, which maps variable names to locations, has not changed. The variable environment “E” can be updated through variable declarations. In our language, a declaration can be specified at the beginning of a new scope-as shown in the incomplete evaluation rule in Fig. 12.25, the declaration involves specifying the type of the variable(“T”), the name of the variable(“id”),and the initial value assigned to this variable(which in this case is the value evaluated through the expression “e1”). Further, the scope’s body is represented by the expression “e2”-this expression “e2” must be evaluated in an updated variable environment “E”(in which the newly declared variable “id” is mapped to a newly allocated location, say “lnew”)and an updated memory store “S”(in which the location “lnew” is mapped to the value evaluated for expression “e1”).

The scope itself is demarcated using curly-braces. We are interested in identifying the scalar value and the updated memory store returned by this scope-expression upon evaluation. Needless to say, these returned values will depend on the values evaluated for “e1”and “e2”in their respective contexts.

We are interested in evaluating the scope expression under an arbitrary evaluation context “E,S”. The first step involves the evaluation of the expression “e1” under the input context “E,S” as shown below:

E, S⊢e1:v1,S1?,?⊢e2:v2,S2E, S⊢{T id=e1;e2}:v2,S2\begin{array}{l}\text{E, S}\vdash e_{1}:v_{1},S_{1}\\ \text{?,?}\vdash e_{2}:v_{2},S_{2}\\ \text{E, S}\vdash\{T\text{ id}=e_{1};e_{2}\}:v_{2},S_{2}\end{array}

Figure 12.25 Variable Declarations Evaluation Rule(Incomplete2)

The second step involves evaluating the expression “e2”- however, the evaluation context of “e2” will be different from the input evaluation context; it needs to reflect the updates caused due to the variable declaration “T id=e1”. In the evaluation rule shown above, we have not yet shown this updated evaluation context used for evaluating “e2” and we will discuss this next. But the incomplete evaluation rule is shown above in Figure 12.25 already specifies that if “e2” evaluates to “v2,S2”(under the updated context), then the returned values for the full scope-expression are also “v2,S2”

Now, let’s come back to the evaluation context for the expression “e2”. The variable environment “E” of this evaluation context must now contain a mapping from “id” to its newly-allocated location “lnew”. If “E” already had a mapping for “id”(to some other location), then that mapping needs to be overwritten with this new mapping “id→lnew”. Further, the store “S” in the evaluation context should reflect the allocation of the new location “lnew” and its new contents “v1”(as evaluated for expression “e1”)- in addition to any side-effects that may have been caused due to the evaluation of “e1”itself. Thus “e2”‘s evaluation context must have a variable environment like the input environment “E”, except that it has the extra mapping “id→lnew” and a memory store like the “S1”store(as returned by “e1”‘s evaluation) except that it has the extra mapping “lnew→v1.”

To encode the property that “lnew” must be a newly allocated location, i.e., a location that does not already exist in the current store(say “S”), we write “lnew= newloc(S)”. Here “newloc” returns a location that is not already mapped in “S”, and can be thought of as the memory-allocation function.

E, S⊢e1:v1,S1lnew=newloc (S1)E,[lnew/id],S1[v1/lnew]⊢e2:v2,S2E, S⊢{T id=e1;e2}:v2,S2[Decl]\begin{array}{c}{\text{E, S}\vdash e_{1}:v_{1},S_{1}}\\ {l_{\text{new}}=newloc\,(S_{1})}\\ {\frac{\text{E,}[l_{\text{new}}/id],S_{1}[v_{1}/l_{\text{new}}]\vdash e_{2}:v_{2},S_{2}}{\text{E, S}\vdash\{T\text{ id}=e_{1};e_{2}\}:v_{2},S_{2}}\quad[Decl]}\\ \end{array}

Programming Language Semantics

The final evaluation rule states:

  • If under an arbitrary evaluation context “E,S”; the expression “e1” evaluates to value “v1” and memory store “S1”

  • If “lnew” is a newly allocated location in store “S1”

  • If under an evaluation context formed by “E[lnew/id]”(“E” where “lnew” is mapped to “id”) and under a memory store “S1[v1/lnew]”(“S1” where “lnew” maps to value “v1”), the expression “e2” evaluates to value “v2” and store “S2”

  • Then under the original input evaluation context “E,S”; the scope-expression “{T id=e1;e2}” evaluates to value “v2” and stores “S2”.

Notice that all semantics have been deliberately kept as abstract as possible. For example, we have abstracted memory allocation through the “newloc” function without specifying, for example, any distinction between stack memory and heap memory. This allows the compiler/interpreter more freedom to choose the optimal implementation for their purposes.

Exercise 12.7.1: Show the evaluation tree for the expression “{int x=3;{int y:=x+4 r:=y+2;}” In particular, show the different variable environments “E” and the memory stores “S” that are used to evaluate the subexpressions of this expression.

Exercise 12.7.2: Show the evaluation tree for the expression “{int x=3;{int x:=x+ r:=y+2;}” In particular, show the different variable environments “E” and the memor stores “S” that are used to evaluate the subexpressions of this expression.

● Semantics for Source Programming Language: The source programming language semantics should be precise enough to allow the programmer to reason about the correctness of a program. Yet they should be abstract enough to allow multiple implementation choices for the compiler, interpreter, and hardware.

● Semantics for Intermediate Representations(IR): All IR languages should have well-defined semantics. Similarly, the assembly language must have well-defined semantics. At any stage of translation in the compiler pipeline, we should be able to show that the translated program’s behaviours(based on the target language semantics) are a subset of the source program’s behaviours(based on the source language semantics).

Inference Rules: Inference Rules provide a succinct and precise method for specifying logical deductions. Inference rules can be written vertically or horizontally. Methods of Specifying Programming Language Semantics: There are multiple ways of specifying programming language semantics. A broad categorization of different ways of specifying programming language semantics is: (1) Big-Step and Small-Step Operational Semantics, (2) Denotational Semantics, (3) Axiomatic Semantics. Evaluation Judgements for an Imperative Programming Language: The evaluation judgment for an imperative programming language specifies the effect of an operation under an evaluation context – for a language that supports mutability, this context includes the variable environment (variables declared in the scope) and the memory store (state of the memory). Only a minimal amount of detail is specified in these evaluation judgments such that they are precise enough for understanding the meaning of a program, and yet general enough to allow the compiler to choose among multiple possible implementations. The evaluation judgment may involve special antecedents, such as those relating to termination. Order of Evaluation: The evaluation judgment rules often encode the order of evaluation of the operands of an operator by carefully orchestrating the context of evaluation of each operand. Evaluation of a Program: The evaluation of a program involves invoking the evaluation rules that apply, one after another, until the program terminates. Loop Evaluation: Evaluation of looping operations may involve evaluation of the same program again, albeit under a different context. This can potentially cause non-termination of program execution. Variable Declarations Update the Variable Environments: The variable environment is updated on entering and exiting a scope with a variable declaration.

Programming language semantics may be specified using pen-and-paper exposition (as also done in this book) [1,2], or using special computer software tools meant for the easy codification of such semantics [3]. While most language manuals specify the meanings of different operators in a natural language like English [4,5], there is an increasing trend to specify these meanings in formal notation to improve precision [6]. Such formal notation also aids the development of verification tools [7].

There are multiple ways of specifying semantics, such as Operational Semantics [6], Denotational Semantics [8], Axiomatic Semantics [9], Action Semantics [10], Algebraic Semantics [11], Attribute Grammars [12], Categorical (or Functorial) Semantics [13], Concurrency Semantics [14], Game Semantics [15], Predicate Transformer Semantics [16], etc. The right choice of semantics depends on both the programming language and the application for which the semantics are being used. Non-determinism in programming language semantics is common. For example, Michael Norrish [6] provided a small-step operational semantics for the C programming language that modeled the non-deterministic order of evaluation of operands for C operators. Such non-determinism is often useful for optimization [17].

  1. Joseph A. Goguen (1975), “Semantics of computation, Category Theory Applied to Computation and Control”, Lecture Notes in Computer Science (Springer), 25:151-163. doi:10.1007/3-540-07142-3_75. ISBN 978-3-540-07142-6.

  2. Hennessy, M. (1990), The semantics of programming languages: an elementary introduction using structural operational semantics (Wiley). ISBN 978-0-471-92772-3.

  3. Grigore Rosu, and Traian Florin Serbanuta (2010), “An overview of the K semantic framework”, The Journal of Logic and Algebraic Programming, 79(6): 397-434. ISSN 1567-8326, https://doi.org/10.1016/j.jlap.2010.03.012.

  4. C Reference Manual. ISO/IEC 9899:2018. https://www.iso.org/standard/74528.html

  5. Standard for Programming Language C++. https://isocpp.org/std/the-standard

  6. Michael Norrish (1997), An abstract dynamic semantics for C, Computer Systems Lab, University of Cambridge Technical Report.

  7. Xavier Leroy (2009), “Formal verification of a realistic compiler”, Communications of the ACM, 52(7):107-115. DOI:https://doi.org/10.1145/1538788.1538814

  8. David A. Schmidt (1986), Denotational Semantics: A Methodology for Language Development (William C. Brown Publishers). ISBN 9780205104505.

  9. Joseph A. Goguen, James W. Thatcher, Eric G. Wagner, and Jesse B. Wright (1978) “Initial algebra semantics and continuous algebras”, Journal of the ACM, 24(1): 68-95. doi:10.1145/321992.321997. S2CID 11060837.

  10. Peter D. Mosses (1996), “Theory and practice of action semantics”, BRICS Report RS9653. Aarhus University.

  11. Pierre Deransart, Martin Jourdan, and Bernard Lorho (1988), “Attribute Grammars: Definitions, Systems and Bibliography”, Lecture Notes in Computer Science 323 (Springer-Verlag). ISBN 9780387500560.

  12. Pierre Deransart, Martin Jourdan, and Bernard Lorho (1988), “Attribute Grammars: Definitions, Systems and Bibliography”, Lecture Notes in Computer Science 323 (Springer-Verlag). ISBN 9780387500560.

  13. F.William Lawvere (1963), “Functorial semantics of algebraic theories”, Proceedings of the National Academy of Sciences of the United States of America, 50 (5): 869-872. doi:10.1073/pnas.50.5.869. PMC 221940. PMID 16591125.

  14. Mark Batty, Kayvan Memarian, Kyndylan Nienhuis, Jean Pichon-Pharabod, and Peter Sewell (2015), “The problem of programming language concurrency semantics”, Proceedings of the European Symposium on Programming Languages and Systems (Springer), pp. 283-307. doi:10.1007/978-3-662-46669-8_12.

Inference Rules: Inference Rules provide a succinct and precise method for specifying logical deductions. Inference rules can be written vertically or horizontally.

Methods of Specifying Programming Language Semantics: There are multiple ways of specifying programming language semantics. A broad categorization of different ways of specifying programming language semantics is: (1) Big-Step and Small-Step Operational Semantics, (2) Denotational Semantics, (3) Axiomatic Semantics.

Evaluation Judgements for an Imperative Programming Language: The evaluation judgment for an imperative programming language specifies the effect of an operation under an evaluation context - for a language that supports mutability, this context includes the variable environment (variables declared in the scope) and the memory store (state of the memory). Only a minimal amount of detail is specified in these evaluation judgments such that they are precise enough for understanding the meaning of a program, and yet general enough to allow the compiler to choose among multiple possible implementations. The evaluation judgment may involve special antecedents, such as those relating to termination.

Order of Evaluation: The evaluation judgment rules often encode the order of evaluation of the operands of an operator by carefully orchestrating the context of evaluation of each operand.

Evaluation of a Program: The evaluation of a program involves invoking the evaluation rules that apply, one after another, until the program terminates.

Loop Evaluation: Evaluation of looping operations may involve evaluation of the same program again, albeit under a different context. This can potentially cause non-termination of program execution.

Variable Declarations Update the Variable Environments: The variable environment is updated on entering and exiting a scope with a variable declaration.

Programming language semantics may be specified using pen-and-paper exposition (as also done in this book) [1,2], or using special computer software tools meant for the easy codification of such semantics [3]. While most language manuals specify the meanings of different operators in a natural language like English [4,5], there is an increasing trend to specify these meanings in formal notation to improve precision [6]. Such formal notation also aids the development of verification tools [7].

There are multiple ways of specifying semantics, such as Operational Semantics [6], Denotational Semantics [8], Axiomatic Semantics [9], Action Semantics [10], Algebraic Semantics [11], Attribute Grammars [12], Categorical (or Functorial) Semantics [13], Concurrency Semantics [14], Game Semantics [15], Predicate Transformer Semantics [16], etc. The right choice of semantics depends on both the programming language and the application for which the semantics are being used. Non-determinism in programming language semantics is common. For example, Michael Norrish [6] provided a small-step operational semantics for the C program language that modeled the non-deterministic order of evaluation of operands for C operations. Such non-determinism is often useful for optimization [17].

  1. Joseph A. Goguen (1975), “Semantics of computation category Computation and Control”, Lecture Notes in Computer Science, 163. doi:10.1007/3-540-07142-3_75. ISBN 978-3-540-061-84.

  2. Hennessy, M. (1990), The semantics of program execution using structural operational semantics.

  3. Grigore Roşu, and Traian Florin Şerbănutătic framework”, The Journal of Logic and Algebra, 79(6): 397–434. ISSN 1567-8326, https://doi.org/10.1016/j.jlap.2010.03.012.

  4. C Reference Manual. ISO/IEC 9899:2018. https://www.iso.org/standard/74528.html

  5. Standard for Programming Language C++. https://isocpp.org/std/the-standard

  6. Michael Norrish (1997), An abstract dynamic semantics for C, Computer Systems Lab, University of Cambridge Technical Report.

  7. Xavier Leroy (2009), “Formal verification of a realistic compiler”, Communications of the ACM, 52(7):107–115. DOI: https://doi.org/10.1145/1538788.1538814

  8. David A. Schmidt (1986), Denotational Semantics: A Methodology for Language Development (William C. Brown Publishers). ISBN 9780205104505.

  9. Joseph A. Goguen, James W. Thatcher, Eric G. Wagner, and Jesse B. Wright (1977), “Initial algebra semantics and continuous algebras”. Journal of the ACM, 24(1): 68–95. doi:10.1145/321992.321997. S2CID 11060837.

  10. Peter D. Mosses (1996), “Theory and practice of action semantics”, BRICS Report RS9653. Aarhus University.

  11. Pierre Deransart, Martin Jourdan, and Bernard Lorho (1988), “Attribute Grammars: Definitions, Systems and Bibliography”, Lecture Notes in Computer Science 323 (Springer-Verlag). ISBN 9780387500560.

  12. Pierre Deransart, Martin Jourdan, and Bernard Lorho (1988), “Attribute Grammars: Definitions, Systems and Bibliography”, Lecture Notes in Computer Science 323 (Springer-Verlag). ISBN 9780387500560.

  13. F.William Lawvere (1963), “Functorial semantics of algebraic theories”, Proceedings of the National Academy of Sciences of the United States of America, 50 (5): 869–872. doi:10.1073/pnas.50.5.869. PMC 221940. PMID 16591125.

  14. Mark Batty, Kayvan Memarian, Kyndylan Nienhuis, Jean Pichon-Pharabod, and Peter Sewell (2015), “The problem of programming language concurrency semantics”, Proceedings of the European Symposium on Programming Languages and Systems (Springer), pp. 283–307. doi:10.1007/978-3-662-46669-8_12.

  15. Samson Abramsky(2009).“Semantics of interaction: An introduction to game semantics”, In Andrew M.Pitts and P.Dybjer(eds.), Semantics and Logics of Computation(Cambridge University Press), pp.1-32. doi:10.1017/CBO9780511526619.002. ISBN 9780521580571.

  16. Edsger W. Dijkstra(1975),“Guarded commands, nondeterminacy and formal derivation of programs”, Communications of the ACM, 18(8):453-457.doi:10.1145/360933.360975.S2CID 1679242.

  17. Ankush Phulia, Vaibhav Bhagee, and Sorav Bansal(2020),“OOElala: order-of-evaluation based alias analysis for compiler optimization”,‘(In Proceedings of the 41st ACM SIGPLAN Conference on Programming Language Design and Implementation(PLDI 2020). Association for Computing Machinery, New York,NY,USA,839-853).DOI:https://doi.org/10.1145/3385412.3385962

Contributed by: Sorav Bansal, Indian Institute of Technology Delhi

What is Undefined Behaviour or UB, and why do we need to discuss UB semantics? Let’s look at a few examples to understand this better. Consider a source expression in a high-level language like C, “x = y/z”. Now consider two machines with different ISAs (Instruction Set Architectures) and let’s assume that “x = divide y, z” is a common instruction on both ISAs that implements “x = y/z” in the assembly code. There is a subtle difference between the two ISAs however, in how they handle division-by-zero, i.e., the case when “z” evaluates to zero: on one machine, a division by zero causes a hardware exception (eventually leading the program to terminate execution) while on the other machine, a division by zero simply returns the zero result into “x”. Now, what should be the semantics of “x = y/z” in the C language? If the C language designer chooses to cause an exception on division-by-zero, then the code generated on the second machine may need to look something like: “if z == 0 then RaiseException else x = y/z”. On the other hand, if the C language designer chooses to return the zero value into “x”, then the code generated on the first machine may need to look something like: “if z == 0 then x = 0 else x = y/z”. Irrespective of the choice taken by the C language designer, there will always be suboptimal code generation on at least one of the machines—this is because at least on one of the machines, the generated code would involve a conditional branch.

Notice that this overhead of the conditional branch is necessary only to handle the corner case error condition; yet we will pay this overhead on every execution of the division instruction, irrespective of whether the denominator was zero or not. Further, while we have considered only two ISAs in our example, the number of different ISAs and the different ways in which they handle such error conditions (such as divide-by-zero) is much larger, and thus if the C language designer makes one choice, the code generated on all other ISAs could potentially be suboptimal.

To handle these situations, the language designer may allow the semantics of the programming language to be non-deterministic. For example, the non-deterministic semantics could allow division-by-zero to either cause an exception or return the zero value. This allows the compiler/interpreter to choose the optimal implementation depending on the underlying machine ISA. One such type of non-deterministic semantics, that are exclusively meant to capture such corner-case error conditions, are the undefined behaviour semantics.

The undefined behaviour semantics say that if during runtime, an expression “x=y/z”is evaluated on a state where “z” evaluates to zero, then anything can happen-in other words, such an evaluation triggers Undefined Behaviour(UB). By “anything can happen”,we mean that the program can potentially exhibit any behaviour in such a situation,e.g.,it can raise an exception, it can silently ignore the instruction, it can return the zero value into “x”,it could overwrite the entire process memory with random contents, it could send out a message on the network, it could terminate the process, etc. Because division-by-zero is deemed UB in C, the compiler and runtime are free to choose any implementation for this situation. These anything-can-happen UB semantics are also popularly called catch-fire semantics. These catch-fire semantics also imply that for a program execution to be “well-behaved”(also called “well-defined”), the program execution must be free of UB.In this chapter, we discuss the nature of such UB semantics in the source and intermediate languages and their important implications on compiler optimizations.

A common example of UB involves an array dereference. Consider an expression “x=y[i]“,where “y” represents an array in the program containing “sz” elements, and “i”is a signed integer used to index into the array to obtain the “i”th element. Now, what should the C-language semantics specify for the situation where “i” is outside the range of indices for “y”;e.g.,if “i”is less than zero or greater than or equal to “sz”.One approach could be to expect that the program must raise an exception in such a scenario,e.g.,the assembly implementation for this C expression could look something like:“if(i<0||i>=sz)then raise MemoryException else x=(y+i)”. However, such semantics would require the compiler to emit an if-then-else clause for every such memory access-once again, the cost of this if-then-else construct will be paid for every array access, and not just for the(rare) array accesses that have an out-of-bounds index. This approach of raising memory exceptions is indeed used by some languages like Java, which prioritize the program’s safety(and debuggability) over the program’s runtime performance. However, a performance-critical language like C instead chooses to use UB semantics for such out-of-bounds accesses,i.e.,if a program execution causes an out-of-bounds memory access, then anything can happen(the program triggers UB).This allows the compiler to emit the simple implementation “x=(y+i)”-in situations where “i”is out of bounds, this may cause the program to read arbitrary memory values into “x”(which would be acceptable under the UB semantics, where anything could happen).

13.1.2 UB Associated with Integer Overflow

Section titled “13.1.2 UB Associated with Integer Overflow”

Integer arithmetic operations also involve error conditions related to overflow. For example, consider the instruction “x = y + z” where x, y, and z are of integer type of a finite bitwidth. If the addition operation, “y + z”, results in arithmetic overflow, different architectures handle it differently, depending on the internal representation of the integer type. For example, some machines may implement “saturating arithmetic” where the maximum-representable integer value is stored into “x” on overflow; while other machines may exhibit wrap-around semantics where the overflowing bit is simply discarded. To allow flexibility for the compiler in choosing the exact implementation, which depends on the hardware being compiled for, the C language specifies that overflow for signed integer arithmetic triggers UB.

Exercise 13.1.1: Consider the C expression “x / (y + z)” (where “x”, “y”, and “z” are signed integers). The precise condition under which UB is triggered during the evaluation of this expression is:

a. “y+z” overflows OR b. “y+z” evaluates to zero

Similarly, identify the precise conditions under which UB is triggered during the evaluation of the following expressions:

a. “(x+y) / (w+z)” b. a[x+y] / y c. A[x+y] + B[w+z]

13.2 Implications of UB Semantics for Compiler Optimization

Section titled “13.2 Implications of UB Semantics for Compiler Optimization”

An important consequence of this property is that the compiler optimization algorithms can safely assume the absence of UB conditions while reasoning about all possible “legal” (or well-behaved) program execution behaviours. Even if UB happens during execution, because it entails anything-can-happen semantics, whatever happens, would still be within the permissible realm of the programming language semantics. And thus the compiler can conveniently avoid catering to those cases. Let’s understand this more clearly with an example.

could allow division-by-zero to either cause an exception or return the zero value. This allows the compiler/interpreter to choose the optimal implementation depending on the underlying machine ISA. One such type of non-deterministic semantics, that are exclusively meant to capture such corner-case error conditions, are the undefined behaviour semantics.

The undefined behaviour semantics say that if during runtime, an expression “x=y/z”is evaluated on a state where “z” evaluates to zero, then anything can happen-in other words, such an evaluation triggers Undefined Behaviour(UB). By “anything can happen”,we mean that the program can potentially exhibit any behaviour in such a situation,e.g.,it can raise an exception, it can silently ignore the instruction, it can return the zero value into “x”,it could overwrite the entire process memory with random contents, it could send out a message on the network, it could terminate the process, etc. Because division-by-zero is deemed UB in C, the compiler and runtime are free to choose any implementation for this situation. These anything-can-happen UB semantics are also popularly called catch-fire semantics. These catch-fire semantics also imply that for a program execution to be “well-behaved”(also called “well-defined”), the program execution must be free of UB.In this chapter, we discuss the nature of such UB semantics in the source and intermediate languages and their important implications on compiler optimizations.

A common example of UB involves an array dereference. Consider an expression “x=y[i]“,where “y” represents an array in the program containing “sz” elements, and “i” is a signed integer used to index into the array to obtain the “i”th element. Now, what should the C-language semantics specify for the situation where “i” is outside the range of indices for “y”,e.g.,if “i” is less than zero or greater than or equal to “sz”.One approach could be to expect that the program must raise an exception in such a scenario,e.g.,the assembly implementation for this C expression could look something like:“if(i<0||i>=sz)then raise MemoryException else x=(y+i)”. However, such semantics would require the compiler to emit an if-then-else clause for every such memory access-once again, the cost of this if-then-else construct will be paid for every array access, and not just for the(rare) array accesses that have an out-of-bounds index. This approach of raising memory exceptions is indeed used by some languages like Java, which prioritize the program’s safety(and debuggability) over the program’s runtime performance. However, a performance-critical language like C instead chooses to use UB semantics for such out-of-bounds accesses,i.e.,if a program execution causes an out-of-bounds memory access, then anything can happen(the program triggers UB).This allows the compiler to emit the simple implementation “x=(y+i)”-in situations where “i” is out of bounds, this may cause the program to read arbitrary memory values into “x”(which would be acceptable under the UB semantics, where anything could happen).

Integer arithmetic operations also involve error propagation. Consider the instruction “x = y + z” where x is a bitwidth. If the addition operation, “y + z”, results in an overflow, it is different depending on the internal type. For example, some machines may implement “saturating” maximum-representable integer value is stored into “x” on overflow, while exhibit wrap-around semantics where the overflow bit is simply disabled. For the compiler in choosing the exact implementation, which depends on the hardware being compiled for, the C language specifies that overflow for signed arithmetic triggers UB.

Exercise 13.1.1: Consider the C expression “x / (y + z)” (where “x” “y” and “z” are signed integers). The precise condition under which UB is triggered during the evaluation of this expression is:

  1. “y+z” overflows OR
  2. “y+z” evaluates to zero

Similarly, identify the precise conditions under which UB is triggered during the evaluation of the following expressions:

  1. -(x+y) / (w+z)
  2. a[x+y] / y
  3. A[x+y] + B [w+z]

13.2 Implications of UB Semantics for Compiler Optimization

Section titled “13.2 Implications of UB Semantics for Compiler Optimization”

An important consequence of this property is that the compiler optimization algorithms can safely assume the absence of UB conditions while reasoning about all possible “legal” (or well-behaved) program execution behaviors. Even if UB happens during execution, because it entails anything-can-happen semantics, whatever happens, would still be within the permissible realm of the programming language semantics. And thus the compiler can conveniently avoid catering to those cases. Let’s understand this more clearly with an example.

13.2.1 Example for Signed Integer Overflow

Section titled “13.2.1 Example for Signed Integer Overflow”

int n;

for(int i= 0; i<n+ 1; i++)

↓

for(int i= 0; i<= n; i++)

Legal?

Figure 13.1: Signed Integer Overflow Optimization Example

In Fig. 13.1, consider the for-loop’s loop condition “i<n+ 1.”Computing this condition may first require performing an addition operation(“n+ 1”) and then performing a comparison operation(“i<..”).A compiler would ideally like to optimize this condition to “i<= n,” as it saves the addition operation. However, would such a transformation from “i<n+ 1”to “i<= n”be legal? To show that this transformation is illegal, we only need to provide one possible value for the input variable “n” such that the two programs evaluate to different results.

Consider the scenario where “n=INT_MAX”, where INT_MAX is the maximum-representable value for the integer type,e.g., INT_MAX could be 231-1 for a 32-bit machine using 2’s complement representation. Also, consider the case where the machine implements wrap-around semantics for integer arithmetic overflow,i.e., INT_MAX+ 1 would evaluate to-231(or INT_MIN). In this case, the original for-loop would look like “for(int i= 0; i< INT_MIN; i++)” which specifies that the for-loop is never entered(because the initial value of “i” does not satisfy the loop-condition). On the other hand, the transformed for-loop would look like “for(int i= 0; i<= INT_MAX;i++)”. Thus, for “n=INT_MAX”, the transformed for-loop would execute an infinite number of iterations(because “i” being an integer would always be “<= INT_MAX”).Thus, because the two loops(original and transformed) evaluate to different results for “n=INT_MAX”; this argues that the transformation is not legal.

However, recall that we mentioned that signed-integer arithmetic overflow is UB in C.In our example,“INT_MAX+ 1” would result in arithmetic overflow, and would thus trigger UB. Also, recall that we said that the compiler does not need to bother about the situations that trigger UB. And thus, the compiler does not need to bother about this corner case scenario where “n=INT_MAX” because that corner-case scenario triggers UB. For all other permissible values of the input variable “n”(that do not trigger UB),this transformation is legal because both programs evaluate to the same result. And thus a compiler is allowed to make this transformation- it is interesting to see how this simple and very common transformation is legal only due to the UB semantics available in the programming language, and would have been illegal in the absence of UB semantics. Indeed, C compilers routinely use this transformation by leveraging the signed-integer overflow UB semantics.

13.2.2 Example for Type-based Strict Aliasing

if (!a) return; void foo (int *a, float *b) { for (int i = 0; i < n; i++) { b[i] += *a; } }

Figure 13.2 Type Based Strict Aliasing Optimization Example

In Fig. 13.2, consider the C function foo() that takes two input arguments “a” and “b”.where “a” is a pointer to an integer type and “b” is a pointer to a float type. The program involves a for loop that iterates variable “i” from “0” to “n”, accumulating “*a” into “b[i]” in each iteration. In this example, would it be legal for a compiler to perform Loop Invariant Code Motion (LICM) wherein “*a” is precomputed and cached into a register “r” before the loop begins, and then the register “r” is used to update “b[i]” in each iteration (shown below in Fig. 13.3)?

r = *a for (int i = 0; i < n; i++) { b[i] += r; }

Figure 13.3 LICM Example

If it is possible for “*a” to refer to the same memory location as “b[i]” (for some value of “i” between “0” and “n-1”), then this transformation (from Figure 13.2 to Figure 13.3) is illegal because when “b[i]” gets overwritten, “*a” may get overwritten too. Thus, it would be incorrect to precompute the value of “*a” into “r” at the beginning of the loop.

Fortunately, this LICM transformation is legal in C due to its Type-Based Strict-Aliasing (TBSA) UB semantics. The TBSA UB semantics state that if a memory location holds an object of some type T1, then it is UB for the program to dereference that location to try and obtain an object of an incompatible type T2 from that same location through de-reference. For example, if we store an integer to a memory location “l”; and then try to dereference location “l” to obtain a float (floating point) object (e.g., through a float pointer), then that would trigger UB. This allows the compiler/runtime to use arbitrary bit-level representations for different types, without worrying about how the representation of one type may affect the representation of another unrelated type.

Using TBSA UB semantics, in our example, we can be sure that “b[i]”(of integer type) can never point to the same location as “*a”(of float type)- because if they do, they violate the TBSA assumption that a location holding an integer(or float) type will never be dereferenced through a float(or integer) pointer. Based on this property, the compiler can safely assume that “b[i]”and “*a”can never be aliased in a legal program(for all possible values of “i”) and thus the LICM transformation shown above is valid under C’s UB semantics.

Notice that just like most UB semantics, the TBSA UB semantics in C are not checked explicitly-neither by the compiler nor by the runtime. Thus, it is the responsibility of the programmer to ensure that her program is UB-free. This is unlike other languages(e.g.,Java) where explicit runtime checks are emitted in the generated code(which involves runtime overhead).

13.2.3 Example for Based-On Semantics in C

Section titled “13.2.3 Example for Based-On Semantics in C”

int A[256];

int b[1];

void foo(int n){

int*p= A;

for(int i= 0; i< n; i++, p++){

*p+= b[0];

}

Consider this C program where a pointer “p”is initialized to the start address of the array “A” and then incremented on every iteration of the subsequent for-loop. Notice that the for-loop iterates over “i” from “0” to “n-1”-but what should happen if “n” exceeds 256,the size of the array “A”? Because “p” was initialized to “A”,it is a pointer that is based on “A” and thus if it points outside the limits of “A”,then the C programming language deems it UB.

Using these based-on semantics in the C programming language, it is possible for the compiler to infer that this program is legal only if “n<= 256”; and thus it is free to assume this and transform/optimize the code accordingly.

Exercise 13.2.1: Often, the expression “(lo+ hi)/2” is used to compute the average of two signed integers “lo” and “hi”;e.g.,such an expression will likely be used to compute the “mid” element during the binary search algorithm. Determine the condition under which this expression triggers UB.If both “lo” and “hi” are known to be greater than zero, then is it possible to rewrite this expression so that it becomes UB-free?

All the UB examples discussed so far are based on the source programming language, i.e., both the original program and the transformed program have been written in the source programming language itself. However, a compiler typically performs these transformations at the IR abstraction level, and thus it is important for these UB semantics to be preserved at the IR level too.

A common IR language is the Three-Address Code (3AC): translating a source program to an unoptimized 3AC program typically involves translating each operator in the source program’s abstract syntax tree to its corresponding instructions in the 3AC IR. The instructions in the IR language should be rich enough, so this translation preserves the UB semantics.

We use an example of a 3AC-like IR, the Low-Level Virtual Machine (LLVM) IR to demonstrate how UB semantics for the C language are preserved during translation to LLVM IR. Here are some examples of how LLVM-IR preserves UB semantics:

  1. The division operation in C (encoded using the “/” character) is translated to the “div” opcode in LLVM IR. Division by zero (using the “div” opcode) in LLVM IR also triggers UB in the LLVM program (just like it triggers UB in the C program). Thus, this translation of the division operation to the “div” opcode preserves UB semantics.

  2. Arithmetic operations in C (e.g., “+”, “-”, etc.) are encoded using the “add”, “sub”, etc. opcodes in the LLVM IR. LLVM IR provides opcode modifiers in the IR language. For integer arithmetic, it provides two opcode modifiers: (a) nsw (no signed overflow), and (b) nuw (no unsigned overflow). Thus we can have three types of addition operations in LLVM IR:

(a) x = add y, z Here, the wrap-around semantics are used on overflow (in two’s complement representation). This instruction is thus used to implement the unsigned-integer arithmetic in the C program.

(b) x = add nsw y, z Here, “y” and “z” are treated as signed integers in two’s complement representation. On an overflow in signed arithmetic, this instruction triggers UB. Thus, to implement C language’s signed-integer-overflow UB semantics, this instruction must be used to implement all signed-integer arithmetic in the C source program.

(c) x = add nuw y, z Here, “y” and “z” are treated as unsigned integers in two’s complement representation. On an overflow in unsigned arithmetic, this instruction triggers UB. Because the C language does not involve unsigned-integer overflow UB semantics, this instruction is not used while lowering C programs to LLVM IR.However, this instruction may potentially be used during the lowering of other source languages that may involve unsigned-integer overflow UB semantics. Notice that the LLVM IR supports more types of UB(e.g.,“nuw” modifier) than the C language because it is designed to cater to multiple source languages,

  1. The LLVM IR preserves types which allows the compiler to preserve UB information associated with type-based strict aliasing and based-on semantics in C.

Exercise 13.3.1: Consider the C expression “a+b”. Identify the translation of this expression to the LLVM IR for the following two cases:

a. When both “a” and “b” represent signed integers in C.

b. When both “a” and “b” represent unsigned integers in C.

13.4 Considerations during the Design of IR Semantics

Section titled “13.4 Considerations during the Design of IR Semantics”

We have already seen that Undefined Behaviour(UB) in the source programming language enables optimization. UB semantics introduce a certain type of non-determinism in the semantics of the programming language-they specify that if an error condition occurs, then the program can non-deterministically behave in any possible way. This non-determinism in the programming language semantics allows the compiler a wider transformation space, in turn providing better optimization opportunities. To see this again with an example, the following transformation(Fig. 13.5) is only possible because signed integer overflow is UB in C.

int n;

for(int i= 0; i< n+ 1; i++)

…

↓

for(int i= 0; i<= n; i++)

…

Legal?

Figure 13.5 Signed Integer Overflow Example

To summarize, non-determinism in source program semantics increases the transformation space and optimization opportunities. But what if the target language semantics also includes non-deterministic semantics? In the example shown above, both the source and the target languages are the same language (the C language)—and thus while it is ok to transform from the left program to the right program, it is not correct to transform from the right program to the left program. This can be seen by considering the case when “n=INT_MAX”: while the for-condition evaluation in the program on the right has deterministic semantics in this case (it will always evaluate to true), the program on the left has non-deterministic semantics during the evaluation of the for-condition (UB is triggered while evaluating “n+1”). Thus, it is not correct to transform the program on the right to the program on the left, because the program on the left accepts more (non-deterministic) behaviours than were acceptable by the program on the right.

In general, while non-determinism in the source program enables optimization opportunities, non-determinism in the target program disables optimization opportunities. This tension between non-determinism in the source and target programs can be seen more clearly with the following example:

Source: if (cond) { y = x + 1; … } // y not used here

Target: y = x + 1; //this computation is hoisted above the if-condition check if (cond) { … }

In the source program, the expression “x + 1” is computed only if “cond” evaluates to true. In the transformed target program, the expression “x + 1” is computed unconditionally (it is hoisted above the if-condition). However, there is a problem with this transformation in the presence of UB semantics. If “x + 1” could trigger UB (e.g., due to signed integer overflow UB semantics), then for a certain value of “x” and “cond” (x = INT_MAX and cond = false), the target program exhibit more behaviours than the source program: the target program triggers UB while the source program executes deterministically. Thus, this transformation is not legal in the presence of signed-integer overflow UB semantics.

designed so they enable most transformations,i.e., they increase the transformation space when present in the source program, and they do not thwart the transformation space when present in the target program.

We introduce poison value semantics by contrasting them with the traditional UB semantics that we have seen earlier. In UB semantics, an error condition(such as signed integer overflow) during execution causes the program to be wrong. In contrast, in poison value semantics, an error condition during execution simply produces an error value into the target register-we also call this error value, the poison value.

UB semantics

error condition program is wrong

Poison value semantics

error condition error value is generated

We say that poison value semantics are weaker than UB semantics because poison value semantics limit the types of non-determinism that may occur during an error condition. While UB semantics say that “anything can happen” on an error, the poison value semantics only say that “an unusable value(the poison value) will be generated on an error”.Notice that the non-deterministic choices represented by the latter semantics(unusable value) are a strict subset of the non-deterministic choices represented by the former semantics(anything can happen). Thus, we say that poison value semantics are weaker(i.e.,narrower in their non-determinism) than UB semantics.

To see how poison value semantics help, consider the Loop Invariant Code Motion(LICM) example in Fig. 13.6 discussed earlier:

Source

UB semantics

int x;

…

while(…){

Consider

while(…){

y=x+1

x== INT_MAX

…//use(y)

and loop

never entered

}Target

…

y=x+1

while(…){

…//use(y)

}

Figure 13.7 LICM Hoisting Example

In this example, the hoisting of the expression “y= x+ 1” above the loop is incorrect because if the evaluation of “x+ 1” causes UB(e.g., due to signed integer overflow, when “x”is INT_MAX) and the loop condition is such that the loop is never entered, then the target program exhibits UB when the source program would have had a well-defined execution.

Now consider this same transformation under the poison value semantics. If the evaluation of “x+1” creates an error condition(e.g., due to signed integer overflow, when “x” is INT_MAX), then a poison value is generated and stored into the target register “y”. Now if the loop was never executed, then the value stored in “y” is never used (because it is used only inside the loop), and thus the transformed program still has the same observable behaviour as the original source program—the only difference in the behaviours of the two programs is that the target program performs an extra computation (if the loop is never taken) but the results of that computation are discarded, i.e., they have no observable effect. Thus, under poison value semantics, this LICM transformation, involving hoisting of computation, is correct, as shown in Fig. 13.8.

Figure 13.8 LICM Hoisting Example with Poison Semantics

UB Semantics are more desirable than Poison Value Semantics in some situations

In the example shown in Fig. 13.9, the LICM transformation is performed on an instruction that involves a division operation. Recall that division-by-zero is an error condition (just like signed integer overflow) and would trigger UB in a source language like C.However, unlike signed integer arithmetic overflow, in the case of division-by-zero, we typically do not want this hoisting transformation to be allowed: this difference stems from how the hardware architectures typically treat division-by-zero (vis-a-vis arithmetic

In practice, hardware architectures typically produce some value for “y” on an integer arithmetic overflow,e.g., they may produce the wrap-around or saturating-arithmetic result. And thus, arithmetic such as “y/2” would produce another value(that may be different for different architectures). Because the program does not care about these values in these exceptional overflow situations, it is usually safe to hoist such computation above the loop. And so, we would like to enable such a LICM transformation.

To enable this LICM transformation, a simple semantics is that certain types of arithmetic on the poison value, such as “poison/2”,“poison+X”,“poison+Y”,etc.,simply produce the “poison” value again. In this case, even for the case when “x” evaluates to INT_MAX and the loop is never taken, the target program simply produces a “poison”value into both “y” and “z” registers, but neither of those values influence the observable behaviour of the program, and so the target program’s observable behaviour is identical to the source program’s observable behaviour. Thus, based on this example, Option 2 is the preferred option for poison value semantics. Let’s now look at another example in Fig. 13.11.

Example 13.2

Source

Target

int x;

int x;

…

while(…){?

y=x+1;

We don’t

z=2/y;

y=x+1;want this

while(…){

z=2/y;

transformation

to be valid

}

}

Figure 13.11 Poison Value Semantics for Example 13.2

In this example, we have replaced “z=y/2” with “z=2/y”.The primary difference is that “y”(which could potentially take the “poison” value) is now in the denominator of the division operation. This is consequential because this can lead to division-by-zero(as the poison value could potentially get lowered to the zero value in the assembly program). Because division-by-zero could cause hardware exceptions, we would not like to allow such LICM transformations as they may cause the target program to cause exceptions in situations where the source program would have executed normally.

However, if we use the poison value semantics suggested in Option 2, we would evaluate “2/poison” to “poison”-and thus, under these semantics, this transformation would be acceptable. To ensure that such transformations are unacceptable, we need to ensure that “2/poison” triggers UB, so this computation cannot be hoisted above the loop.

We have seen through examples the different choices for poison value semantics and their implications. We now look at a concrete example of the LLVM IR language, where a mix of both Option-1 and Option-2 semantics are used. In LLVM, some operations on poison trigger UB (Option-1) while others simply return the poison value (Option-2). For example, the division-by-poison operation (e.g., “2/poison”) triggers UB while other non-excepting operations (e.g., “poison/2”, “poison+…”, etc.) return the poison value. We discuss this in more detail in the next section.

Exercise 13.6.1: Consider the following operations on the poison value. Which of these operations should trigger UB and which of them should instead return the poison value?

a. Floating point operation on poison value. b. Array access using the poison value as index. c. Signed integer arithmetic with at least one operand as the poison value. d. Dereference of a poison value address. e. Division by poison. f. Logical shift by poison value.

Compare the answers to this question to the answers to the previous exercise involve the generation of poison value vs. triggering UB.

The LLVM IR is a popular IR and supports multiple source programming languages like C, C++, etc. Undefined behaviour semantics in the source language are then translated to poison value semantics in the LLVM IR. It is instructive to look at the concrete semantics used in LLVM for the poison value, as they provide insight into the choices made by IR designers in practice, and the reasons behind those choices. We will also look at the good and bad implications of these design choices.

To illustrate the LLVM semantics for operations on a “poison” value, consider the following LLVM code example:

p = add nsw i32 0x7fffffff, 1
p2 = sub i32 p, 1
p3 = and i32 p, 0
p4 = or i32 p, 1

Recall that the “add nsw” instruction opcode in LLVM generates a poison value on signed integer overflow. In the first instruction of this example, we have crafted the operands of this opcode such that it will cause signed-integer overflow (for a 32-bit signed integer). Thus, the variable “p” will obtain a “poison” value upon the execution of this instruction. In the subsequent instructions, the program uses the variable “p” and computes on it using different opcodes: in all the three computations (subtract, logical-and, logical-or), the resulting values “p2”, “p3”, “p4” are all “poison” values.

It is interesting to see that “p3” obtains a value that involves conjunction (logical-and) with the zero bitvector — it would have been ok for the LLVM IR designer to say that the resulting value in this case would be the “zero” value (irrespective of whether “p” is “poison” or not); however, the LLVM IR designer chooses to generate the “poison” value into “p3” in this case.

Similarly, “p4” obtains a value that involves disjunction (logical-or) with the constant “1”. Thus, it was possible for the IR designer to say that the least significant bit of “p4” will always be “1” in this case. However, the LLVM designers choose to instead generate the “poison” value in this case (if either of the operands of the logical-or instruction were “poison”). Generating a “poison” value allows more non-determinism (than generating a “zero” value or a value with LSB = 1); because a “poison” value restricts the ways in which it may be used (e.g., it is UB for a poison value to have any effect on the observable behaviour) — these restrictions ensure a larger transformation space when a “poison” value is generated. This choice of how much non-determinism to preserve across a computation depends on a careful determination of typical compiler optimizations and their profitability. Further, the IR designer needs to be cognizant of the behaviour of typical hardware while choosing these semantics, e.g., division-by-poison triggers UB.

x = y/p;

Division by a “poison” value also triggers UB in LLVM. This ensures that this operation cannot be hoisted — such restrictions on hoisting transformations are desirable because a division can potentially cause divide-by-zero exceptions in hardware (and a “poison” value may eventually get lowered to the “zero” value in assembly).

if (p) {
...
} else {
...
}

Figure 13.12 Branch On Poison In the code snippet above (Fig 13.12), the variable “p” could potentially hold a “poison” value. Thus the conditional branch on “p” would translate to a conditional-branch on the “poison” value, and we need to define the semantics for such an operation.

There are again several options for the semantics for a branch operation on a poison value, e.g., one choice of semantics may allow the program may be assumed to take any of the branches non-deterministically LLVM IR deems a conditional branch operation on a “poison” value as Undefined Behaviour (UB), as shown in Fig. 13.13. In other words, the condition used in a branch operation should never evaluate to a “poison” value (in a UB-free program).

if (poison) { //triggers UB … } Figure 13.13 Branch On Poison Triggers UB

Such UB is often represented by showing that a compiler is free to transform code that causes UB to an “unreachable” instruction (because this program point should never be reached in a UB-free program), as shown in Fig. 13.14.

if (poison) { … } else { … } Figure 13.14 UB Program Can Be Transformed To Unreachable

Implications of Triggering UB on Branch-on-Poison

Section titled “Implications of Triggering UB on Branch-on-Poison”

Although it is an easy option to deem branch-on-poison as UB (in fact we could have also chosen to deem other operations on the “poison” value as UB too), this choice thwarts optimization opportunities in some cases, as we show through an example below.

Consider the transformation shown below in Fig. 13.15.

if (a) { if (b) { … } } if b is poison and a is false While this transformation in Fig. 13.15 would be legal for poison-free values, consider the case when “a” evaluates to false, and “b” evaluates to “poison”.In the source program, the conditional branch is evaluated on “a” and the if-condition is never entered. However, in the target program, first “a&&b” is computed, which would evaluate to “poison” in this case, and then a conditional branch is evaluated on the result, which would trigger UB.Thus, we have an input state for which the source program executes correctly but the target program triggers UB; thus this transformation is incorrect under LLVM’s poison value semantics.

Here is another example of the Loop Unswitching transformation in Fig. 13.16.

Loop Unswitching

while(c){if(d){if(d) s1;while(c) s1;else s2;else{while(c) s2;}}

Figure 13.16 Loop Unswitching Example

The loop unswitching transformation is a highly profitable transformation because it reduces the number of instructions that need to be executed within the body of a loop. This transformation is commonly employed and is often essential for aggressive vectorization transformations to be effected. Unfortunately, however, this transformation is incorrect if “c” evaluates to “false” and “d” evaluates to the “poison” value(Fig. 13.16).In this case, while the source program would simply not enter the loop at all, the target program would trigger UB(due to branch-on-poison). We later discuss the “Freeze” opcode as a solution to such problems.

Just like all other values, the poison value can be stored to memory, and loaded back. For example, if you execute*x=p followed by p2=*x, then “p2” will contain the “poison” value if “p” contained the “poison” value originally.

13.7.4 Loading-from and Storing-to Poison Pointer

Section titled “13.7.4 Loading-from and Storing-to Poison Pointer”
∗p = x;x = ∗p;*p\,=\,x;\quad x\,=\,*p;

Figure 13.17 Load Store To Poison Pointer

If during a memory load or a memory store, the address is a “poison” value, then LLVM triggers UB.This is required because the compiler does not want to hoist or sink unsafe memory operations, just like it does not want to hoist division-by-zero operations.

The poison value semantics have a direct effect on the hoisting transformations that are legal/illegal in LLVM. For example, transformations that involve hoisting of memory accesses (Fig. 13.19) or division-by-zero (Fig. 13.18) are disallowed while hoisting of other arithmetic operations (Fig. 13.20) are allowed—this is a direct result of the poison value semantics for different operations; while the former operations trigger UB for poison arguments, the latter simply generate new poison values.

while (…) { x = y/z; x = y/z; while (…) { } … }

Figure 13.18 Hoisting Division Example

while (…) { x = *p; x = *p; while (…) { } … }

Figure 13.19 Hoisting Memory Access Example

while (…) { x = y + z; x = y + z; while (…) { } … }

Figure 13.20 Hoisting Arithmetic Operation Example

13.7.6 Compiler Analyses May Guarantee Poison-Free Values

Section titled “13.7.6 Compiler Analyses May Guarantee Poison-Free Values”

It is important to see that the hoisting of certain operations is disabled only if the compiler has to make the conservative assumption that an argument may hold the “poison” value. In case the compiler is able to ascertain that a variable does not hold a “poison” value(through conservative value analyses), then it may still be acceptable to perform hoisting transformations, as seen in the example of Fig. 13.21.

int A[256]; … 0≤ n< 256; while(…) { x=A[n] while(…) { ok … x=A[n];//x can be poison } … }

Figure 13.21 Compiler Analysis Guarantees Poison Freedom

Here, if the compiler is able to ascertain that n lies within the bounds of the array “A”, then it is legal to hoist “x=A[n]”above the loop. However, if the compiler is unable to ascertain that “n”lies within the bounds of the array A, then that would result in the de-reference of a potentially “poison” address in LLVM, and would thus be incorrect to hoist above the loop.

13.7.7 Immediate UB in Source vs. Deferred UB in IR

Section titled “13.7.7 Immediate UB in Source vs. Deferred UB in IR”

If we reflect on the difference between UB semantics in the source language(e.g.,C/C++)and poison value semantics in the IR language(e.g.,LLVM), we will find that poison-value semantics simply defer the UB. For example, consider the instruction “x= y+z”. If this instruction causes signed arithmetic overflow, then it would immediately trigger UB in the source language. However, in the IR language, it would only generate a “poison” value into “x”. However, as “x”is used further in the program, the “poison” value would propagate and could eventually trigger UB if it potentially influences the program’s observable behaviour(e.g., when it is used in a conditional branch or a memory access). For this reason, the poison value semantics are also called “deferred UB semantics”.

In Section 13.7.2, we discussed how if the loop conditions could potentially evaluate to the “poison” value, the loop unswitching transformation becomes incorrect(because a branch on “poison” triggers UB). However, as we have discussed earlier, transformations like loop-unswitching are important and consequential, e.g., they often enable the vectoriza-tion of regular loops. Does that mean that even though these transformations are profitable, they are disallowed because we have to worry about the corner-case error conditions that are modeled through the “poison” value?

Fortunately, there exists a solution to this problem, the freeze opcode.

x=freeze yx=freeze\,y

The freeze opcode takes a single argument of some type “T” and returns a value of the same type “T”. The semantics of the “freeze” opcode are that: if “y” contains a regular(non-poison) value, then the same value is returned into “x”; however if “y” contains the “poison” value, then some arbitrary non-poison value of type “T” is returned into “x”. Thus, the special property of the “freeze” opcode is that it always returns a regular well-defined non-poison usable value.

Using the “freeze” opcode in the IR now enables important transformations like loop unswitching, as shown below:

while (a) { if (b) … else … } if (freeze (b)) { while (a) … } else { while (a) … }

Figure 13.22 Loop Unswitching With Freeze

In this transformation, while hoisting the conditional branch outside the loop, the compiler freezes the value of variable “b” to ensure that the branch does not result in UB—because “b“‘s frozen value is used, it is guaranteed to be poison-free and thus will not cause UB due to poison-on-branch.

The freeze opcode is converted to a no-op while lowering to assembly. In general, it is always correct to add freeze instructions in your code to ensure that some of the program variables become poison-free. However, an indiscriminate use of the “freeze” instruction can thwart future optimization opportunities, especially those optimization opportunities that relied on the existence of a “poison” value in case of error conditions. This can be seen using the following example in Fig. 13.23.

int n; for (i = 0; i < n + 1; i++) for (i = 0; i <= n; i++)

Figure 13.23 For Loop Transformation

Recall that this transformation (shown in Fig. 13.23) is correct only if we assume the signed-integer overflow yields the “poison” value (and triggers UB). Now consider the following scenario where the source program is modified such that the “n + 1” value is frozen before its use in the for-loop’s condition.

int n; for (i = 0; i < freeze(n + 1); i++) for (i = 0; i <= n; i++)

Figure 13.24 For Loop Transformation With Indiscriminate Freeze

In the example of Fig. 13.24, where the value “n + 1” is frozen, this transformation becomes incorrect. To see this, consider the case when “n” is INT_MAX: In the source program

  • “n + 1” would overflow and thus produce a “poison” value
  • This “poison” value would then be frozen into an arbitrary value, say f, of the integer type (e.g., 32-bit integer type)
  • Irrespective of the frozen value chosen, the for-loop condition, “i < f” would eventually become false (even if “f” is INT_MAX, “i” would eventually be equal to “f” and thus the condition “i < f” would evaluate to false).
  • Thus the source program always terminates
  • In the target program
  • “i <= n” would always evaluate to “true” (for n = INT_MAX)

Thus we have a situation where the target program would observably behave differently from the source program, and thus this transformation is incorrect.

To summarize: While the “freeze” instruction in the target program increases optimization opportunity, the same “freeze” instruction in the source program decreases optimization opportunity. Thus, a compiler transformation pipeline should introduce “freeze” instructions sparingly in the program, and should ideally introduce them only to enable certain important transformations.

Exercise 13.7.1: The assembly program that is output after all the IR-level optimizations contain only non-poison values. Thus, just before translation to assembly, all poison values are frozen before translating to assembly. However such freezing is not typically done at the previous stages of the compiler pipeline. Why not?

Exercise 13.7.1: We have seen through the loop-unswitching example that branch on a frozen value can be hoisted above to implement loop unswitching. Can a division operation “x/p” also be similarly hoisted above (e.g., for loop invariant code motion) by using changing it to “x/freeze (p)”? Why or why not?

  • Undefined Behaviour (UB) Permits Code Generation Flexibility on Multiple Architectures: Different hardware architectures have different methods of handling error conditions; if the source programming language employs UB, then different implementations can be emitted on different architectures, while still obeying the source programming language semantics. Undefined Behaviour Semantics 951

● UB Enables Optimization Opportunity: Many important compiler transformations become illegal due to the presence of corner-case conditions such as arithmetic overflow. The use of UB semantics allows the compiler to disregard these corner-case conditions, thus improving optimization opportunities. The UB semantics involve “anything can happen”, also called “catch-fire”, semantics.

● UB of different types is present in different languages: Different languages involve different types of UB semantics. Performance-oriented languages like C/C++ typically involve more UB than safety-oriented languages like Java and Python. UB may be associated with error conditions like division-by-zero, type-incompatibility.arithmetic overflow, out-of-bounds memory access, etc.

● UB in the target program can thwart optimization opportunities: While UB in the source program enables optimization opportunities, UB in the target program can thwart optimization opportunities. Because many transformations involve the same IR programming language for both the source and target programs, the IR semantics need to be carefully chosen so that most optimizations remain legal.

● Code Motion Transformations Become Harder In the Presence of UB Semantics: Code motion transformations, such as code hoisting and sinking, become harder in the presence of UB semantics in the language. For example, if the hoisted operation exhibits UB for certain inputs, then the target program may trigger UB in situations where the source program did not trigger UB.

● Poison Value Semantics Implement Deferred UB: Poison Value Semantics generat a poison value on the error condition. If the poison value is never used, it has effect on the observable behaviour of the program. Thus, the poison value seman tics enable hoisting and sinking transformations. They are also called deferred because they defer the UB trigger until the point where the poison value is used in an observable way.

● Different Operations behave differently on the Poison Value: Under poison value semantics, a poison value may participate in any language operation; thus we need to define semantics for each operation on the poison value. While some operations simply return the poison value(when they operate on a poison value), other operations on the poison value trigger UB.The language designer carefully chooses these poison value semantics to allow/disallow certain types of transformations. Control-flow based on a poison condition or a memory access on a poison address triggers UB in LLVM.

● Freeze Opcode: Even with the careful choice of poison value semantics, certain code transformations, such as loop unswitching, become invalid. The freeze opcode can be used in such situations. The freeze opcode always returns a non-poison value-it converts a poison value to an arbitrary non-poison value. Using the freeze opcode judiciously allows some transformations, such as loop unswitching, to become correct under the poison value semantics. However, the freeze opcode should be used sparingly as it may potentially disable future transformations in the compilation pipeline.

The Undefined Behaviour(UB) semantics have been a source of much contention, and it is thus no surprise that different programming languages have chosen different degrees of UB semantics, ranging from minimal-UB(e.g.,Java) to heavy-UB(e.g.,C/C++)[1].UB semantics have a profound impact on compiler transformations and the resulting safety of typical code[2,3,4,5].

At the IR level, the deferred UB semantics, the freeze instruction, and the associated transformations have been studied in detail in the context of LLVM IR[6]. There has been a significant amount of work on program analysis tools to detect and avoid UB in programs[7,8,9]. Similarly, there have been tools that check the correctness of compiler transformations in the presence of UB[10,11,12].

  1. Pascal Cuoq and John Regehr(2017),“Undefined Behavior in 2017”, Embedded in Academia Blog,4 July.

2.“Vulnerability Note VU#162289-gcc silently discards some wraparound checks”; Vulnerability Notes Database. CERT.4 April 2008. Archived from the original on 9 April 2008.

  1. Jonathan Corbet(2008),“GCC and pointer overflows”,Linux Weekly News,16 April.

4.“Vulnerability Note VU#162289-C compilers may silently discard some wraparound checks”. Vulnerability Notes Database, CERT.8, October 2008[4 April 2008].

  1. Manjeet Dahiya, and Sorav Bansal(2017),“Modeling Undefined Behaviour Semantics for Checking Equivalence Across Compiler Optimizations”, 19-34.10.1007/978-3-319-70389-3_2.

  2. Juneyoung Lee, Yoonseung Kim, Youngju Song, Chung-Kil Hur, Sanjoy Das, David Majnemer, John Regehr, and Nuno P. Lopes(2017),“Taming undefined behavior in LLVM”(In Proceedings of the 38th ACM SIGPLAN Conference on Programming Language Design and Implementation(PLDI 2017). Association for Computing Machinery, New York, NY, USA, 633-647). DOI:https://doi.org/10.1145/3062341.3062343

  3. Xi Wang, Nickolai Zeldovich, M. Frans Kaashoek, and Armando Solar-Lezama(2013),“Towards optimization-safe systems: analyzing the impact of undefined behavior”(In Proceedings of the Twenty-Fourth ACM Symposium on Operating Systems Principles(SOSP‘13). Association for Computing Machinery, New York,NY,USA,260-275).DOI:https://doi.org/10.1145/2517349.2522728

  4. LLVM’s Undefined Behaviour Sanitizer. https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html

  5. “Warning Options (Using the GNU Compiler Collection (GCC))”, (GCC, the GNU Compiler Collection - GNU Project - Free Software Foundation (FSF). Retrieved 2021-07-09).

  6. Nuno P. Lopes, David Menendez, Santosh Nagarakatte, and John Regehr (2015), “Provably correct peephole optimizations with alive”, (In Proceedings of the 36th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI ‘15). Association for Computing Machinery, New York, NY, USA, 22-32). DOI:https://doi.org/10.1145/2737924.2737965

  7. Nuno P. Lopes, Juneyoung Lee, Chung-Kil Hur, Zhengyang Liu, and John Regehr (2021), “Alive2: bounded translation validation for LLVM”, (Proceedings of the 42nd ACM SIGPLAN International Conference on Programming Language Design and Implementation. Association for Computing Machinery, New York, NY, USA, 65-79). DOI:https://doi.org/10.1145/3453483.3454030

  8. Shubhani Gupta, Abhishek Rose, and Sorav Bansal (2020), “Counterexample-guided correlation algorithm for translation validation”, (Proc. ACM Program. Lang. 4, OOPSLA, Article 221 (November 2020), 29 pages). DOI:https://doi.org/10.1145/3428289

Abstract syntax tree, 41, 69 Acceptance of input strings by automata, 148 Accepting states, 147 Access links, 447 for procedure parameters, 449 manipulating, 448 Access to nonlocal data on the stack, 443 Action-records, 346 Activation records, 431, 435 Activation trees, 432 Actual parameters, 33 Acyclic test, 818 Adapting the translation scheme, 70–71 Addresses and instructions, 366 Addresses in the target code, 518 Addressing array elements, 383 Advanced code motion techniques, 733 Advanced topics in garbage collection, 496 Affine accesses, 797 Affine and nonaffine accesses in practice, 799 Affine array indexes, 797 Affine expressions of reference variables, 686 Affine space partitions, 827 Affine transform theory, 775 Algebraic simplification and reduction in strength, 553 Algorithm for region-based analysis, 678 Algorithm for unification, 397 Algorithm overview, 646 Aliasing, 34 Allocation, 455 Ambiguous grammars, 279 Amdahl’s law, 770

Analysis part, 4 Annotated parse tree, 54, 308 Anticipated expressions, 647 Anticipation of expressions, 645 Antidependence, 709 Applications of syntax-directed translation, 320 Architecture of a transition-diagram-based lexical analyzer, 133–139 Array contraction, 880, 881 Array data-dependence analysis, 710, 812 Assembler, 3 Attribute grammar, 308 Attributes, 53 Attributes for tokens, 112–113 Attribute-value, 6 Augmented grammar, 244 Available expressions, 612, 648 Avoiding redundant gotos, 408 Axiomatic semantics, 905

Back edges and reducibility, 663 Back end, 505 Backpatching, 412 for boolean expressions, 413 one-pass code generation using, 412 Backus-naur form (BNF), 40, 191 Barrier synchronization, 772 Base array, 185 Basic blocks, 527 Basic blocks and flow graphs, 526 Basic machine model, 717 Basic mark-and-sweep collector, 473 Basic-block scheduling, 719 956 Index

Behavior of the LR parser, 250 Best-fit and next-fit object placement, 460 Better code for expressions, 104 Big-oh notation, 158 Big-step operational semantics, 907 Binary alphabet, 118 Binary translation, 22 Block structure, 27,29 Blocking, 781,873 Boolean expressions, 402 control-flow translation of, 406 Boolean values and jumping code, 410 Bottom-up methods, 61 Bottom-up parsing, 234 Bottom-up parsing of L-attributed SDD’s, 351 Boundary tags, 461 Bounds checking, 24 Branch on poison, 944 Break-, continue-, and goto-statements, 418 Break-statements, 418 Bucket headers, 364 Buffer pairs, 115 Bytecodes, 2

Cache interference, 784 Call-by-name, 34 Call-by-reference, 34 Call-by-value, 33 Calling sequences, 438 Canonical LR(1) items, 260 parsing tables, 265 parser, 266 Case-statements, 420 Causes of redundancy, 586 Changing axes, 794 Changing data layout, 781 Class variable, 25 Closure, 677 Code generation by tiling an input tree, 561 Code generator, 10,507 Code motion, 593 Code optimization, 10 Code transformations, 871 Code-generation 10,505-581 algorithm, 545 generators, 12

Code-scheduling constraints, 708 Coefficient matrix, 801 Coercion, 8,98,390 Combining incremental and copying techniques, 488 Common subexpressions, 360 Compaction of LR parsing tables, 276 Comparing costs, 484 Compile time, 25 Compiled simulation, 22 Compilers, 1 design, 15 impact on, 13 just-in-time, 2 structure of a, 4 technology, 17 Compiler transforms the program across multiple abstraction levels, 900 Compiler phases, 4,5,8 Compiler-construction tools, 11,12 Complex instruction set computer (CISC), 507 Composition, 677 Composition of transfer functions, 692 Computation operations, 512 Computing followpos, 177 Computing nullable, firstpos, and lastpos, 176 Concrete syntax tree, 69 Conditional jumps, 513 Conditional statements, 759 Conflict resolution in lex, 143 Conflicts during shift-reduce parsing, 239 Conservative collection for unsafe languages, 499 Considering communication cost, 877 Constant number of synchronizations, 849 Constant propagation, 632 Constants, 78 Constructing iteration spaces from loop nests, 784 Constructing LALR parsing tables, 267 Constructing LR(1) sets of items, 261 Constructing SLR-parsing tables, 253 Construction of an NFA from a regular expression, 158 Construction of syntax trees, 92,320 Context-free grammars, 42,196 Contiguous evaluation, 575 Control dependence, 714 Control stack, 435 Control-dependence constraints, 708 Control-flow constraints, 601, 606 of boolean expressions, 406 Controlling the order of execution, 789 Conversion of an NFA to a DFA, 152 Converting a regular expression directly to a DFA, 178-180 Copy propagation, 592 Copying collectors, 481 Creating yacc lexical analyzers with lex, 295

D DAG representation of basic blocks, 534 Dangling-else ambiguity, 282 Data abstraction, 18 Data access without nested procedures, 443 Data dependence, 709, 800 Data locality, 773 Data reuse, 800 Database query interpreters, 22 Data-dependence constraints, 708, 744 Data-dependence graphs, 719 Data-flow abstraction, 598 analysis, 598 analysis engines, 12 analysis schema, 601 optimizations, 18 problem formulation, 6889 schemas on basic blocks, 602 values, 689 values for the constant-propagation framework, 633 Dead code elimination, 536 Dead states in DFA’s, 171 Dead-code elimination, 592 Declaration(s), 31, 375, 455 Declarations part, 289 Default array, 185 Definition, 31 Definition of data dependence of array accesses, 813 Denotational semantics, 905 Dependency graph, 312 Depth of a flow graph, 664 Depth-first ordering, 659 Depth-first traversal, 57 Derivations, 44, 199 Design goals for garbage collectors, 466

Design of a lexical-analyzer generator, 166 Design of new computer architectures, 20 Design of the function getReg, 548 Deterministic finite automata (DFA), 146, 149 converting a regular expression directly to a, 178 dead states in, 171 minimizing the number of states of a, 180 DFA’s for lexical analyzers, 169 Directed acyclic graph (DAG), 534 Directed acyclic graphs for expressions, 361 Displays, 451 Distributed memory machines, 890 Distributive frameworks, 625 Division by poison, 944 Do-across loops, 741 Dominance relation, 727 Dominators, 656 Downward code motion, 728 Dynamic accesses, 802 Dynamic policy, 25 Dynamic programming algorithm, 577 Dynamic programming code-generation, 575 Dynamic scope, 25, 31 Dynamically typed languages, 466

E Edges in a depth-first spanning tree, 662 Efficiency of NFA simulation, 156 Efficiency of string-processing algorithms Efficient construction of LALR parsing tables, 271 Eliminating ambiguity, 210 Eliminating empty iterations, 838 Eliminating left recursion from SDT’s, 330 Eliminating redundant loads and stores, 551 Eliminating tests from innermost loops, 841 Eliminating unreachable code, 551 Empty set, 118 Empty string, 118 Encapsulation, 31 Ending the basic block, 546 Environment, 88, 256 Error productions, 196 Error recovery in LR parsing, 284 predictive parsing, 229 yacc, 296 Error-recovery strategies, 195 Ershov numbers, 569 Evaluating an SDD at the nodes of a parse tree, 308 Evaluating expressions with an insufficient supply of registers, 572 Evaluation judgment rules for assignment operator, 912 binary operations, 913 block operator, 915 constants, 911 control flow, 916 if-then-else, 917 sequencing operator, 914 ternary operator, 918 variable declarations, 921 variables, 911 while loop, 919 simple operations, 910 Evaluation order 512 Evaluation orders for SDD’s, 312 Evaluation rules, 902 Evolution of programming languages, 12 Execution order for loop nests, 787 Explicit access control, 31 Exploiting fully permutable loops, 871 Exploiting pipelining, 872 Extensions of regular expressions, 123

Fields in records and classes, 378 Fifth-generation language, 13 Final states, 147 Finding dependences among memory accesses, 709 Finding local common subexpressions, 534 Finding synchronization-free parallelism, 824 Finite automata, 146 First-generation languages, 13 Firstpos(n), 175 Flow graphs, 530 Flow-of-control optimizations, 552 Flow-of-control statements, 403, 415 Followpos(p), 175 Formal parameters, 33 Formally specifying evaluation rules through inference rules, 902 Foundations of data-flow analysis, 619

Fourier-motzkin elimination, 793 Fourth-generation languages, 13 Freeze opcode, 948 Full redundancy, 645 Fully permutable loops, 860 Function calls, 425 Function GOTO, 246 Function types, 425 Functions computed from the syntax tree, 175

Garbage collecting a car, 493 Garbage collection, 465 advanced topics in, 496 generational, 490 incremental, 485 introduction to, 465 parallel and concurrent, 496 precision of, 486 short-pause, 485 GCD test, 814 General theory, 863 General tree matching, 567 Generating code from labeled expression trees, 570 Generational garbage collection, 490 Geometric interpretation of parallelization, 846 GetNextToken, 110 Global code scheduling, 725 Global common subexpressions, 590, 639 Global correction, 196 Global register allocation, 554 Global scheduling, 725 Global scheduling algorithms, 730 Goals and constraints of software pipelining, 742 Grammars, 42 Granularity of parallelism, 770 Greatest lower bounds, 621 Group reuse, 808 Grouping of phases into passes, 11

Handle pruning, 235 Handling nonreducible flow graphs, 683 Hardware support for software pipelining, 759 Hardware synthesis, 22 Hash function, 364 Heap management, 454 Heap storage, 431 Height of a semilattice, 624 Heuristics for solving integer linear programs, 817 Hierarchical reduction, 759 Hierarchical time, 853, 855 Higher precedence, 49 High-level programming language, 17 Hoisting transformations in LLVM, 946

Ideal solution, 629 Identifier, 28 Immediate left recursion, 212 Implementing L-attributed SDD’s, 340 Implementing the lookahead operator, 171 Implementing write barriers, 488 Implications of triggering UB on branch-on-poison, 945 Implications of UB semantics for compiler optimization, 929 Important states of an NFA, 173 Improvements to the pipelining algorithms, 755 Incorporating symbolic constants, 789 Incremental garbage collection, 485 Incremental reachability analysis, 487 Incremental translation, 382 Independent-variables test, 817 Indirect triples, 370 Induction variables and reduction in strength, 594 Induction variables, 686 Inference rules, 902 Inheritance of properties, 18 Inherited and synthesized attributes, 306 Inherited attribute, 306 Input buffering, 115 Input to the code generator, 507 Instruction - level parallelism, 705 Instruction pipelines and branch delays, 706 Instruction selection, 508 Instruction selection by tree rewriting, 559 Integer linear programming, 814 Interaction with dynamic schedulers, 734 Interleaving inner loops in a parallel loop, 884 Interleaving statements in a parallel loop, 885 Intermediate code, 40 Intermediate code for procedures, 423 Intermediate-code generation, 9, 91, 359-427

Interpretation of the results, 637 Interpreter, 1 Interprocedural analysis, 711 Issues in the design of a code generator, 506 Issues with nested procedures, 444 Items and the LR(0) automaton, 242 Iteration spaces, 784 Iterative algorithm for general frameworks, 626 Iterative algorithm for reaching definitions, 607

Java virtual machine (JVM), 507 Jumping code, 402 Just-in-time compilers, 2

Key, 88 Keywords, 79

LALR parsing table, 267, 269 LALR(1) collection, 269 Language, 118 Operations on, 119 Language processors, 1-4 Language with nested procedure declarations, 444 Lastpos(n), 175 Lattice diagrams, 622 L-attributed definitions, 315 SDD’s, 340 and LL parsing, 346 translations, 306 Lazy-code-motion algorithm, 646 problem, 644 Left factoring, 214 Left recursion, 67 Lex compiler, 139 Lex programs, 140 Lexeme, 76, 111 LexemeBegin, 169 Lexical analysis, 75, 109-189 Lexical analysis or scanning, 5 Error-recovery strategies, 195 Ershov numbers, 569 Evaluating an SDD at the nodes of a parse tree, 308 Evaluating expressions with an insufficient supply of registers, 572 Evaluation judgment rules for assignment operator, 912 binary operations, 913 block operator, 915 constants, 911 control flow, 916 if-then-else, 917 sequencing operator, 914 ternary operator, 918 variable declarations, 921 variables, 911 while loop, 919 simple operations, 910 Evaluation order 512 Evaluation orders for SDD’s, 312 Evaluation rules, 902 Evolution of programming languages, 12 Execution order for loop nests, 787 Explicit access control, 31 Exploiting fully permutable loops, 871 Exploiting pipelining, 872 Extensions of regular expressions, 123

Fields in records and classes, 378 Fifth-generation language, 13 Final states, 147 Finding dependences among memory accesses, 709 Finding local common subexpressions, 534 Finding synchronization-free parallelism, 824 Finite automata, 146 First-generation languages, 13 Firstpos(n), 175 Flow graphs, 530 Flow-of-control optimizations, 552 Flow-of-control statements, 403, 415 Followpos(p), 175 Formal parameters, 33 Formally specifying evaluation rules through inference rules, 902 Foundations of data-flow analysis, 619

Fourier-motzkin elimination, 793 Fourth-generation languages, 13 Freeze opcode, 948 Full redundancy, 645 Fully permutable loops, 860 Function calls, 425 Function GOTO, 246 Function types, 425 Functions computed from the syntax tree, 175

Garbage collecting a car, 493 Garbage collection, 465 advanced topics in, 496 generational, 490 incremental, 485 introduction to, 465 parallel and concurrent, 496 precision of, 486 short-pause, 485 GCD test, 814 General theory, 863 General tree matching, 567 Generating code from labeled expression trees, 570 Generational garbage collection, 490 Geometric interpretation of parallelization, 846 GetNextToken, 110 Global code scheduling, 725 Global common subexpressions, 590, 639 Global correction, 196 Global register allocation, 554 Global scheduling, 725 Global scheduling algorithms, 730 Goals and constraints of software pipelining, 742 Grammars, 42 Granularity of parallelism, 770 Greatest lower bounds, 621 Group reuse, 808 Grouping of phases into passes, 11

Handle pruning, 235 Handling nonreducible flow graphs, 683 Hardware support for software pipelining, 759 Hardware synthesis, 22 Hash function, 364 Heap management, 454 Heap storage, 431 Height of a semilattice, 624 Heuristics for solving integer linear programs, 817 Hierarchical reduction, 759 Hierarchical time, 853, 855 Higher precedence, 49 High-level programming language, 17 Hoisting transformations in LLVM, 946

Ideal solution, 629 Identifier, 28 Immediate left recursion, 212 Implementing L-attributed SDD’s, 340 Implementing the lookahead operator, 171 Implementing write barriers, 488 Implications of triggering UB on branch-on-poison, 945 Implications of UB semantics for compiler optimization, 929 Important states of an NFA, 173 Improvements to the pipelining algorithms, 755 Incorporating symbolic constants, 789 Incremental garbage collection, 485 Incremental reachability analysis, 487 Incremental translation, 382 Independent-variables test, 817 Indirect triples, 370 Induction variables and reduction in strength, 594 Induction variables, 686 Inference rules, 902 Inheritance of properties, 18 Inherited and synthesized attributes, 306 Inherited attribute, 306 Input buffering, 115 Input to the code generator, 507 Instruction - level parallelism, 705 Instruction pipelines and branch delays, 706 Instruction selection, 508 Instruction selection by tree rewriting, 559 Integer linear programming, 814 Interaction with dynamic schedulers, 734 Interleaving inner loops in a parallel loop, 884 Interleaving statements in a parallel loop, 885 Intermediate code, 40 Intermediate code for procedures, 423 Intermediate-code generation, 9, 91, 359-427

Interpretation of the results, 637 Interpreter, 1 Interprocedural analysis, 711 Issues in the design of a code generator, 506 Issues with nested procedures, 444 Items and the LR(0) automaton, 242 Iteration spaces, 784 Iterative algorithm for general frameworks, 626 Iterative algorithm for reaching definitions, 607

Java virtual machine (JVM), 507 Jumping code, 402 Just-in-time compilers, 2

Key, 88 Keywords, 79

LALR parsing table, 267, 269 LALR(1) collection, 269 Language, 118 operations on, 119 Language processors, 1-4 Language with nested procedure declarations, 444 Lastpos(n), 175 Lattice diagrams, 622 L-attributed definitions, 315 SDD’s, 340 and LL parsing, 346 translations, 306 Lazy-code-motion algorithm, 646 problem, 644 Left factoring, 214 Left recursion, 67 Lex compiler, 139 Lex programs, 140 Lexeme, 76, 111 LexemeBegin, 169 Lexical analysis, 75, 109-189 Lexical analysis or scanning, 5 Lexical analyzer, 80, 957 architecture of a transition-diagram-based, 133-139 DFA’s for, 169 role of, 109 Lexical errors, 114, 194 Lexical scope, 25 Lexical versus syntactic analysis, 209 Lexical-analyzer generator, 109 Linker, 3 List scheduling, 719 List scheduling of basic blocks, 721 Live-variable analysis, 610 LL(1) grammars, 223 LLVM semantics for the poison value, 943 Load operations, 512 Loader, 3 Loading-from and storing-to poison pointer, 946 Locality in programs, 457 Locality optimizations, 880 Logical errors, 194 Lookahead operator, 144 Lookahead symbol, 62 Loop unrolling, 732 Loop-bounds generation, 793 Loop-invariant expressions, 641 Loop-level parallelism, 771 Loop-residue test, 819 Loops, 532 Loops in flow graphs, 656 Low overhead, 456 LR grammar, 242 LR parsers, 260 LR parsing, 241 LR parsing table, 249 LR(0) automaton, 247 LR(1) grammar, 266 LR-parser configurations, 250 LR-parsing algorithm, 248 L-values, 97

Machine-independent optimizations, 585-702 Machine instructions for copy statements, 545 Machine instructions for operations, 545 Managing and coalescing free space, 461 Managing register and address descriptors, 546 Managing trains, 493

Manifest constants, 140 Manipulating access links, 448 Manual deallocation requests, 462 Mark-and-compact garbage collectors, 478 Marker nonterminals, 327 Markers, 353 Matrix formulation of inequalities, 788 Matrix multiply, 778 Matrix-multiplication algorithm, 778 Maximum fixedpoint versus the MOP solution, 630 Meaning of a data-flow solution, 628 Meet for the constant-propagation framework, 633 Meet of transfer functions, 693 Meet operator, 677 Meet-over-paths solution, 630 Memoization, 820 Memory hierarchies, 19, 20 Memory hierarchy of a computer, 456 Memory manager, 455 Memory store, 908 Memoryleak error, 463 Memory-management tools, 24 Minimizing the number of states of a DFA, 180 Modeling in compiler design and implementation, 15 Modular resource reservation, 743 Modular variable expansion, 756 Monotone frameworks, 625 Monotonicity of the constant-propagation framework, 635 Multi-instruction-issue processors, 891 Multiple instruction issue, 707 Multiprocessors, 768

Name equivalence, 374 Natural loops, 665 Necessary assumptions about transfer functions, 677 Need for semantics at each abstraction level, 901 Need for specifying programming language semantics, 900 Neighborhood compaction, 733 Nesting depth, 446 NewStates, 156 Next-use information, 529 Non-context-free language constructs, 215 Nondeterministic finite automata (NFA), 146 conversion of, 152 important states of, 173 pattern matching based on, 169 simulation of, 156 Nondistributivity of the constant-propagation framework, 635 Nonrecursive predictive parsing, 227 Nonterminals, 42, 197 Notational conventions, 198 Null space of a matrix, 804 Nullable(n), 175

Object ownership, 464 Object-oriented language, 13 OldStates, 156 One-pass code generation using backpatching, 412 On-the-fly code generation, 344 Operational semantics, 904 Operations on languages, 119 Operations within expressions, 380 Oplogical sort of the graph, 314 Optimal code generation for expressions, 569 Optimization of basic blocks, 533 Optimization of DFA-based pattern matchers, 173 Optimization using the memory hierarchy, 458 Optimizations, 781 Optimizations for computer architectures, 19 Optimizing for parallelism and locality, 765-896 Optimizing mark-and-sweep, 477 Ordering the evaluation of attributes, 314 Other reference variables, 687 Other uses of affine transforms, 890 Output dependence, 709 Overloading, 98 Overloading of functions and operators, 391 Overview of a region-based analysis, 676

Padding, 376, 430 Panic mode, 494 Panic-mode recovery, 195 Parallel and concurrent garbage collection, 496 Parallelism, 19 Parallelism in applications, 770

Parallelism with minimum synchronization, 876 Parallelization algorithm, 855 Parameterized function compositions, 693 Parametric polymorphism, 392 Parse tree, 45, 201 Parser, 74 role of, 192 Parser generators, 12, 288 Parser-stack implementation of postfix SDT’s, 328 Parsing, 8, 45, 47, 61 predictive, 64 recursive-descent, 64 top-down, 62 Partial object relocation, 498 Partial order for a semilattice, 620 Partial orders, 620 Partial redundancy elimination, 586 Partial redundancy, 645 Partial-collection basics, 489 Partially redundant expressions, 642 Partial-redundancy elimination, 639 Partition interleaving, 883 Pattern, 111 Pattern matching based on NFA’s, 169 Pattern matching by parsing, 565 Peephole optimization, 550 Performance metrics, 467 Phase ordering between register allocation code scheduling, 713 Phrase-level error recovery, 231 Phrase-level recovery, 196 Pipelined execution, 707 Pipelining, 857 Pipelining fully permutable loops, 860 Pointer assignments and procedure calls, 540 Pointer-alias analysis, 710 Poison bits, 715 Poison values, 937 Poison-free values, 948 Polymorphic functions, 392 Postfix, 74 Postfix notation, 53 Postfix SDT, 327 Postfix translation schemes, 327 Postorder traversal, 58 Postponable expressions, 651 Precedence and associativity to resolve conflicts, 280 Precedence of operators, 48 Precision of incremental collection, 486 Predicated execution, 716 Predictive parser, 66 Predictive parsing, 64 Prefetching, 715, 892 Preorder traversal, 58 Preprocessing steps, 647 Preprocessor, 3 Primitive code motion, 725 Principal sources of optimization, 586 Prioritized topological orders, 722 Problems with manual deallocation, 463 Procedures for the nonterminals, 72-73 Processor architectures, 706 Product lattices, 623 Production, 42 Program and instruction costs, 515 Program dependence graph (PDG), 851 Program efficiency, 455 Program translations, 21 Program-dependence graphs, 851 Programming conventions and tools, 464 Programming errors, 194 Programming language basics, 24 Programming language semantics, 899 Programming languages, 1 Putting it all together, 888

Quadruples, 368 Qualified names, 28 Quicksort, 447

Rank of a matrix, 803 Reachability, 468 Reaching definitions, 603 Reassembling basic blocks from DAG’s, 540 Recognition of reserved words and identifiers, 131 Recognition of tokens, 128 Recognizing keywords and identifiers, 79 Recursive descent, 61 Recursive-descent parsing, 219, 341, 64 Reduced instruction set computer (RISC), 21, 507 Reducing fragmentation, 459 Reductions, 234 Reference counting, 464

Reference counting garbage collectors, 470 Region hierarchies for reducible flow graphs, 673 Region-based algorithm, 465, 695 analysis, 671 scheduling, 730 symbolic analysis, 693 Regions, 672 Register allocation, 510 and assignment, 554 and code generation, 740 Register allocation by graph coloring, 558 Register and address descriptors, 544 Register assignment for outer loops, 557 Register transfer level (RTL), 22 Regular definitions, 122 Regular expressions, 120 Remembered sets, 493 Removal of white space and comments, 77 Representation of array references, 538 Representation of flow graphs, 530 Representative grammars, 193 Representing blocks in syntax trees, 95 Reserved words, 79 Resource constraints, 708 Resource-reservation table, 717 Return sequence, 438 Reuse in innermost blocks, 883 Role of the lexical analyzer, 109 Role of the parser, 192 Routines for semantic checking, 566 Row-by-row parallelization, 780 Rules for type checking, 388 Run time, 25 Run-time addresses for names, 524 Run-time environments, 429 R-values, 97

S-attributed definitions, 315 Scanner generators, 12 Scheduling acyclic data-dependence graphs, 746 Scheduling cyclic dependence graphs, 748 Science of building a compiler, 15 Science of code optimization, 15 Scopes, 86 Scripting languages, 13 SDT’s for L-attributed definitions, 333 SDT’s with actions inside productions, 329 Search for extra-terrestrial intelligence (SETI), 770 Second-generation language, 13 Self-spatial reuse, 806 Semantic actions, 326 Semantic analysis, 8 Semantic analyzer, 8 Semantic errors, 194 Semantic rules with controlled side effects, 317 Semantic rules, 54 Semantics, 40 Semantics for the poison value, 940 Semantics-preserving transformations, 588 Semilattices, 619 Sentinels, 117 Sequences of declarations, 377 Serial execution of the matrix multiplication, 779 Seven primitive affine transforms, 844 Shift-reduce parsing, 236 Short-circuit code, 402 Short-pause garbage collection, 485 Signature of method, 31 Signed integer overflow, 930 Simple code generator, 543 Simple code-generation algorithm, 835 Simple incremental tracing, 486 Simple syntax-directed translator, 39-107 Simple target machine model, 512 Simplifying the translator, 73 Simulation of an NFA, 156 Single instruction multiple data (SIMD), 890 Single productions, 70 Single program multiple data (SPMD), 772 Single representation, 79 SLR-parsing tables, 253 Software pipelining, 735 Software pipelining of loops, 738 Software productivity tools, 23 Software-pipelining algorithm, 746 Solution to data-flow problem, 692 Solving general integer linear programs, 820 Solving space-partition constraints, 832 Solving time-partition constraints by Farkas’ lemma, 868 Source language, 1 Source-code transforms, 844 Sources of redundancy, 639 Source-to-source translator, 4

Space efficiency, 455 Space-partition constraints, 828 Specification of tokens, 118 Specifying programming language semantics, 904 Speculative execution support, 715 Speed of convergence of iterative data-flow algorithms, 667 Stack allocation, 521 Stack allocation of space, 432 Stack storage, 431 Start state, 147 State, 26 Static access, 802 Static allocation, 519 Static checking, 92, 97 Static policy, 25 Static scope, 25, 27 Static single-assignment form (SSA), 371 Static versus dynamic storage allocation, 431 Storage layout for local names, 375 Storage organization, 429 Storage-related dependences, 709 Store operations, 512 Storing poison to memory, 946 Strings, 118 Structure of a compiler, 4-12 a type, 324 a programs, 140 the generated analyzer, 166 the LR parsing table, 249 Structured query language (SQL), 22 Successive over-relaxation (SOR), 859 Supporting C-routines, 292 Switch-statements, 420 syntax-directed translation of, 421 translation of, 421 Symbol tables, 4, 85, 425 Symbolic analysis, 685 Symbol-table management, 11 Synchronization between parallel loops, 849 Synchronizing tokens, 195 Syntactic checking, 97 Syntactic errors, 194 Syntax, 40, 42 Syntax analysis, 8, 191-301 Syntax error handling, 194 Syntax trees, 8, 41, 70, 320 abstract, 69 concrete, 69 construction of, 92 for expressions, 96 for statements, 93 representing blocks in, 95 Syntax-directed definition (SDD), 56, 306 Syntax-directed definition associates, 54 Syntax-directed translation, 40, 52, 305–357 engines, 12 of switch-statements, 421 Syntax-directed translation schemes (SDT), 326 Synthesis part, 4 Synthesized attribute, 54, 306 Synthesize-records, 346

Target language, 1, 512 Target program, 507 Temporal locality of computed data, 880 Terminals, 42, 197 Third-generation language, 13 Three-address code, 9, 99, 365 Three-address instructions, 99 Time-partition constraints, 864 Token-name, 6 Tokens, 41, 111 attributes for, 112–113 recognition of, 128 specification of, 118 synchronizing, 195 Top-down methods, 61 Top-down parsing, 62, 217 Topological sort, 314 Trace-based collection, 473 Tradeoff between register usage and parallelism, 711 Trading communication for synchronization, 877 Trading time for space in DFA simulation, 184 Train algorithm, 491 Transfer equations for reaching definitions, 605 Transfer function of a statement, 690 Transfer functions, 601 for the constant-propagation framework, 634 Transition diagrams, 129 Transition function, 147 Transition graph, 147 Transition tables, 147 Translation during recursive-descent parsing, 341

Translation of array references, 384 expressions, 101, 380 statements, 100 switch-statements, 421 Translation rules part, 290 Translation scheme, 53, 58 Translator for simple expressions, 69 Tree traversals, 57 Tree-translation schemes, 559 Triples, 369 indirect, 370 True dependence, 709 Turnstile operator, 902 Type checking, 8, 23, 97, 98, 388, 425 Type conversions, 389 Type equivalence, 374 Type expressions, 373 Type inference, 392 Type synthesis, 388 Type-based strict-aliasing (TBSA), 931 Types and declarations, 372

UB associated with array indexing, 928 with integer overflow, 929 Unconditional jumps, 513 Undefined behaviour in IR, 933, 934 Undefined behaviour semantics, 927–952 Unimodular transforms, 844 Updating data dependences, 729 Upward and downward code motion, 728 Upward code motion, 727 Usage counts, 555 Use of algebraic identities, 537 Use of lex, 139 Use of machine idioms, 553 Used expressions, 653

Value, 88 Value number, 363 Value-number method for constructing DAG’s, 362 Values in the language, 908 Variable, 28 Index 965

Variable environment, 908 Variable-length data on the stack, 440 Variants of syntax trees, 360 Vector and SIMD instructions, 891 Verifying the language generated by a grammar, 204 Very high-speed integrated circuit hardware description language (VHDL), 22 Very long instruction word (VLIW), 19, 21, 707 Viable prefixes, 256 Viable-prefix property, 195 Von neumann language, 13

W Wavefronting, 873 Weak references, 500 Wilderness chunk, 460 Writing a grammar, 209

Y Yacc lexical analyzers with lex, 295 Yacc specification, 292 Yacc with ambiguous grammars, 292


← node-book_compilers-principles-techniques-and-tools_chapter-11-optimizing-for-parallelism-and-locality | node-book_compilers-principles-techniques-and-tools