Docsity

Python Assignment 5: Variables and Control Flow - Prof. Jeremy G. Siek, Assignments of Electrical and Electronics Engineering

Toggle sidebar
bg1
Assignment 5: variables and control flow
ECEN 4553 & 5013, CSCI 4555 & 5525
Prof. Jeremy G. Siek
October 7, 2007
(This assignment was too long. For next year, introduce the new language features and do
iterative type analysis in the first week and do SSA conversion in the second week. -Jeremy)
(Break and continue are extra hard to deal with so I’m removing them. -Jeremy)
The main concepts for this week are
•Variable binding.
•Using recursive functions to analyze the program.
•Translating from one intermediate language to another.
•Extending type analysis to deal with variables and control flow. This uses static single-
assignment form and iterative type analysis.
1 Implementing P2
1.1 Syntax of P2
identifier ::= # see the Python Reference Manual
expression ::= identifier
simple_statement ::= "pass"
| (identifier "=")+ expression
| expression
compound_statement ::= "if" expression ":" suite "else" ":" suite
| "while" expression ":" suite
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
statement ::= stmt_list NEWLINE | compound_stmt
suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
Figure 1: Concrete syntax for the P2subset of Python. (In addition to the syntax of P1.)
Figure 1 shows the concrete syntax for the subset P2. This subset adds variables, assignment,
and control flow.
1.2 Semantics of P2and compiling to C
Compiling the variables and assignment is the more challenging aspect because in Python, there
are no variable declarations, as there are in C. For example, the following program assigns the
value 3to the variable xand then prints out its contents.
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Python Assignment 5: Variables and Control Flow - Prof. Jeremy G. Siek and more Assignments Electrical and Electronics Engineering in PDF only on Docsity!

Assignment 5: variables and control flow

ECEN 4553 & 5013, CSCI 4555 & 5525

Prof. Jeremy G. Siek

October 7, 2007

(This assignment was too long. For next year, introduce the new language features and do iterative type analysis in the first week and do SSA conversion in the second week. -Jeremy) (Break and continue are extra hard to deal with so I’m removing them. -Jeremy) The main concepts for this week are

  • Variable binding.
  • Using recursive functions to analyze the program.
  • Translating from one intermediate language to another.
  • Extending type analysis to deal with variables and control flow. This uses static single- assignment form and iterative type analysis.

1 Implementing P 2

1.1 Syntax of P 2

identifier ::= # see the Python Reference Manual expression ::= identifier simple_statement ::= "pass" | (identifier "=")+ expression | expression compound_statement ::= "if" expression ":" suite "else" ":" suite | "while" expression ":" suite stmt_list ::= simple_stmt (";" simple_stmt)* [";"] statement ::= stmt_list NEWLINE | compound_stmt suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT

Figure 1: Concrete syntax for the P 2 subset of Python. (In addition to the syntax of P 1 .)

Figure 1 shows the concrete syntax for the subset P 2. This subset adds variables, assignment, and control flow.

1.2 Semantics of P 2 and compiling to C

Compiling the variables and assignment is the more challenging aspect because in Python, there are no variable declarations, as there are in C. For example, the following program assigns the value 3 to the variable x and then prints out its contents.

x = 3 print x 3

The analogous program in C would need to first declare the variable x and then assign to it as follows.

int x; x = 3; printf("%d\n", x); The compiler needs to analyze the Python program and figure out where to insert the variable declarations in the output C program.

Exercise 1.1. (Nothing to turn in here.) Read the sections of the Python Reference Manual that apply to P 2 : 4.1 Naming and binding 6.1 expression statements, 6.3 assignment, 6.4 pass, 6. break, 6.11 continue, 7.1 if, and 7.2 while.

Exercise 1.2. (This should be included in what you turn in.) Write five programs in the P 2 subset of Python that help you understand the language. Look for corner cases or unusual aspects of the language to test in your programs. Run the programs using the standard python interpreter. Add your test programs to the test directory.

Figure 2 shows the Python classes for the P 2 AST nodes. The If class has two attributes, the tests attribute that is a sequence of pairs, where the first item is an expression (the condition) and the second item is a statement. The else attribute is a statement. The While class has the attribute test (an expression), body (a statement), and else (a statement). In the Assign class, the nodes attribute contains a list of left-hand sides (because assignment may be chained, as in a = b = 2) where each left-hand side is represented by a AssName node (There are other kinds of assignment nodes in Python, but we don’t have to worry about them yet.) The expr attribute of Assign is the right-hand side expression. You can ignore the flags attribute of AssName for now, as it is used to distinguish between the use of AssName for assignment and variable deletion. In the previous chapters, we output the C code directly from the Python AST. That approach works well when there is a close node-to-node correspondence between the Python AST nodes and the C code to be generated. However, for this chapter we need to deal with variables: variables must be declared before they are used in C whereas in Python there are no variable declarations. Thus, we need to add in variable declaration nodes before generating the C code. We define a new AST node VarDecl.

class VarDecl(Node): def init(self, name, type): self.name = name self.type = type

Figure 3 shows the architecture of the compiler for this chapter.

Exercise 1.3. (Don’t turn this in yet.) Write a function that analyzes a P 2 program and builds up a new program with VarDecl nodes inserted at the appropriate locations for every variable that is used in the program. You will find the Python sets module helpful.

Exercise 1.4. (Don’t turn this in yet.) Extend your Python to C compiler to handle P 2. Test your compiler against the new test programs for P 2 in addition to the tests for P 0 and P 1. To keep things

simple with respect to type analysis, just use the pyobj union type for all variables. In Section 2 of this assignment you will be doing more sophisticated type analysis to improve on this. For extra credit, write the parser yourself using PLY, building on your parser for P 1. You will need to handle the peculiar indentation rules of Python. Look in the PLY distribution, in the directory example/GardenSnake, for code that will help you do this.

2 Type analysis and specialization for P 2

In Section 1 we simply used pyobj as the type for every variable. However, this approach produces poor code. For example, the variable x in the following code is assigned an integer, so we should generate C code with x declared as an integer.

x = 4 print x + 5

The following is the C code generated from Section 1 compared to what we would like to produce.

// Generated from the compiler for Section 1 pyobj x; x = make_int(4); print_any(add(x, make_int(5)));

// Goal for Section 2 int x; x = 4; printf("%d\n", x + 3); Type analysis in the presence of variables is complicated because, in Python, a variable may be assigned values of different types. In the following code, variable x is first assigned an integer and later assigned a floating point number.

x = 3 y = x + 1 x = x + 0. z = x / 2 One way to handle the above example is the split the variable x into multiple variables, each playing the role of x in different regions of the program. The following shows the above code transformed to split variable x into variables x 0 and x 1.

x_0 = 3 y = x_0 + 1 x_1 = x_0 + 0. z = x_1 / 2

Now the variable x 0 can be given the type int and x 1 can be given the type float. This resulting code is in what is called Static Single Assignment (SSA) form [1, 3, 5] because each variable is only assigned to at a single place in the code. (There is a chapter on SSA form in the recommended textbook [2].) To convert a program to SSA form you traverse the program, and when you encounter an assignment, you replace it with an assignment to a new variable with its version number incre- mented by one. For each variable, you maintain a dictionary that maps each variable to its current version number. When you encounter a variable in an expression, you replace the variable with

its name with the version number appended. So, for example, when you see x = 3 you transform it to x_0 = 3 and add x_0 to the dictionary. When you see x + 1 you transform it to x_0 + 1. For straight-line code in SSA form, type analysis is straightforward. You simply maintain a dictionary mapping variables to their type.

  1. When you encounter a variable in an expression, look up the variable’s type in the dictionary and set the type attribute. If the variable is not in the dictionary, then return the ’undefined’ type.
  2. When you encounter an assignment, perform type analysis on the right-hand side and then add to the dictionary an entry mapping the assigned variable to the type of the right-hand side.

Here’s the C code that can be generated from the above. We are able to give each variable a specific type (not pyobj).

int x_0; int y; float x_1; float z; x_0 = 3; y = x_0 + 1; x_1 = x_0 + 0.14159; z = x_1 / 2; The language P 2 also includes if statements and while loops, which introduces some com- plication in the SSA form and makes the type analysis more difficult. Consider the following program in which the variable x is assigned values of different types in two branches of the if.

if randint(0,1): x = 42 else: x = 3. print x

SSA form deals with if statements by inserting a φ node following the if for each variable that is assigned in the different branches. The φ expression returns the value of the variable correspond- ing to the branch that was actually taken at runtime.

if randint(0,1): x_0 = 42 else: x_1 = 3. x_2 = φ(x_0,x_1) print x_

The following C code is generated from the above. The φ expression is implemented by adding an assignment to x 2 at the end of each branch. Even with the SSA transformation, we still have to give x 2 the type pyobj because we just don’t know exactly what type it will hold at runtime.

int x_0; float x_1; pyobj x_2;

if (randint(0,1)) {

of the analysis, we create a dictionary that maps all variables to the type undefined. As the anal- ysis iterates the variables will be updated with better approximations. Let F represent the change that each pass makes to the dictionary, so if d 0 is the initial dictionary, d 1 = F (d 0 ) and in general after the ith iteration di = F (di− 1 ).

undefined

int float bool

pyobj

Figure 4: Types arranged according to information content (more informative is higher).

The next challenge is to figure out when to stop making passes over the AST, and how to ensure that we can stop after a finite number of steps. We can stop iterating the analysis when the results no longer change. That is, when F (di) = di. The dictionary di is called the fixed point of F. To ensure that we eventually reach a fixed point, each pass must either improve or leave untouched the approximation for each variable, and our lattice must not have any infinitely ascending chains, which is easy to see is not the case by looking at Figure 4. If a pass were to worsen the approximation, then the iterations could vacillate back and forth forever. Let v be the less or equally informative relation on types, where some type τ 1 v τ 2 if there is a line connecting τ 1 to τ 2 in Figure 4, with τ 1 lower than τ 2 , or if τ 1 and τ 2 are the same type. So, for example, undefined v int, int v pyobj, and int v int. We can extend the informative relation to dictionaries by saying that some dictionary d 1 is less or equally informative than dictionary d 2 , written d 1 v d 2 , if for every variable x in d 1 , d 1 [x] v d 2 [x]. Now, to ensure that the approximation improves with every iteration, we will require that whenever the input to F increases (or stays the same), then the output also increases (or stays the same). That is, if for some d and d′, d v d′, then F (d) v F (d′). This property is called monotonicity. Now, in the initial dictionary d 0 , every variable assigned the undefined type, which is the bottom of the type lattice. So the first iteration will result in a dictionary d 1 that is at least as informative as d 0 , i.e. d 0 v d 1. If d 0 = d 1 then we have already found the fixed point of F and we are done. Otherwise, we apply F again. Because d 0 v d 1 then F (d 0 ) v F (d 1 ) by the monotonicity of F , so we have d 1 v d 2. We can continue this process until we can’t go higher in the lattice (the lattice does not have infinitely ascending chains) and have therefore reached the fixed point. The function F is determined by the program and how we propagate types through the various operations. For each operation, such as addition, we have corresponding rules for what the return type should be given the types of the arguments. Figure 6 shows the rules for addition. To ensure that F is monotone, we need each of the typing rules also be monotone. Let’s check that the typing rule for addition is monotonic. Suppose that the inputs to an addition go from being (int,int) to (int,pyobj). Then the output goes from int to pyobj.

Exercise 2.1. (Don’t turn this in.) Check two more combinations of inputs to addition to make sure the output does not decrease. Look at two more operations, such as less than comparison and if expressions.

d 0

d 1 =F(d 0 )

d 2 =F(d 1 )

d 0 ⊑ d 1 because anything is as good or better than undefined

Because d 0 ⊑ d 1 , we have F(d 0 ) ⊑ F(d 1 ) by the monotonicity of F

d 3 =F(d 2 ) Because d 1 ⊑ d 2 , we have F(d 1 ) ⊑ F(d 2 ) by the monotonicity of F

di=F(di) (^) Fixed point

Figure 5: The monotonicity of F ensures that the process reaches a fixed point.

  • undefined int bool float pyobj undefined undefined undefined undefined undefined undefined int undefined int int float pyobj bool undefined int int float pyobj float undefined float float float pyobj pyobj undefined pyobj pyobj pyobj pyobj

Figure 6: Type rule for addition.

[5] R. Cytron, J. Ferrante, B. K. Rosen, M. N. Wegman, and F. K. Zadeck. Efficiently computing static single assignment form and the control dependence graph. ACM Trans. Program. Lang. Syst., 13(4):451–490, 1991.

[6] B. Davey and H. Priestley. Introduction to Lattices and Order. Cambridge University Press, 2nd edition, 2002.

[7] G. A. Kildall. A unified approach to global program optimization. In POPL ’73: Proceedings of the 1st annual ACM SIGACT-SIGPLAN symposium on Principles of programming languages, pages 194–206, New York, NY, USA, 1973. ACM Press.