p  Compilers 

Principles,  Techniques,  <§  Tools 

Second  Edition 

Second 
Edition 

Compilers 

Principles,  Techniques,  &  Tools 

Second  Edition 

Alfred V. Aho 
Columbia  University 

Monica S.  Lam 
Stanford  University 

Ravi  Sethi 
Avaya 

Jeffrey  D.  Ullman 
Stanford  University 

Boston  San  Francisco  New  York 
London  Toronto  Sydney  Tokyo  Singapore  Madrid 
Mexico  City  Munich  Paris  Cape Town  Hong Kong  Montreal 

Publisher 
Executive  Editor 
Acquisitions  Editor 
Project  Editor 
Associate  Managing  Editor 
Cover  Designer 
Digital  Assets  Manager 
Media  Producer 
Senior  Marketing  Manager 
Marketing  Assistant 
Senior  Author  Support/ 

Technology  Specialist 

Senior  Manufacturing  Buyer 

Cover  Image 

Greg  Tobin 
Michael  Hirsch 
Matt  Goldstein 
Katherine  Harutunian 
Jeffrey  Holcomb 
Joyce  Cosentino  Wells 
Marianne  Groth 
Bethany  Tidd 
Michelle  Brown 
Sarah  Milmore 

Joe  Vetere 
Carol  Melville 

Scott Ullman  of Strange  Tonic  Productions 
(www. strangetonic.com) 

Many  of the  designations  used  by  manufacturers  and  sellers  to  distinguish  their 
products  are  claimed  as  trademarks.  Where those  designations  appear in this 
book,  and Addison-Wesley was  aware  of a trademark  claim,  the  designations 
have been printed  in  initial  caps  or  all  caps. 

This  interior  of this  book  was  composed  in  LATEX. 

Library  of Congress  Cataloging-in-Publication  Data 

Compilers  :  principles,  techniques,  and tools / Alfred V.  Aho  ...  [et al.].  ~ 2nd ed. 

p.  cm. 

Rev.  ed.  of:  Compilers,  principles,  techniques,  and tools  / Alfred V.  Aho,  Ravi 

Sethi,  Jeffrey D.  Ullman.  1986. 

ISBN 0-321-48681-1  (alk.  paper) 
1.  Compilers  (Computer programs)  I.  Aho, Alfred V.  II.  Aho, Alfred V. 
Compilers, principles, techniques,  and tools. 

QA76.76.C65A37  2007 
005.4'53~dc22 

2006024333 

Copyright  ©  2007  Pearson Education,  Inc.  All  rights  reserved.  No  part  of this 
publication may be  reproduced,  stored  in  a retrieval  system,  or transmitted,  in 
any  form or by  any means,  electronic,  mechanical,  photocopying,  recording,  or 
otherwise,  without the  prior written permission  of the  publisher.  Printed  in  the 
United  States  of  America.  For  information  on  obtaining  permission  for  use  of 
material  in  this  work,  please  submit  a written request to  Pearson  Education, 
Inc.,  Rights  and Contracts  Department,  75  Arlington  Street,  Suite 300,  Boston, 
MA  02116,  fax your request to  617-848-7047,  or  e-mail  at 
http://www.pearsoned.com/legal/permissions.htm. 

2 3 4 5 6 7 89  10—CW—10  09  08  07  06 

Preface 

In  the  time  since  the  1986  edition  of  this  book,  the  world  of  compiler  design 
has  changed  significantly.  Programming  languages  have  evolved  to  present  new 
compilation  problems.  Computer  architectures  offer  a  variety  of  resources  of 
which  t he  compiler  designer  must  take  advantage.  Perhaps  most  interestingly, 
t he  venerable  technology  of  code  optimization  has  found  use  outside  compilers. 
It  is  now  used  in  tools  t h at  find  bugs  in  software,  and  most  importantly,  find 
security  holes  in  existing  code.  And  much  of  the  "front-end"  technology  — 
grammars,  regular  expressions,  parsers,  and  syntax-directed  translators  —  are 
still  in  wide  use. 

Thus,  our  philosophy  from  previous  versions  of  the  book  has  not  changed. 
We  recognize  t h at  few  readers  will  build,  or  even  maintain,  a  compiler  for  a 
major  programming  language.  Yet  the  models,  theory,  and  algorithms  associ 
ated  with  a  compiler  can  be  applied  to  a  wide  range  of  problems  in  software 
design  and  software  development.  We  therefore  emphasize  problems  t h at  are 
most  commonly  encountered  in  designing  a  language  processor,  regardless  of 
t he  source  language  or  target  machine. 

Use  of  the  Book 

It  takes  at  least  two  quarters  or  even  two  semesters  to  cover  all  or  most  of  the 
material  in  this  book.  It  is  common  to  cover  t he  first  half  in  an  undergraduate 
course  and  the  second  half  of  the  book  —  stressing  code  optimization  —  in 
a  second  course  at  the  graduate  or  mezzanine  level.  Here  is  an  outline  of  the 
chapters: 

Chapter  1  contains  motivational  material  and  also  presents  some  background 
issues  in  computer  architecture  and  programming-language  principles. 

Chapter  2  develops  a  miniature  compiler  and  introduces  many  of  the  impor 
t a nt  concepts,  which  are  then  developed  in  later  chapters.  The  compiler  itself 
appears  in  the  appendix. 

Chapter  3  covers  lexical  analysis,  regular  expressions,  finite-state  machines,  and 
scanner-generator  tools.  This  material  is  fundamental  to  text-processing  of  all 
sorts. 

v 

vi 

PREFACE 

Chapter  4  covers  the  major  parsing  methods,  top-down  (recursive-descent,  LL) 
and  bottom-up  (LR  and  its  variants). 

Chapter  5  introduces  the  principal  ideas  in  syntax-directed  definitions  and 
syntax-directed  translations. 

Chapter  6  takes  the  theory  of  Chapter  5  and  shows  how  to  use  it  to  generate 
intermediate  code  for  a  typical  programming  language. 

Chapter  7  covers  run-time  environments,  especially  management  of the  run-time 
stack  and  garbage  collection. 

Chapter  8  is  on  object-code  generation.  It  covers  construction  of  basic  blocks, 
generation  of  code  from  expressions  and  basic  blocks,  and  register-allocation 
techniques. 

Chapter  9  introduces  the  technology  of code  optimization,  including flow graphs, 
data-flow  frameworks,  and  iterative  algorithms  for  solving  these  frameworks. 

Chapter  10  covers  instruction-level  optimization.  The  emphasis  is  on  the  ex 
traction  of parallelism  from  small  sequences  of instructions  and  scheduling  t h em 
on  single  processors  t h at  can  do  more  t h an  one  thing  at  once. 

Chapter  11  talks  about  larger-scale parallelism  detection  and  exploitation.  Here, 
the  emphasis  is  on  numeric  codes  t h at  have  many  tight  loops  t h at  range  over 
multidimensional  arrays. 

Chapter  12  is  on  interprocedural  analysis.  It  covers  pointer  analysis,  aliasing, 
and  data-flow  analysis  t h at  takes  into  account  the  sequence  of  procedure  calls 
t h at  reach  a  given  point  in  the  code. 

Courses  from  material  in  this  book  have  been  taught  at  Columbia,  Harvard, 
and  Stanford.  At  Columbia,  a  senior/first-year  graduate  course  on  program 
ming  languages  and  translators  has  been  regularly  offered  using  material  from 
the  first  eight  chapters.  A  highlight  of  this  course  is  a  semester-long  project 
in  which  students  work  in  small  teams  to  create  and  implement  a  little  lan 
guage  of  their  own  design.  The  student-created  languages  have  covered  diverse 
application  domains  including  q u a n t um  computation,  music  synthesis,  com 
puter  graphics,  gaming,  matrix  operations  and  many  other  areas.  Students  use 
compiler-component  generators  such  as  ANTLR,  Lex,  and  Yacc  and  the  syntax-
directed  translation  techniques  discussed  in  chapters  two  and  five  to  build  their 
compilers.  A  follow-on  graduate  course  has  focused  on  material  in  Chapters  9 
through  12,  emphasizing  code  generation  and  optimization  for  contemporary 
machines  including  network  processors  and  multiprocessor  architectures. 

At  Stanford,  a  one-quarter  introductory  course  covers  roughly  t he  mate 
rial  in  Chapters  1  through  8,  although  there  is  an  introduction  to  global  code 
optimization  from  Chapter  9.  T he  second  compiler  course  covers  Chapters  9 
through  12,  plus  the  more  advanced  material  on  garbage  collection  from  Chap 
ter  7.  Students  use  a  locally  developed,  Java-based  system  called  J o eq  for 
implementing  data-flow  analysis  algorithms. 

PREFACE 

Prerequisites 

vii 

T he  reader  should  possess  some  "computer-science  sophistication," 
including 
at  least  a  second  course  on  programming,  and  courses  in  d a ta  structures  and 
discrete  mathematics.  Knowledge  of  several  different  programming  languages 
is  useful. 

Exercises 

T he  book  contains  extensive  exercises,  with  some  for  almost  every  section.  We 
indicate  harder  exercises  or  p a r ts  of  exercises  with  an  exclamation  point.  T he 
hardest  exercises  have  a  double  exclamation  point. 

Gradiance On-Line Homeworks 

A  feature  of  the  new  edition  is  t h at  there  is  an  accompanying  set  of  on-line 
homeworks  using  a  technology  developed  by  Gradiance  Corp.  Instructors  may 
assign  these  homeworks  to  their  class,  or  students  not  enrolled  in  a  class  may 
enroll  in  an  "omnibus  class"  t h at  allows  them  to  do  the  homeworks  as  a  tutorial 
(without  an  instructor-created  class).  Gradiance  questions  look  like  ordinary 
questions,  but  your  solutions  are  sampled.  If  you  make  an  incorrect  choice  you 
are  given  specific  advice  or  feedback  to  help  you  correct  your  solution.  If  your 
instructor  permits,  you  are  allowed  to  t ry  again,  until  you  get  a  perfect  score. 

A  subscription  to  the  Gradiance  service  is  offered  with  all  new  copies  of  this 
text  sold  in  North  America.  For  more  information,  visit  the  Addison-Wesley 
web site www.aw.com/gradiance or send email to computing@aw.com. 

Support  on  the  World  Wide  Web 

T he  book's  home  page  is 

dragonbook.Stanford.edu 

Here,  you  will  find  errata  as  we  learn  of  them,  and  backup  materials.  We  hope 
to  make  available  the  notes  for  each  offering  of  compiler-related  courses  as  we 
teach  them,  including  homeworks,  solutions,  and  exams.  We  also  plan  to  post 
descriptions  of  important  compilers  written  by  their  implementers. 

Acknowledgements 

Cover  art  is  by  S.  D.  Ullman  of  Strange  Tonic  Productions. 

Jon  Bentley  gave  us  extensive  comments  on  a  number  of  chapters  of  an 
earlier  draft  of  this  book.  Helpful  comments  and  e r r a ta  were  received  from: 

viii 

PREFACE 

Domenico  Bianculli,  Peter  Bosch,  Marcio  Buss,  Marc  Eaddy,  Stephen  Edwards, 
Vibhav  Garg,  Kim  Hazelwood,  Gaurav  Kc,  Wei  Li,  Mike  Smith,  Art  Stamness, 
Krysta  Svore,  Olivier  Tardieu,  and  Jia  Zeng.  The  help  of  all  these  people  is 
gratefully  acknowledged.  Remaining  errors  are  ours,  of  course. 

In  addition,  Monica  would  like  to  t h a nk  her  colleagues  on  the  SUIF  com 
piler  team  for  an  18-year  lesson  on  compiling:  Gerald  Aigner,  Dzintars  Avots, 
Saman  Amarasinghe,  Jennifer  Anderson,  Michael  Carbin,  Gerald  Cheong,  Amer 
Diwan,  Robert  French,  Anwar  Ghuloum,  Mary  Hall,  John  Hennessy,  David 
Heine,  Shih-Wei  Liao,  Amy  Lim,  Benjamin  Livshits,  Michael  Martin,  Dror 
Maydan,  Todd  Mowry,  Brian  Murphy,  Jeffrey  Oplinger,  Karen  Pieper,  Mar 
tin  Rinard,  Olatunji  Ruwase,  Constantine  Sapuntzakis,  Patrick  Sathyanathan, 
Michael  Smith,  Steven  Tjiang,  Chau-Wen  Tseng,  Christopher  Unkel,  John 
Whaley,  Robert  Wilson,  Christopher  Wilson,  and  Michael  Wolf. 

A.  V.  A.,  C h a t h am  NJ 
M.  S.  L.,  Menlo  P a rk  CA 
R.  S.,  Far  Hills  NJ 
J.  D.  U.,  Stanford  CA 
June,  2006 

Table  of  Contents 

1 

I n t r o d u c t i on 
1.1  Language  Processors 

1.1.1  Exercises  for  Section  1.1 

1.2  T he  Structure  of a  Compiler 
1.2.1  Lexical  Analysis 
Syntax  Analysis 
1.2.2 
Semantic  Analysis 
1.2.3 
1.2.4 
Intermediate  Code  Generation 
1.2.5  Code  Optimization 
1.2.6  Code  Generation 
1.2.7 
1.2.8 
1.2.9  Compiler-Construction  Tools 
1.3  T he  Evolution  of  Programming  Languages 

Symbol-Table  Management 
The  Grouping  of  Phases  into  Passes 

1.3.1  T he  Move  to  Higher-level  Languages 
1.3.2 
1.3.3  Exercises  for  Section  1.3 
1.4  T he  Science  of  Building  a  Compiler 

Impacts  on  Compilers 

1.4.1  Modeling  in  Compiler  Design  and  Implementation 
1.4.2  T he  Science  of  Code  Optimization 

1.5  Applications  of  Compiler  Technology 

Implementation  of  High-Level  Programming  Languages 

1.5.1 
1.5.2  Optimizations  for  Computer  Architectures 
1.5.3  Design  of New  Computer  Architectures 
1.5.4 
1.5.5 

Program  Translations 
Software  Productivity  Tools 

1.6  Programming  Language  Basics 

The  Static/Dynamic  Distinction 
Environments  and  States 
Static  Scope  and  Block  Structure 
Explicit  Access  Control 

1.6.1 
1.6.2 
1.6.3 
1.6.4 
1.6.5  Dynamic  Scope 
1.6.6 

P a r a m e t er  Passing  Mechanisms 

ix 

1 
1 
3 
4 
5 
8 
8 
9 
10 
10 
11 
11 
12 
12 
13 
14 
14 
15 

. . .. 

15 

. 

15 
17 
17 
19 
21 
22 
23 
25 
25 
26 
28 
31 
31 
33 

TABLE  OF  CONTENTS 

1.6.7  Aliasing 
1.6.8  Exercises  for  Section  1.6 

1.7  Summary  of  Chapter  1 
1.8  References  for  Chapter  1 

A  S i m p le  S y n t a x - D i r e c t ed  T r a n s l a t or 
2.1 
Introduction 
2.2  Syntax  Definition 

2.2.1  Definition  of  G r a m m a rs 
2.2.2  Derivations 
2.2.3  Parse  Trees 
2.2.4  Ambiguity 
2.2.5  Associativity  of  Operators 
2.2.6  Precedence  of  Operators 
2.2.7  Exercises  for  Section  2.2 

Synthesized  Attributes 

2.3  Syntax-Directed  Translation  . 
2.3.1  Postfix  Notation 
2.3.2 
2.3.3  Simple  Syntax-Directed  Definitions 
2.3.4  Tree  Traversals 
2.3.5  Translation  Schemes 
2.3.6  Exercises  for  Section  2.3 

2.4  Parsing 

2.4.1  Top-Down  Parsing 
2.4.2 
Predictive  Parsing 
2.4.3  When  to  Use  e-Productions 
2.4.4  Designing  a  Predictive  Parser 
2.4.5  Left  Recursion 
2.4.6  Exercises  for  Section  2.4 
2.5  A  Translator  for  Simple  Expressions 

2.5.1  Abstract  and  Concrete  Syntax 
2.5.2  Adapting  the  Translation  Scheme 
2.5.3  Procedures  for  the  Nonterminals 
2.5.4  Simplifying  the  Translator 
2.5.5  T he  Complete  P r o g r am 

2.6  Lexical  Analysis 

2.6.1  Removal  of White  Space  and  Comments 
2.6.2  Reading  Ahead 
2.6.3  Constants 
2.6.4  Recognizing  Keywords  and  Identifiers 
2.6.5  A  Lexical  Analyzer 
2.6.6  Exercises  for  Section  2.6 

2.7  Symbol  Tables 

2.7.1  Symbol  Table  Per  Scope 
2.7.2  The  Use  of  Symbol  Tables 

35 
35 
36 
38 

39 
40 
42 
42 
44 
45 
47 
48 
48 
51 
52 
.  53 
54 
56 
56 
57 
60 
60 
61 
64 
65 
66 
67 
68 
68 
69 
70 
72 
73 
74 
76 
77 
78 

78 

79 
81 
84 

85 

86 
89 

TABLE  OF  CONTENTS 

2.8 

Intermediate  Code  Generation 
2.8.1  Two  Kinds  of Intermediate  Representations 
2.8.2  Construction  of  Syntax  Trees 
2.8.3 
2.8.4  Three-Address  Code 
2.8.5  Exercises  for  Section  2.8 

Static  Checking 

2.9  Summary  of  Chapter  2 

3  L e x i c al  A n a l y s is 

3.1  T he  Role  of  the  Lexical  Analyzer 

3.1.1  Lexical  Analysis  Versus  Parsing 
3.1.2  Tokens,  P a t t e r n s,  and  Lexemes 
3.1.3  Attributes  for  Tokens 
3.1.4  Lexical  Errors 
3.1.5  Exercises  for  Section  3.1 
Input  Buffering 
3.2.1  Buffer  Pairs 
3.2.2 

Sentinels 

3.2 

3.3  Specification  of  Tokens 

Strings  and  Languages 

3.3.1 
3.3.2  Operations  on  Languages 
3.3.3  Regular  Expressions 
3.3.4  Regular  Definitions 
3.3.5  Extensions  of  Regular  Expressions 
3.3.6  Exercises  for  Section  3.3 

3.4  Recognition  of  Tokens 

3.4.1  Transition  Diagrams 
3.4.2  Recognition  of  Reserved  Words  and  Identifiers 
3.4.3  Completion  of the  Running  Example 
3.4.4  Architecture  of  a  Transition-Diagram-Based  Lexical  An 

alyzer 

3.4.5  Exercises  for  Section  3.4 
3.5  The  Lexical-Analyzer  Generator  Lex 

3.5.1  Use  of Lex 
3.5.2 
Structure  of Lex  Programs 
3.5.3  Conflict  Resolution  in  Lex 
3.5.4  T he  Lookahead  Operator 
3.5.5  Exercises  for  Section  3.5 

3.6  Finite  A u t o m a ta 

3.6.1  Nondeterministic  Finite  A u t o m a ta 
3.6.2  Transition  Tables 
3.6.3  Acceptance  of Input  Strings  by  A u t o m a ta 
3.6.4  Deterministic  Finite  A u t o m a ta 
3.6.5  Exercises  for  Section  3.6 

3.7  From  Regular  Expressions  to  A u t o m a ta 

xi 

91 
91 
92 
97 
99 
105 
105 

109 
110 
I ll 
112 
113 
114 
115 
115 
116 
116 
117 
119 
120 
123 
124 
125 
128 
130 
132 
133 

134 
136 
140 
140 
141 
144 
144 
146 
147 
147 
148 
149 
149 
151 
152 

xii 

TABLE  OF  CONTENTS 

152 
156 
157 
. 1 59 
163 
166 
166 
167 
168 
170 
171 
172 
173 
173 
175 
176 
177 
.  179 
180 
. 1 84 
185 
186 
187 
189 

191 
192 
192 
193 
194 
195 
197 

3.7.1  Conversion  of  an  NFA  to  a  DFA 
3.7.2 
Simulation  of an  NFA 
3.7.3  Efficiency  of  NFA  Simulation 
3.7.4  Construction  of  an  NFA  from  a  Regular  Expression 
3.7.5  Efficiency  of  String-Processing  Algorithms 
3.7.6  Exercises  for  Section  3.7 

. 

. 

3.8  Design  of  a  Lexical-Analyzer  Generator 

3.8.1  T he  Structure  of the  Generated  Analyzer 
3.8.2 
P a t t e rn  Matching  Based  on  NFA's 
3.8.3  DFA's  for  Lexical  Analyzers 
3.8.4 
3.8.5  Exercises  for  Section  3.8 

Implementing  the  Lookahead  Operator 

3.9  Optimization  of DFA-Based  P a t t e rn  Matchers 
Important  States  of an  NFA 
Functions  Computed  From  the  Syntax  Tree 

3.9.1 
3.9.2 
3.9.3  Computing  unliable,  firstpos,  and  lastpos 
3.9.4  Computing  followpos 
3.9.5  Converting  a  Regular  Expression  Directly  to  a  DFA 
3.9.6  Minimizing  the  Number  of  States  of  a  DFA 
3.9.7 
3.9.8  Trading  Time  for  Space  in  DFA  Simulation 
3.9.9  Exercises  for  Section  3.9 

State  Minimization  in  Lexical  Analyzers 

. 

. 

3.10  Summary  of  Chapter  3 
3.11  References  for  Chapter  3 

4.1 

4  S y n t ax  A n a l y s is 
Introduction 
4.1.1  T he  Role  of t he  Parser 
4.1.2  Representative  G r a m m a rs 
4.1.3 
4.1.4  Error-Recovery  Strategies 

Syntax  Error  Handling 

4.2  Context-Free  G r a m m a rs 

4.2.1  The  Formal  Definition  of  a  Context-Free  G r a m m ar 
4.2.2  Notational  Conventions 
4.2.3  Derivations 
4.2.4 
4.2.5  Ambiguity 
4.2.6  Verifying  t he  Language  Generated  by  a  G r a m m ar 
4.2.7  Context-Free  G r a m m a rs  Versus  Regular  Expressions 
4.2.8  Exercises  for  Section  4.2 

Parse  Trees  and  Derivations 

4.3  Writing  a  G r a m m ar 

4.3.1  Lexical  Versus  Syntactic  Analysis 
4.3.2  Eliminating  Ambiguity 
4.3.3  Elimination  of  Left  Recursion 
4.3.4  Left  Factoring 

. . ..  197 

198 
199 
201 
203 

. . ..  204 
. 

. 

.  205 
206 
209 
209 
210 
212 
214 

TABLE  OF  CONTENTS 

4.3.5  Non-Context-Free  Language  Constructs 
4.3.6  Exercises  for  Section  4.3 

4.4  Top-Down  Parsing 

F I R ST  and  F O L L OW 

4.4.1  Recursive-Descent  Parsing 
4.4.2 
4.4.3  LL(1)  G r a m m a rs 
4.4.4  Nonrecursive  Predictive  Parsing 
4.4.5  Error  Recovery  in  Predictive  Parsing 
4.4.6  Exercises  for  Section  4.4 

4.6 

Shift-Reduce  Parsing 

4.5  Bottom-Up  Parsing 
4.5.1  Reductions 
4.5.2  Handle  Pruning 
4.5.3 
4.5.4  Conflicts  During  Shift-Reduce  Parsing 
4.5.5  Exercises  for  Section  4.5 
Introduction  to  LR  Parsing:  Simple  LR 
4.6.1  Why  LR  Parsers? 
4.6.2 
4.6.3  T he  LR-Parsing  Algorithm 
4.6.4  Constructing  SLR-Parsing  Tables 
4.6.5  Viable  Prefixes 
4.6.6  Exercises  for  Section  4.6 

Items  and  the  LR(0)  Automaton 

4.7  More  Powerful  LR  Parsers 

4.7.1  Canonical  LR(1)  Items 
4.7.2  Constructing  LR(1)  Sets  of  Items 
4.7.3  Canonical  LR(1)  Parsing  Tables 
4.7.4  Constructing  LALR  Parsing  Tables 
4.7.5  Efficient  Construction  of  LALR  Parsing  Tables 
4.7.6  Compaction  of  LR  Parsing  Tables 
4.7.7  Exercises  for  Section  4.7 

4.8  Using  Ambiguous  G r a m m a rs 

4.8.1  Precedence  and  Associativity  to  Resolve  Conflicts 
4.8.2  The  "Dangling-Else"  Ambiguity 
4.8.3  Error  Recovery  in  LR  Parsing 
4.8.4  Exercises  for  Section  4.8 

4.9  Parser  Generators 

The  Parser  Generator Yacc 

4.9.1 
4.9.2  Using Yacc  with  Ambiguous  G r a m m a rs 
4.9.3  Creating Yacc  Lexical  Analyzers  with  Lex 
4.9.4  Error  Recovery  in Yacc 
4.9.5  Exercises  for  Section  4.9 

4.10  Summary  of  Chapter  4 
4.11  References  for  Chapter  4 

x i

ii 

215 
216 
217 
219 
220 
222 
226 
228 
231 
233 
234 
235 
236 
238 
240 
241 
241 
242 
248 
252 
256 
257 
259 
260 
261 
265 
266 
270 
275 
277 
278 

. . ..  279 

281 
283 
285 
287 
287 
291 
294 
295 
297 
297 
300 

xiv 

TABLE  OF  CONTENTS 

5  S y n t a x - D i r e c t ed  T r a n s l a t i on 
5.1  Syntax-Directed  Definitions 

Inherited  and  Synthesized  Attributes 

5.1.1 
5.1.2  Evaluating  an  SDD  at  the  Nodes  of  a  Parse  Tree 
5.1.3  Exercises  for  Section  5.1 

5.2  Evaluation  Orders  for  SDD's 

5.2.1  Dependency  Graphs 
5.2.2  Ordering  the  Evaluation  of Attributes 
5.2.3  S-Attributed  Definitions 
5.2.4  L-Attributed  Definitions 
5.2.5 
5.2.6  Exercises  for  Section  5.2 

Semantic  Rules  with  Controlled  Side  Effects 

5.3  Applications  of  Syntax-Directed  Translation 

5.3.1  Construction  of  Syntax  Trees 
5.3.2  The  Structure  of a  Type 
5.3.3  Exercises  for  Section  5.3 
5.4  Syntax-Directed  Translation  Schemes 

SDT's  for  L-Attributed  Definitions 

Postfix  Translation  Schemes 
5.4.1 
Parser-Stack  Implementation  of Postfix  SDT's 
5.4.2 
5.4.3 
SDT's  W i th  Actions  Inside  Productions 
5.4.4  Eliminating  Left  Recursion  From  SDT's 
5.4.5 
5.4.6  Exercises  for  Section  5.4 
Implementing  L-Attributed  SDD's 
5.5.1  Translation  During  Recursive-Descent  Parsing 
5.5.2  On-The-Fly  Code  Generation 
5.5.3  L-Attributed  SDD's  and  LL  Parsing 
5.5.4  Bottom-Up  Parsing  of L-Attributed  SDD's 
5.5.5  Exercises  for  Section  5.5 

5.5 

5.6  Summary  of  Chapter  5 
5.7  References  for  Chapter  5 

6 

I n t e r m e d i a t e - C o de  G e n e r a t i on 
6.1  Variants  of  Syntax  Trees 

6.1.1  Directed  Acyclic  Graphs  for  Expressions 
6.1.2  The  Value-Number  Method  for  Constructing  DAG's 
6.1.3  Exercises  for  Section  6.1 

6.2  Three-Address  Code 

6.2.1  Addresses  and  Instructions 
6.2.2  Quadruples 
6.2.3  Triples 
6.2.4 
6.2.5  Exercises  for  Section  6.2 

Static  Single-Assignment  Form 

6.3  Types  and  Declarations 

6.3.1  Type  Expressions 

3 03 
304 
304 
306 
309 
310 
310 
312 
312 
313 
314 
317 
318 
318 
321 
323 
324 
324 
325 
327 
328 
331 
336 
337 
338 
340 
343 
348 
352 
353 
354 

3 57 
358 
359 

. ..  360 

362 
363 
364 
366 
367 
369 
370 
370 
371 

TABLE  OF  CONTENTS 

6.3.2  Type  Equivalence 

6.3.3  Declarations 

6.3.4 

Storage  Layout  for  Local  Names 

6.3.5 

Sequences  of  Declarations 

6.3.6 

Fields  in  Records  and  Classes 

6.3.7  Exercises  for  Section  6.3 

6.4  Translation  of Expressions 

6.4.1  Operations  Within  Expressions 

6.4.2 

Incremental  Translation 

6.4.3  Addressing  Array  Elements 

6.4.4  Translation  of  Array  References 

6.4.5  Exercises  for  Section  6.4 

6.5  Type  Checking 

6.5.1  Rules  for  T y pe  Checking 

6.5.2  Type  Conversions 

6.5.3  Overloading  of  Functions  and  Operators 

6.5.4  Type  Inference  and  Polymorphic  Functions 

6.5.5  An  Algorithm  for  Unification 

6.5.6  Exercises  for  Section  6.5 

6.6  Control  Flow 

6.6.1  Boolean  Expressions 

6.6.2 

Short-Circuit  Code 

6.6.3 

Flow-of-Control  Statements 

6.6.4  Control-Flow  Translation  of  Boolean  Expressions 

6.6.5  Avoiding  Redundant  Gotos 

6.6.6  Boolean  Values  and  Jumping  Code 

6.6.7  Exercises  for  Section  6.6 

6.7  Backpatching 

6.7.1  One-Pass  Code  Generation  Using  Backpatching 

6.7.2  Backpatching  for  Boolean  Expressions 

6.7.3 

Flow-of-Control  Statements 

6.7.4  Break-,  Continue-,  and  Goto-Statements 

6.7.5  Exercises  for  Section  6.7 

6.8  Switch-Statements 

6.8.1  Translation  of  Switch-Statements 

™ 

372 

373 

373 

376 

376 

378 

378 

378 

380 

381 

383 

384 

386 

387 

388 

390 

391 

395 

398 

399 

399 

400 

401 

403 

405 

408 

408 

410 

410 

411 

413 

416 

417 

418 

419 

6.8.2 

Syntax-Directed  Translation  of  Switch-Statements 

. . ..  420 

6.8.3  Exercises  for  Section  6.8 

6.9 

Intermediate  Code  for  Procedures 

6.10  Summary  of  Chapter  6 

6.11  References  for  Chapter  6 

421 

422 

424 

425 

xvi 

TABLE  OF  CONTENTS 

7  R u n - T i me  E n v i r o n m e n ts 
7.1  Storage  Organization 

7.1.1 

Static  Versus  Dynamic  Storage  Allocation 

7.2  Stack  Allocation  of Space 

7.2.1  Activation  Trees 
7.2.2  Activation  Records 
7.2.3  Calling  Sequences 
7.2.4  Variable-Length  D a ta  on  t he  Stack 
7.2.5  Exercises  for  Section  7.2 
7.3  Access  to  Nonlocal  D a ta  on  t he  Stack 

Issues  W i th  Nested  Procedures 

7.3.1  D a ta  Access  W i t h o ut  Nested  Procedures 
7.3.2 
7.3.3  A  Language  W i th  Nested  Procedure  Declarations 
7.3.4  Nesting  Depth 
7.3.5  Access  Links 
7.3.6  Manipulating  Access  Links 
7.3.7  Access  Links  for  Procedure  P a r a m e t e rs 
7.3.8  Displays 
7.3.9  Exercises  for  Section  7.3 

7.4  Heap  Management 

7.5 

7.4.1  T he  Memory  Manager 
7.4.2  T he  Memory  Hierarchy  of  a  Computer 
7.4.3  Locality  in  Programs 
7.4.4  Reducing  Fragmentation 
7.4.5  Manual  Deallocation  Requests 
7.4.6  Exercises  for  Section  7.4 
Introduction  to  Garbage  Collection 
7.5.1  Design  Goals  for  Garbage  Collectors 
7.5.2  Reachability 
7.5.3  Reference  Counting  Garbage  Collectors 
7.5.4  Exercises  for  Section  7.5 
Introduction  to  Trace-Based  Collection 
7.6.1  A  Basic  Mark-and-Sweep  Collector 
7.6.2  Basic  Abstraction 
7.6.3  Optimizing  Mark-and-Sweep 
7.6.4  Mark-and-Compact  Garbage  Collectors 
7.6.5  Copying  collectors 
7.6.6  Comparing  Costs 
7.6.7  Exercises  for  Section  7.6 
7.7  Short-Pause  Garbage  Collection 

7.6 

Incremental  Garbage  Collection 
7.7.1 
Incremental  Reachability  Analysis 
7.7.2 
7.7.3 
Partial-Collection  Basics 
7.7.4  Generational  Garbage  Collection 
7.7.5  The  Train  Algorithm 

4 27 
427 
429 
430 
430 
433 
436 
438 
440 
441 
442 
442 
443 
443 
445 
447 
448 
449 
451 
452 
453 
454 
455 
457 
460 
463 
463 
464 
466 
468 
470 
470 
471 
473 
475 
476 
478 
482 
482 
483 
483 
485 
487 
488 
490 

TABLE  OF  CONTENTS 

7.7.6  Exercises  for  Section  7.7 

7.8  Advanced  Topics  in  Garbage  Collection 

Parallel  and  Concurrent  Garbage  Collection 
Partial  Object  Relocation 

7.8.1 
7.8.2 
7.8.3  Conservative  Collection  for  Unsafe  Languages 
7.8.4  Weak  References 
7.8.5  Exercises  for  Section  7.8 

7.9  Summary  of  Chapter  7 
7.10  References  for  Chapter  7 

8  C o de  G e n e r a t i on 

8.1 

Input  to  t he  Code  Generator 

Issues  in  the  Design  of  a  Code  Generator 
8.1.1 
8.1.2  T he  Target  Program 
8.1.3 
Instruction  Selection 
8.1.4  Register  Allocation 
8.1.5  Evaluation  Order 

8.2  T he  Target  Language 

8.2.1  A  Simple  Target  Machine  Model 
8.2.2 
8.2.3  Exercises  for  Section  8.2 

Program  and  Instruction  Costs 

8.3  Addresses  in  the  Target  Code 

Static  Allocation 
Stack  Allocation 

8.3.1 
8.3.2 
8.3.3  Run-Time  Addresses  for  Names 
8.3.4  Exercises  for  Section  8.3 

8.4  Basic  Blocks  and  Flow  Graphs 

8.4.1  Basic  Blocks 
8.4.2  Next-Use  Information 
8.4.3 
Flow  Graphs 
8.4.4  Representation  of Flow  Graphs 
8.4.5  Loops 
8.4.6  Exercises  for  Section  8.4 

8.5  Optimization  of Basic  Blocks 

Finding  Local  Common  Subexpressions 

8.5.1  The  DAG  Representation  of  Basic  Blocks 
8.5.2 
8.5.3  Dead  Code  Elimination 
8.5.4  The  Use  of  Algebraic  Identities 
8.5.5  Representation  of  Array  References 
8.5.6 
8.5.7  Reassembling  Basic  Blocks  From  DAG's 
8.5.8  Exercises  for  Section  8.5 

Pointer  Assignments  and  Procedure  Calls 

8.6  A  Simple  Code  Generator 

8.6.1  Register  and  Address  Descriptors 
8.6.2  T he  Code-Generation  Algorithm 

xvii 

493 
494 
495 
497 
498 
498 
499 
500 
502 

505 
506 
507 
507 
508 
510 
511 
512 
512 
515 
516 
518 
518 
520 
522 
524 
525 
526 
528 
529 
.  530 
531 
531 
533 
533 
534 
535 
536 
537 
539 
539 
541 
542 
543 
544 

xviii 

TABLE  OF  CONTENTS 

8.6.3  Design  of t he  Function  getReg 
8.6.4  Exercises  for  Section  8.6 

8.7  Peephole  Optimization 

8.7.1  Eliminating  R e d u n d a nt  Loads  and  Stores 
8.7.2  Eliminating  Unreachable  Code 
Flow-of-Control  Optimizations 
8.7.3 
8.7.4  Algebraic  Simplification  and  Reduction  in  Strength  . . ..  552 
8.7.5  Use  of Machine  Idioms 
8.7.6  Exercises  for  Section  8.7 
8.8  Register  Allocation  and  Assignment 

8.9 

8.8.1  Global  Register  Allocation 
8.8.2  Usage  Counts 
8.8.3  Register  Assignment  for  Outer  Loops 
8.8.4  Register  Allocation  by  G r a ph  Coloring 
8.8.5  Exercises  for  Section  8.8 
Instruction  Selection  by  Tree  Rewriting 
8.9.1  Tree-Translation  Schemes 
8.9.2  Code  Generation  by  Tiling  an  Input  Tree 
8.9.3 
8.9.4  Routines  for  Semantic  Checking 
8.9.5  General  Tree  Matching 
8.9.6  Exercises  for  Section  8.9 

P a t t e rn  Matching  by  Parsing 

8.10  Optimal  Code  Generation  for  Expressions 

8.10.1  Ershov  Numbers 
8.10.2  Generating  Code  From  Labeled  Expression  Trees 
8.10.3  Evaluating  Expressions with  an Insufficient  Supply  of Reg 

isters 

• 

8.10.4  Exercises  for  Section  8.10 

8.11  Dynamic  Programming  Code-Generation 

8.11.1  Contiguous  Evaluation 
8.11.2  The  Dynamic  Programming  Algorithm 
8.11.3  Exercises  for  Section  8.11 

8.12  Summary  of  Chapter  8 
8.13  References  for  Chapter  8 

9  M a c h i n e - I n d e p e n d e nt  O p t i m i z a t i o ns 

9.1  The  Principal  Sources  of  Optimization 

Semantics-Preserving  Transformations 

9.1.1  Causes  of Redundancy 
9.1.2  A  Running  Example:  Quicksort 
9.1.3 
9.1.4  Global  Common  Subexpressions 
9.1.5  Copy  Propagation 
9.1.6  Dead-Code  Elimination 
9.1.7  Code  Motion 
9.1.8 

Induction  Variables  and  Reduction  in  Strength 

547 
548 
549 
550 
550 
551 

552 
553 
553 
553 
554 
556 
556 
557 
558 
558 
560 
563 
565 
565 
567 
567 
567 
568 

570 
572 
573 
574 
575 
577 
578 
579 

5 83 
584 
584 
585 
586 
588 
590 
591 
592 
592 

TABLE  OF  CONTENTS 

9.2 

9.1.9  Exercises  for  Section  9.1 
Introduction  to  Data-Flow  Analysis 
9.2.1  The  Data-Flow  Abstraction 
9.2.2  T he  Data-Flow  Analysis  Schema 
9.2.3  Data-Flow  Schemas  on  Basic  Blocks 
9.2.4  Reaching  Definitions 
9.2.5  Live-Variable  Analysis 
9.2.6  Available  Expressions 
9.2.7 
9.2.8  Exercises  for  Section  9.2 
9.3  Foundations  of Data-Flow  Analysis 

Summary 

9.3.1 
Semilattices 
9.3.2  Transfer  Functions 
9.3.3  T he  Iterative  Algorithm  for  General  Frameworks 
9.3.4  Meaning  of  a  Data-Flow  Solution 
9.3.5  Exercises  for  Section  9.3 

9.4  Constant  Propagation 

9.4.1  Data-Flow  Values  for  the  Constant-Propagation  Frame 

work 

9.4.2  T he  Meet  for  the  Constant-Propagation  Framework 
. 
9.4.3  Transfer  Functions  for  the  Constant-Propagation  Frame 

. 

x

ix 

596 
597 
597 
599 
600 
601 
608 
610 
614 
615 
618 
618 
623 
626 
628 
631 
632 

633 
.  633 

work 

Interpretation  of the  Results 

9.5.1  T he  Sources  of  Redundancy 
9.5.2  Can  All  Redundancy  Be  Eliminated? 
9.5.3  T he  Lazy-Code-Motion  Problem 
9.5.4  Anticipation  of Expressions 
9.5.5  T he  Lazy-Code-Motion  Algorithm 
9.5.6  Exercises  for  Section  9.5 

634 
9.4.4  Monotonicity  of  the  Constant-Propagation  Framework  . 
.  635 
9.4.5  Nondistributivity  of  the  Constant-Propagation  Framework  635 
637 
9.4.6 
637 
9.4.7  Exercises  for  Section  9.4 
639 
9.5  Partial-Redundancy  Elimination 
639 
642 
644 
645 
646 
655 
655 
656 
660 
661 
662 
665 
665 
Speed  of  Convergence  of  Iterative  Data-Flow  Algorithms  .  667 
669 
672 
672 
673 

9.6.1  Dominators 
9.6.2  Depth-First  Ordering 
9.6.3  Edges  in  a  Depth-First  Spanning  Tree 
9.6.4  Back  Edges  and  Reducibility 
9.6.5  Depth  of  a  Flow  Graph 
9.6.6  Natural  Loops 
9.6.7 
9.6.8  Exercises  for  Section  9.6 

9.7  Region-Based  Analysis 
9.7.1  Regions 
9.7.2  Region  Hierarchies  for  Reducible  Flow  Graphs 

9.6  Loops  in  Flow  Graphs 

XX 

TABLE  OF  CONTENTS 

9.7.3  Overview  of  a  Region-Based  Analysis 
9.7.4  Necessary  Assumptions  About  Transfer  Functions 
9.7.5  An  Algorithm  for  Region-Based  Analysis 
9.7.6  Handling  Nonreducible  Flow  Graphs 
9.7.7  Exercises  for  Section  9.7 

9.8  Symbolic  Analysis 

9.8.1  Affine  Expressions  of  Reference  Variables 
9.8.2  Data-Flow  Problem  Formulation 
9.8.3  Region-Based  Symbolic  Analysis 
9.8.4  Exercises  for  Section  9.8 

9.9  Summary  of  Chapter  9 
9.10  References  for  Chapter  9 

10  I n s t r u c t i o n - L e v el  P a r a l l e l i sm 
10.1  Processor  Architectures 

676 

. . ..  678 
680 
684 
686 
686 
687 
689 
694 
699 
700 
703 

10.1.1  Instruction  Pipelines  and  Branch  Delays 
10.1.2  Pipelined  Execution 
10.1.3  Multiple  Instruction  Issue 

10.2  Code-Scheduling  Constraints 
10.2.1  D a ta  Dependence 
10.2.2  Finding  Dependences  Among  Memory  Accesses 
10.2.3  Tradeoff  Between  Register  Usage  and  Parallelism 
10.2.4  Phase  Ordering  Between  Register  Allocation  and  Code 

Scheduling 
10.2.5  Control  Dependence 
10.2.6  Speculative  Execution  Support 
10.2.7  A  Basic  Machine  Model 
10.2.8  Exercises  for  Section  10.2 

10.3  Basic-Block  Scheduling 

10.3.1  Data-Dependence  Graphs 
10.3.2  List  Scheduling  of Basic  Blocks 
10.3.3  Prioritized  Topological  Orders 
10.3.4  Exercises  for  Section  10.3 

10.4  Global  Code  Scheduling 

10.4.1  Primitive  Code  Motion 
10.4.2  Upward  Code  Motion 
10.4.3  Downward  Code  Motion 
10.4.4  Updating  D a ta  Dependences 
10.4.5  Global  Scheduling  Algorithms  . 
10.4.6  Advanced  Code  Motion  Techniques 
10.4.7  Interaction  with  Dynamic  Schedulers 
10.4.8  Exercises  for  Section  10.4 

10.5  Software  Pipelining 
10.5.1  Introduction 
10.5.2  Software  Pipelining  of Loops 

7 07 
708 
708 
709 
710 
710 
711 
712 
713 

716 
716 
717 
719 
720 
721 
722 
723 
725 
726 
727 
728 
730 
731 
732 
732 
736 
737 
737 
738 
738 
740 

TABLE  OF  CONTENTS 

10.5.3  Register  Allocation  and  Code  Generation 
10.5.4  Do-Across  Loops 
10.5.5  Goals  and  Constraints  of  Software  Pipelining 
10.5.6  A  Software-Pipelining  Algorithm 
10.5.7  Scheduling  Acyclic  Data-Dependence  Graphs 
10.5.8  Scheduling  Cyclic  Dependence  Graphs 
10.5.9  Improvements  to  the  Pipelining  Algorithms 
10.5.10Modular  Variable  Expansion 
10.5.11 Conditional  Statements 
10.5.12 Hardware  Support  for  Software  Pipelining 
10.5.13Exercises  for  Section  10.5 

10.6  Summary  of  Chapter  10 
10.7  References  for  Chapter  10 

11  O p t i m i z i ng  for  P a r a l l e l i sm  a nd  L o c a l i ty 

11.1  Basic  Concepts 

11.1.1  Multiprocessors 
11.1.2  Parallelism  in  Applications 
11.1.3  Loop-Level  Parallelism 
11.1.4  D a ta  Locality 
11.1.5  Introduction  to  Affine  Transform  Theory 

11.2  Matrix  Multiply:  An  In-Depth  Example 

11.2.1  The  Matrix-Multiplication  Algorithm 
11.2.2  Optimizations 
11.2.3  Cache  Interference 
11.2.4  Exercises  for  Section  11.2 

11.3  Iteration  Spaces 

11.3.1  Constructing  Iteration  Spaces  from  Loop  Nests 
11.3.2  Execution  Order  for  Loop  Nests 
11.3.3  Matrix  Formulation  of Inequalities 
11.3.4  Incorporating  Symbolic  Constants 
11.3.5  Controlling  t he  Order  of  Execution 
11.3.6  Changing  Axes 
11.3.7  Exercises  for  Section  11.3 

11.4  Affine  Array  Indexes 

11.4.1  Affine  Accesses 
11.4.2  Affine  and  Nonaffine  Accesses  in  Practice 
11.4.3  Exercises  for  Section  11.4 

11.5  D a ta  Reuse 

11.5.1  Types  of Reuse 
11.5.2  Self Reuse 
11.5.3  Self-Spatial  Reuse 
11.5.4  Group  Reuse 
11.5.5  Exercises  for  Section  11.5 
11.6  Array  Data-Dependence  Analysis 

x

xi 

743 
743 
745 
749 
749 
751 
758 
758 
761 
762 
763 
765 
766 

7 69 

771 
772 
773 
775 
777 
778 
782 
782 
785 
788 
788 
788 
788 
791 
791 
793 
793 
798 
799 
801 
802 
803 
804 
804 
805 
806 
809 
811 
814 
815 

xxii 

TABLE  OF  CONTENTS 

11.6.1  Definition  of  D a ta  Dependence  of Array  Accesses 
11.6.2  Integer  Linear  Programming 
11.6.3  The  GCD  Test 
11.6.4  Heuristics  for  Solving  Integer  Linear  Programs 
11.6.5  Solving  General  Integer  Linear  Programs 
11.6.6  Summary 
11.6.7  Exercises  for  Section  11.6 

11.7  Finding  Synchronization-Free  Parallelism 

11.7.1  An  Introductory  Example 
11.7.2  Affine  Space  Partitions 
11.7.3  Space-Partition  Constraints 
11.7.4  Solving  Space-Partition  Constraints 
11.7.5  A  Simple  Code-Generation  Algorithm 
11.7.6  Eliminating  E m p ty  Iterations 
11.7.7  Eliminating  Tests  from  Innermost  Loops 
11.7.8  Source-Code  Transforms 
11.7.9  Exercises  for  Section  11.7 
11.8  Synchronization  Between  Parallel  Loops 

11.8.1  A  Constant  Number  of  Synchronizations 
11.8.2  Program-Dependence  Graphs 
11.8.3  Hierarchical  Time 
11.8.4  The  Parallelization  Algorithm 
11.8.5  Exercises  for  Section  11.8 

11.9  Pipelining 

11.9.1  W h at  is  Pipelining? 
11.9.2  Successive  Over-Relaxation  (SOR):  An  Example 
11.9.3  Fully  Permutable  Loops 
11.9.4  Pipelining  Fully  Permutable  Loops 
11.9.5  General  Theory 
11.9.6  Time-Partition  Constraints 
11.9.7  Solving  Time-Partition  Constraints  by  Farkas'  Lemma 
11.9.8  Code  Transformations 
11.9.9  Parallelism  W i th  Minimum  Synchronization 
11.9.10Exercises  for  Section  11.9 

. 

11.10  Locality  Optimizations 

11.10.1 Temporal  Locality  of  Computed  D a ta 
11.10.2 Array  Contraction 
11.10.3 Partition  Interleaving 
11.10.4Putting  it  All  Together 
11.10.5 Exercises  for  Section  11.10 

11.11  Other  Uses  of  Affine  Transforms 

11.11.1 Distributed  memory  machines 
11.11.2 Multi-Instruction-Issue  Processors 
11.11.3 Vector  and  SIMD  Instructions 
11.11.4 Prefetching 

816 
817 
818 
820 
823 
825 
826 
828 
828 
830 
831 
835 
838 
841 
844 
846 
851 
853 
853 
854 
857 
859 
860 
861 
861 
863 
864 
864 
867 
868 
.  872 
875 
880 
882 
884 
885 
885 
887 
890 
892 
893 
894 
895 
895 
896 

TABLE  OF  CONTENTS 

11.12  Summary  of  Chapter  11 
11.13  References  for  Chapter  11 

12  I n t e r p r o c e d u r al  A n a l y s is 

12.1  Basic  Concepts 

12.1.1  Call  Graphs 
12.1.2  Context  Sensitivity 
12.1.3  Call  Strings 
12.1.4  Cloning-Based  Context-Sensitive  Analysis 
12.1.5  Summary-Based  Context-Sensitive  Analysis 
12.1.6  Exercises  for  Section  12.1 

12.2  Why  Interprocedural  Analysis? 

12.2.1  Virtual  Method  Invocation 
12.2.2  Pointer  Alias  Analysis 
12.2.3  Parallelization 
12.2.4  Detection  of  Software  Errors  and  Vulnerabilities 
12.2.5  SQL  Injection 
12.2.6  Buffer  Overflow 

12.3  A  Logical  Representation  of  D a ta  Flow 

12.3.1  Introduction  to  Datalog 
12.3.2  Datalog  Rules 
12.3.3  Intensional  and  Extensional  Predicates 
12.3.4  Execution  of  Datalog  Programs 
12.3.5  Incremental  Evaluation  of  Datalog  Programs 
12.3.6  Problematic  Datalog  Rules 
12.3.7  Exercises  for  Section  12.3 
12.4  A  Simple  Pointer-Analysis  Algorithm 

12.4.1  Why  is  Pointer  Analysis  Difficult 
12.4.2  A  Model  for  Pointers  and  References 
12.4.3  Flow  Insensitivity 
12.4.4  T he  Formulation  in  Datalog 
12.4.5  Using  Type  Information 
12.4.6  Exercises  for  Section  12.4 

12.5  Context-Insensitive  Interprocedural  Analysis 
12.5.1  Effects  of  a  Method  Invocation 
12.5.2  Call  Graph  Discovery  in  Datalog 
12.5.3  Dynamic  Loading  and  Reflection 
12.5.4  Exercises  for  Section  12.5 

12.6  Context-Sensitive  Pointer  Analysis 

12.6.1  Contexts  and  Call  Strings 
12.6.2  Adding  Context  to  Datalog  Rules 
12.6.3  Additional  Observations  About  Sensitivity 
12.6.4  Exercises  for  Section  12.6 

12.7  Datalog  Implementation  by  BDD's 
12.7.1  Binary  Decision  Diagrams 

x x i

ii 

897 
899 

9 03 
904 
904 
906 
908 
910 
911 
914 
916 
916 
917 
917 
917 
918 
920 
921 
921 
922 
924 
927 
928 
930 
932 
933 
934 
935 
936 
937 
938 
939 
941 
941 
943 
944 
945 
945 
946 
949 
949 
950 
951 
951 

xxiv 

TABLE  OF  CONTENTS 

12.7.2  Transformations  on  BDD's 
12.7.3  Representing  Relations  by  BDD's 
12.7A  Relational  Operations  as  BDD  Operations 
12.7.5  Using  BDD's  for  Points-to  Analysis 
12.7.6  Exercises  for  Section  12.7 

12.8  Summary  of  Chapter  12 
12.9  References  for  Chapter  12 

A  A  C o m p l e te  Front  E nd 

A .l  The  Source  Language 
A.2  Main 
A.3  Lexical  Analyzer 
A.4  Symbol  Tables  and  Types 
A.5 
Intermediate  Code  for  Expressions 
A.6  Jumping  Code  for  Boolean  Expressions 
A.7  Intermediate  Code  for  Statements 
A.8  Parser 
A.9  Creating  the  Front  End 

B  F i n d i ng  Linearly  I n d e p e n d e nt  S o l u t i o ns 

I n d ex 

953 
954 
954 
957 
958 
958 
961 

9 65 
965 
966 
967 
970 
971 
974 
978 
981 
986 

9 89 

9 93 

Chapter  1 

Introduction 

Programming  languages  are  notations  for  describing  computations  to  people 
and  to  machines.  The  world  as  we  know  it  depends  on  programming  languages, 
because  all  the  software  running  on  all  the  computers  was  written  in  some 
programming  language.  But,  before  a  program  can  be  run,  it  first  must  be 
translated  into  a  form  in  which  it  can  be  executed  by  a  computer. 

T he  software  systems  t h at  do  this  translation  are  called  compilers. 
This  book  is  about  how  to  design  and  implement  compilers.  We  shall  dis 
cover  t h at  a  few  basic  ideas  can  be  used  to  construct  translators  for  a  wide 
variety  of  languages  and  machines.  Besides  compilers,  the  principles  and  tech 
niques  for  compiler  design  are  applicable  to  so  many  other  domains  t h at  they 
are  likely  to  be  reused  many  times  in  t he  career  of  a  computer  scientist.  T he 
study  of  compiler  writing  touches  upon  programming  languages,  machine  ar 
chitecture,  language  theory,  algorithms,  and  software  engineering. 

In  this  preliminary  chapter,  we  introduce  the  different  forms  of  language 
translators,  give  a  high  level  overview  of  the  structure  of  a  typical  compiler, 
and  discuss  the  trends  in  programming  languages  and  machine  architecture 
t h at  are  shaping  compilers.  We  include  some  observations  on  the  relationship 
between  compiler  design  and  computer-science  theory  and  an  outline  of  the 
applications  of  compiler  technology  t h at  go  beyond  compilation.  We  end  with 
a  brief  outline  of  key  programming-language  concepts  t h at  will  be  needed  for 
our  study  of  compilers. 

1.1  Language  Processors 

Simply  stated,  a  compiler  is  a  program  t h at  can  read  a  program  in  one  lan 
guage  —  t he  source  language  —  and  translate  it  into  an  equivalent  program  in 
another  language  —  the  target  language;  see  Fig.  1.1.  An  important  role  of  the 
compiler  is  to  report  any  errors  in  the  source  program  t h at  it  detects  during 
the  translation  process. 

1 

2 

CHAPTER 

1. 

INTRODUCTION 

source  program 

Compiler 

target  program 

Figure  1.1:  A  compiler 

If  the  target  program  is  an  executable  machine-language  program,  it  can 
then  be  called  by  the  user  to  process  inputs  and  produce  outputs;  see  Fig.  1.2. 

input 

Target  Program 

output 

Figure  1.2:  Running  the  target  program 

An  interpreter  is  another  common  kind  of  language  processor. 

Instead  of 
producing  a  target  program  as  a  translation,  an  interpreter  appears  to  directly 
execute  the  operations  specified  in  t he  source  program  on  inputs  supplied  by 
t he  user,  as  shown  in  Fig.  1.3. 

source  program 

input 

Interpreter 

output 

Figure  1.3:  An  interpreter 

The  machine-language  target  program  produced  by  a  compiler  is  usually 
much  faster  t h an  an  interpreter  at  mapping  inputs  to  outputs  .  An  interpreter, 
however,  can  usually  give  better  error  diagnostics  t h an  a  compiler,  because  it 
executes  the  source  program  statement  by  statement. 

E x a m p le  1 . 1:  Java  language  processors  combine  compilation  and  interpreta 
tion,  as  shown  in  Fig.  1.4.  A  Java  source  program  may  first  be  compiled  into 
an  intermediate  form  called  bytecodes.  The  bytecodes  are  then  interpreted  by  a 
virtual  machine.  A  benefit  of  this  arrangement  is  t h at  bytecodes  compiled  on 
one  machine  can  be  interpreted  on  another  machine,  perhaps  across  a  network. 
In  order  to  achieve  faster  processing  of inputs  to  outputs,  some  Java  compil 

ers,  called  just-in-time  compilers,  translate  the  bytecodes  into  machine  language 
• 
immediately  before  they  run  the  intermediate  program  to  process  the  input. 

1.1. 

LANGUAGE  PROCESSORS 

3 

source  program 

Translator 

intermediate program —»H 

input  —*A 

Virtual 
Machine 

output 

Figure  1.4:  A  hybrid  compiler 

In  addition  to  a  compiler,  several  other  programs  may  be  required  to  create 
an  executable  target  program,  as  shown  in  Fig.  1.5.  A  source  program  may  be 
divided  into  modules  stored  in  separate  files.  The  task  of  collecting  the  source 
program  is  sometimes  entrusted  to  a  separate  program,  called  a  preprocessor. 
The  preprocessor  may  also  expand  shorthands,  called  macros,  into  source  lan 
guage  statements. 

T he  modified  source  program  is  then  fed  to  a  compiler.  The  compiler  may 
produce  an  assembly-language  program  as  its  output,  because  assembly  lan 
guage  is  easier  to  produce  as  output  and  is  easier  to  debug.  The  assembly 
language  is  then  processed  by  a  program  called  an  assembler  t h at  produces 
relocatable  machine  code  as  its  output. 

Large  programs  are  often  compiled  in  pieces,  so  the  relocatable  machine 
code  may  have  to  be  linked  together  with  other  relocatable  object  files  and 
library  files  into  the  code  t h at  actually  runs  on  the  machine.  The  linker resolves 
external  memory  addresses,  where  t he  code  in  one  file  may  refer  to  a  location 
in  another  file.  T he  loader  then  puts  together  all  of  the  executable  object  files 
into  memory  for  execution. 

1.1.1  Exercises  for  Section  1.1 

E x e r c i se  1 . 1 . 1:  W h at  is  the  difference  between  a  compiler  and  an  interpreter? 

E x e r c i se  1 . 1 . 2:  W h at  are  the  advantages  of  (a)  a  compiler  over  an  interpreter 
(b)  an  interpreter  over  a  compiler? 

E x e r c i se  1.1.3  :  W h at  advantages  are  there  to  a  language-processing  system  in 
which  the  compiler  produces  assembly  language  rather  t h an  machine  language? 

E x e r c i se  1 . 1 . 4:  A  compiler  t h at  translates  a  high-level  language  into  another 
high-level  language  is  called  a  source-to-source  translator.  W h at  advantages  are 
there  to  using  C  as  a  target  language  for  a  compiler? 

E x e r c i se  1 . 1 . 5:  Describe  some  of  the  tasks  t h at  an  assembler  needs  to  per 
form. 

4 

CHAPTER 

1. 

INTRODUCTION 

source  program 

L_ 
Preprocessor 

modified  source  program 

Compiler 

target  assembly  program 

L_ 
Assembler 

relocatable  machine  code 

i 
Linker/Loader 
T 
target  machine  code 

library  files 
relocatable  object  files 

Figure  1.5:  A  language-processing  system 

1.2  The  Structure  of  a  Compiler 

Up  to  this  point  we  have  treated  a  compiler  as  a  single  box  t h at  maps  a  source 
program  into  a  semantically  equivalent  target  program.  If  we  open  up  this  box 
a  little,  we  see  t h at  there  are  two  parts  to  this  mapping:  analysis  and  synthesis. 

T he  analysis  part  breaks  up  the  source  program  into  constituent  pieces  and 
imposes  a  grammatical  structure  on  them.  It  then  uses  this  structure  to  cre 
ate  an  intermediate  representation  of  t he  source  program.  If  the  analysis  part 
detects  t h at  t he  source  program  is  either  syntactically  ill  formed  or  semanti 
cally  unsound,  then  it  must  provide  informative  messages,  so  the  user  can  take 
corrective  action.  T he  analysis  part  also  collects  information  about  t he  source 
program  and  stores  it  in  a  d a ta  structure  called  a  symbol  table,  which  is  passed 
along  with  the  intermediate  representation  to  t he  synthesis  part. 

The  synthesis  part  constructs  the  desired  target  program  from  the  interme 
diate  representation  and  the  information  in  t he  symbol  table.  T he  analysis  part 
is  often  called  the  front  end  of  the  compiler;  the  synthesis  p a rt  is  t he  back  end. 

If we  examine  the  compilation  process  in  more  detail,  we  see  t h at  it  operates 
as  a  sequence  of  phases,  each  of  which  transforms  one  representation  of  t he 
source  program  to  another.  A  typical  decomposition  of  a  compiler  into  phases 
is  shown  in  Fig.  1.6. 
In  practice,  several  phases  may  be  grouped  together, 
and  the  intermediate  representations  between  t he  grouped  phases  need  not  be 
constructed  explicitly.  T he  symbol  table,  which  stores  information  about  t he 

1.2. 

THE  STRUCTURE  OF  A  COMPILER 

5 

character  stream 

i 

Lexical  Analyzer 

token  stream 

Syntax  Analyzer 

syntax  tree 

Semantic  Analyzer 

syntax  tree 

Symbol  Table 

Intermediate  Code  Generator 

intermediate  representation 
i 
Machine-Independent 
Code  Optimizer 

intermediate  representation 
i 
Code  Generator 

target-machine  code 
i 
Machine-Dependent 
Code  Optimizer 

target-machine  code 

Figure  1.6:  Phases  of  a  compiler 

entire  source  program,  is  used  by  all  phases  of  the  compiler. 

Some  compilers  have  a  machine-independent  optimization  phase  between 

the  front  end  and  the  back  end.  The  purpose  of  this  optimization  phase  is  to 
perform  transformations  on  t he  intermediate  representation,  so  t h at  the  back 
end  can  produce  a  better  target  program  t h an  it  would  have  otherwise  pro 
duced  from  an  unoptimized  intermediate  representation.  Since  optimization  is 
optional,  one  or  the  other  of the  two  optimization  phases  shown  in  Fig.  1.6  may 
be  missing. 

1.2.1  Lexical  Analysis 

T he  first  phase  of  a  compiler  is  called  lexical  analysis  or  scanning.  The  lex 
ical  analyzer  reads  the  stream  of  characters  making  up  the  source  program 

6 

CHAPTER 

1. 

INTRODUCTION 

and  groups  the  characters  into  meaningful  sequences  called  lexemes.  For  each 
lexeme,  the  lexical  analyzer  produces  as  output  a  token  of  t he  form 

(token-name, 

attribute-value) 

t h at  it  passes  on  to  the  subsequent  phase,  syntax  analysis.  In  the  token,  the 
first  component  token-name  is  an  abstract  symbol  t h at  is  used  during  syntax 
analysis,  and  t he  second  component  attribute-value  points  to  an  entry  in  t he 
symbol  table  for  this  token.  Information  from  the  symbol-table  entry Is  needed 
for  semantic  analysis  and  code  generation. 

For  example,  suppose  a  source  program  contains  t he  assignment  statement 

p o s i t i on  =  i n i t i al  +  r a te  *  60 

(1.1) 

The  characters  in  this  assignment  could  be  grouped  into  the  following  lexemes 
and  mapped  into  the  following  tokens  passed  on  to  the  syntax  analyzer: 

1.  p o s i t i on  is  a  lexeme  t h at  would  be  mapped  into  a  token  (id,  1),  where  id 
is  an  abstract  symbol  standing  for  identifier  and  1  points  to  t he  symbol-
table  entry  for  p o s i t i o n.  T he  symbol-table  entry  for  an  identifier  holds 
information  about  the  identifier,  such  as  its  name  and  type. 

2.  The  assignment  symbol  =  is  a  lexeme  t h at  is  m a p p ed  into  t he  token  ( = ). 
Since  this  token  needs  no  attribute-value,  we  have  omitted  t he  second 
component.  We  could  have  used  any  abstract  symbol  such  as  a s s i gn  for 
t he  token-name,  but  for  notational  convenience  we  have  chosen  to  use  t he 
lexeme  itself  as  the  name  of  the  abstract  symbol. 

3.  i n i t i al  is  a  lexeme  t h at  is  m a p p ed  into  the  token  (id,  2),  where  2  points 

to  the  symbol-table  entry  for  i n i t i a l. 

4.  +  is  a  lexeme  t h at  is  m a p p ed  into  t he  token  ( + ). 

5.  r a te  is  a  lexeme  t h at  is  mapped  into  the  token  (id, 3),  where  3  points  to 

the  symbol-table  entry  for  r a t e. 

6.  *  is  a  lexeme  t h at  is  mapped  into  the  token  (*). 

7.  60  is  a  lexeme  t h at  is  mapped  into  the  token  (60).1 

Blanks  separating  the  lexemes  would  be  discarded  by  the  lexical  analyzer. 

Figure  1.7  shows  the  representation  of  the  assignment  statement  (1.1)  after 

lexical  analysis  as  t he  sequence  of  tokens 

( i d , l)  <=)  (id, 2)  (+)  (id, 3)  (*)  (60) 

(1.2) 

In  this  representation,  the  token  names  =,  +,  and  *  are  abstract  symbols  for 
the  assignment,  addition,  and  multiplication  operators,  respectively. 

1 Technically  speaking,  for  the  lexeme  60  we  should  make  up  a  token  like  (number, 4 ), 
where  4  points  to  the  symbol  table  for  the  internal  representation  of  integer  60  but  we  shall 
defer  the  discussion  of  tokens  for  numbers  until  Chapter  2.  Chapter  3  discusses  techniques 
for  building  lexical  analyzers. 

THE  STRUCTURE  OF  A  COMPILER 

position  =  initial  +  rate  *  60 

i 
Lexical  Analyzer 

(id,l>  {=)  <id,2>  <+)  <id,3> (.> (60) 

* 
Syntax  Analyzer 

<id,l) 

(id,2)-

+ 

(id,3) 

60 

Semantic  Analyzer 

position 
initial 
rate 

S Y M B OL  T A B LE 

(id,l) 

(id, 2) 

(id, 3} 

inttofloat 
I 
60 

Intermediate  Code  Generator 

tl  =  inttofloat(60) 
t2  =  id3  *  tl 
t3  =  id2  +  t2 
idl  =  t3 

i 
Code  Optimizer 

tl  =  id3  *  60.0 
idl  =  id2  +  tl 

i 
Code  Generator 

LDF  R2,  id3 
MULF R 2,  R2,  #60.0 
LDF  Rl,  id2 
ADDF Rl,  Rl,  R2 
STF  idl,  Rl 

Figure  1.7:  Translation  of  an  assignment  statement 

8 

CHAPTER 

1. 

INTRODUCTION 

1.2.2  Syntax  Analysis 

The  second  phase  of  the  compiler  is  syntax  analysis  or  parsing.  T he  parser  uses 
the  first  components  of  t he  tokens  produced  by  t he  lexical  analyzer  to  create 
a  tree-like  intermediate  representation  t h at  depicts  t he  grammatical  structure 
of  the  token  stream.  A  typical  representation  is  a  syntax  tree  in  which  each 
interior  node  represents  an  operation  and  the  children  of the  node  represent  t he 
arguments  of  the  operation.  A  syntax  tree  for  the  token  stream  (1.2)  is  shown 
as  t he  output  of  the  syntactic  analyzer  in  Fig.  1.7. 

This  tree  shows  the  order  in  which  the  operations  in  the  assignment 

p o s i t i on  =  i n i t i al  +  r a te  *  60 

are  to  be  performed.  T he  tree  has  an  interior  node  labeled  *  with  (id, 3)  as 
its  left  child  and  the  integer  60  as  its  right  child.  The  node  (id, 3)  represents 
the  identifier  r a t e.  The  node  labeled  *  makes  it  explicit  t h at  we  must  first 
multiply  the  value  of  r a te  by  60.  The  node  labeled  +  indicates  t h at  we  must 
add  the  result  of  this  multiplication  to  the  value  of  i n i t i a l.  The  root  of  the 
tree,  labeled  =,  indicates  t h at  we  must  store  t he  result  of this  addition  into  t he 
location  for  the  identifier  p o s i t i o n.  This  ordering  of  operations  is  consistent 
with  the  usual  conventions  of  arithmetic  which  tell  us  t h at  multiplication  has 
higher  precedence  t h an  addition,  and  hence  t h at  the  multiplication  is  to  be 
performed  before  the  addition. 

T he  subsequent  phases  of t he  compiler  use  t he  grammatical  structure  to  help 
analyze  the  source  program  and  generate  the  target  program. 
In  Chapter  4 
we  shall  use  context-free  grammars  to  specify  t he  grammatical  structure  of 
programming  languages  and  discuss  algorithms  for  constructing  efficient  syntax 
analyzers  automatically  from  certain  classes  of grammars.  In  Chapters  2  and  5 
we  shall  see  t h at  syntax-directed  definitions  can  help  specify  t he  translation  of 
programming  language  constructs. 

1.2.3  Semantic  Analysis 

T he  semantic  analyzer  uses  the  syntax  tree  and  the  information  in  the  symbol 
table  to  check  the  source  program  for  semantic  consistency  with  the  language 
definition.  It  also  gathers  type  information  and  saves  it  in  either  the  syntax  tree 
or  the  symbol  table,  for  subsequent  use  during  intermediate-code  generation. 

An  important  part  of  semantic  analysis  is  type  checking,  where  the  compiler 
checks  t h at  each  operator  has  matching  operands.  For  example,  many  program 
ming  language  definitions  require  an  array  index  to  be  an  integer;  t he  compiler 
must  report  an  error  if  a  floating-point  number  is  used  to  index  an  array. 

The  language  specification  may  permit  some  type  conversions  called  coer 
cions.  For  example,  a  binary  arithmetic  operator  may  be  applied  to  either  a 
pair  of integers  or  to  a  pair  of floating-point  numbers.  If t he  operator  is  applied 
to  a  floating-point  number  and  an  integer,  the  compiler  may  convert  or  coerce 
t he  integer  into  a  floating-point  number. 

1.2. 

THE  STRUCTURE  OF  A  COMPILER 

9 

Such  a  coercion  appears  in  Fig.  1.7.  Suppose  t h at  p o s i t i o n,  i n i t i a l,  and 
r a te  have  been  declared  to  be  floating-point  numbers,  and  t h at  the  lexeme  60 
by  itself forms  an  integer.  The  type  checker  in  the  semantic  analyzer  in  Fig.  1.7 
discovers  t h at  the  operator  *  is  applied  to  a  floating-point  number  r a te  and 
an  integer  60.  In  this  case,  t he  integer  may  be  converted  into  a  floating-point 
number. 
In  Fig.  1.7,  notice  t h at  t he  o u t p ut  of  t he  semantic  analyzer  has  an 
extra  node  for  the  operator  inttofloat,  which  explicitly  converts  its  integer 
argument  into  a  floating-point  number.  Type  checking  and  semantic  analysis 
are  discussed  in  Chapter  6. 

1.2.4 

Intermediate  Code  Generation 

In  the  process  of translating  a  source  program  into  target  code,  a  compiler  may 
construct  one  or  more  intermediate  representations,  which  can  have  a  variety 
of  forms.  Syntax  trees  are  a  form  of  intermediate  representation;  they  are 
commonly  used  during  syntax  and  semantic  analysis. 

After  syntax  and  semantic  analysis  of  the  source  program,  many  compil 

ers  generate  an  explicit  low-level  or  machine-like  intermediate  representation, 
which  we  can  think  of  as  a  program  for  an  abstract  machine.  This  intermedi 
ate  representation  should  have  two  important  properties:  it  should  be  easy  to 
produce  and  it  should  be  easy  to  translate  into  the  target  machine. 

In  Chapter  6,  we  consider  an  intermediate  form  called  three-address  code, 
which  consists  of  a  sequence  of  assembly-like  instructions  with  three  operands 
per  instruction.  Each  operand  can  act  like  a  register.  T he  output  of  the  inter 
mediate  code  generator  in  Fig.  1.7  consists  of  t he  three-address  code  sequence 

tl  •• 
t2 •• 
ts •• 
i dl 

i n t t o f l o a t ( 6 0) 
tl 
i d3  * 
i d2  +  t2 
t3 

(1.3) 

There  are  several  points  worth  noting  about  three-address  instructions. 
First,  each  three-address  assignment  instruction  has  at  most  one  operator  on  the 
right  side.  Thus,  these  instructions  fix  the  order  in  which  operations  are  to  be 
done;  t he  multiplication  precedes  t he  addition  in  t he  source  program  (1.1).  Sec 
ond,  t he  compiler  must  generate  a  temporary  name  to  hold  the  value  computed 
by  a  three-address  instruction.  Third,  some  "three-address  instructions"  like 
the  first  and  last  in  the  sequence  (1.3),  above,  have  fewer  t h an  three  operands. 

In  Chapter  6,  we  cover  the  principal  intermediate  representations  used  in 
compilers.  Chapters  5  introduces  techniques  for  syntax-directed  translation 
t h at  are  applied  in  Chapter  6  to  type  checking  and  intermediate-code  generation 
for typical programming language constructs such  as expressions,  flow-of-control 
constructs,  and  procedure  calls. 

10 

CHAPTER 

1. 

INTRODUCTION 

1.2.5  Code  Optimization 

The  machine-independent  code-optimization  phase  a t t e m p ts  to  improve  t he 
intermediate  code  so  t h at  better  target  code  will  result.  Usually  better  means 
faster,  but  other  objectives  may  be  desired,  such  as  shorter  code,  or  target  code 
t h at  consumes  less  power.  For  example,  a  straightforward  algorithm  generates 
the  intermediate  code  (1.3),  using  an  instruction  for  each  operator  in  the  tree 
representation  t h at  comes  from  t he  semantic  analyzer. 

A  simple  intermediate  code  generation  algorithm  followed  by  code  optimiza 
tion  is  a  reasonable  way  to  generate  good  target  code.  T he  optimizer  can  deduce 
t h at  the  conversion  of 60  from  integer  to  floating  point  can  be  done  once  and  for 
all  at  compile  time,  so  the inttofloat  operation  can  be  eliminated  by  replacing 
the  integer  60  by  t he  floating-point  number  60.0.  Moreover, t3  is  used  only 
once  to  transmit  its  value  to  i dl  so  t he  optimizer  can  transform  (1.3)  into  t he 
shorter  sequence 

tl  =  id3  *  60.0 

idl  =  id2  + tl 

(1.4) 

There  is  a  great  variation  in  the  amount  of  code  optimization  different  com 
pilers  perform.  In  those  t h at  do  the  most,  the  so-called  "optimizing  compilers," 
a  significant  amount  of  time  is  spent  on  this  phase.  There  are  simple  opti 
mizations  t h at  significantly  improve  the  running  time  of  the  target  program 
without  slowing  down  compilation  too  much.  T he  chapters  from  8  on  discuss 
machine-independent  and  machine-dependent  optimizations  in  detail. 

1.2.6  Code  Generation 

The  code  generator  takes  as  input  an  intermediate  representation  of  t he  source 
program  and  maps  it  into  the  target  language.  If the  target  language  is  machine 
code,  registers  Or  memory  locations  are  selected  for  each  of t he  variables  used  by 
the  program.  Then,  the  intermediate  instructions  are  translated  into  sequences 
of  machine  instructions  t h at  perform  t he  same  task.  A  crucial  aspect  of  code 
generation  is  the  judicious  assignment  of  registers  to  hold  variables. 

For  example,  using  registers  Rl  and R2,  the  intermediate  code  in  (1.4)  might 

get  translated  into  t he  machine  code 

LDF  R2,  id3 
MULF R2,  R2,  #60.0 
LDF  Rl,  id2 
ADDF Rl,  Rl,  R2 
STF  idl,  Rl 

(1.5) 

The  first  operand  of  each  instruction  specifies  a  destination.  T he F  in  each 
instruction  tells  us  t h at  it  deals  with  floating-point  numbers.  T he  code  in 

1.2. 

THE  STRUCTURE  OF  A  COMPILER 

11 

(1.5)  loads  t he  contents  of  address  i d3  into  register  R2,  then  multiplies  it  with 
floating-point  constant  60.0.  T he  #  signifies  t h at  60.0  is  to  be  treated  as  an 
immediate  constant.  The  third  instruction  moves  i d2  into  register  Rl  and  t he 
fourth  adds  to  it  the  value  previously  computed  in  register  R2.  Finally,  the  value 
in  register  Rl  is  stored  into  the  address  of  i d l,  so  the  code  correctly  implements 
t he  assignment  statement  (1.1).  Chapter  8  covers  code  generation. 

This  discussion  of  code  generation  has  ignored  t he  important  issue  of  stor 
age  allocation  for  the  identifiers  in  the  source  program.  As  we  shall  see  in 
Chapter  7,  the  organization  of storage  at  run-time  depends  on  the  language  be 
ing  compiled.  Storage-allocation  decisions  are  made  either  during  intermediate 
code  generation  or  during  code  generation. 

1.2.7 

Symbol-Table  Management 

An  essential  function  of  a  compiler  is  to  record  t he  variable  names  used  in  t he 
source  program  and  collect  information  about  various  attributes  of  each  name. 
These  attributes  may  provide  information  about  the  storage  allocated  for  a 
name,  its  type,  its  scope  (where  in  the  program  its  value  may  be  used),  and 
in  t he  case  of  procedure  names,  such  things  as  the  number  and  types  of  its 
arguments,  t he  method  of  passing  each  argument  (for  example,  by  value  or  by 
reference),  and  the  type  returned. 

T he  symbol  table  is  a  d a ta  structure  containing  a  record  for  each  variable 
name,  with  fields  for  the  attributes  of  the  name.  The  d a ta  structure  should  be 
designed  to  allow  the  compiler  to  find  t he  record  for  each  name  quickly  and  to 
store  or  retrieve  d a ta  from  t h at  record  quickly.  Symbol  tables  are  discussed  in 
Chapter  2. 

1.2.8  The  Grouping  of  Phases  into  Passes 

T he  discussion  of  phases  deals  with  the  logical  organization  of  a  compiler.  In 
an  implementation,  activities  from  several  phases  may  be  grouped  together 
into  a  pass  t h at  reads  an  input  file  and  writes  an  output  file.  For  example, 
the  front-end  phases  of  lexical  analysis,  syntax  analysis,  semantic  analysis,  and 
intermediate  code  generation  might  be  grouped  together  into  one  pass.  Code 
optimization  might  be  an  optional  pass.  T h en  there  could  be  a  back-end  pass 
consisting  of  code  generation  for  a  particular  target  machine. 

Some  compiler  collections  have  been  created  around  carefully  designed  in 
termediate  representations  t h at  allow  the  front  end  for  a  particular  language  to 
interface  with  the  back  end  for  a  certain  target  machine.  W i th  these  collections, 
we  can  produce  compilers  for  different  source  languages  for  one  target  machine 
by  combining  different  front  ends  with  the  back  end  for  t h at  target  machine. 
Similarly,  we  can  produce  compilers  for  different  target  machines,  by  combining 
a  front  end  with  back  ends  for  different  target  machines. 

12 

CHAPTER 

1. 

INTRODUCTION 

1.2.9  Compiler-Construction  Tools 

T he  compiler  writer,  like  any  software  developer,  can  profitably  use  modern 
software  development  environments  containing  tools  such  as  language  editors, 
debuggers,  version  managers,  profilers,  test  harnesses,  and  so  on.  In  addition 
to  these  general  software-development  tools,  other  more  specialized  tools  have 
been  created  to  help  implement  various  phases  of  a  compiler. 

These  tools  use  specialized  languages  for  specifying  and  implementing  spe 
cific  components,  and  many  use  quite  sophisticated  algorithms.  T he  most  suc 
cessful  tools  are  those  t h at  hide  the  details  of  t he  generation  algorithm  and 
produce  components  t h at  can  be  easily  integrated  into  the  remainder  of  t he 
compiler.  Some  commonly  used  compiler-construction  tools  include 

1.  Parser  generators  t h at  automatically  produce  syntax  analyzers  from  a 

grammatical  description  of  a  programming  language. 

2.  Scanner  generators  t h at  produce  lexical  analyzers  from  a  regular-expres 

sion  description  of  t he  tokens  of  a  language. 

3.  Syntax-directed 

translation  engines 

t h at  produce  collections  of  routines 

for  walking  a  parse  tree  and  generating  intermediate  code. 

4.  Code-generator  generators  t h at  produce  a  code  generator  from  a  collection 
of  rules  for  translating  each  operation  of  the  intermediate  language  into 
the  machine  language  for  a  target  machine. 

5.  Data-flow  analysis  engines  t h at  facilitate 

the  gathering  of  information 
about  how  values  are  transmitted  from  one  p a rt  of  a  program  to  each 
other  part.  Data-flow  analysis  is  a  key  part  of  code  optimization. 

6.  Compiler-construction 

toolkits  t h at  provide  an  integrated  set  of  routines 

for  constructing  various  phases  of  a  compiler. 

We  shall  describe  many  of  these  tools  throughout  this  book. 

1.3  The  Evolution  of  Programming  Languages 

The  first  electronic  computers  appeared  in  t he  1940's  and  were  programmed  in 
machine  language  by  sequences  of  O's  and  l 's  t h at  explicitly  told  t he  computer 
what  operations  to  execute  and  in  what  order.  T he  operations  themselves 
were  very  low  level:  move  d a ta  from  one  location  to  another,  add  t he  contents 
of  two  registers,  compare  two  values,  and  so  on.  Needless  to  say,  this  kind 
of  programming  was  slow,  tedious,  and  error  prone.  And  once  written,  t he 
programs  were  hard  to  understand  and  modify. 

1.3. 

THE  EVOLUTION  OF  PROGRAMMING  LANGUAGES 

13 

1.3.1  The  Move  to  Higher-level  Languages 

T he  first  step  towards  more  people-friendly  programming  languages  was  t he 
development  of  mnemonic  assembly  languages  in  the  early  1950's. 
Initially, 
the  instructions  in  an  assembly  language  were  just  mnemonic  representations 
of  machine  instructions.  Later,  macro  instructions  were  added  to  assembly 
languages  so  t h at  a  programmer  could  define  parameterized  shorthands  for 
frequently  used  sequences  of  machine  instructions. 

A  major  step  towards  higher-level  languages  was  made  in  the  latter  half  of 
the  1950's  with  the  development  of  Fortran  for  scientific  computation,  Cobol 
for  business  d a ta  processing,  and  Lisp  for  symbolic  computation.  T he  philos 
ophy  behind  these  languages  was  to  create  higher-level  notations  with  which 
programmers  could  more  easily  write  numerical  computations,  business  appli 
cations,  and  symbolic  programs.  These  languages  were  so  successful  t h at  they 
are  still  in  use  today. 

In  the  following  decades,  many  more  languages  were  created  with  innovative 
features  to  help  make  programming  easier,  more  natural,  and  more  robust. 
Later  in  this  chapter,  we  shall  discuss  some  key  features  t h at  are  common  to 
many  modern  programming  languages. 

languages  are 

Fourth-generation 

Today,  there  are  thousands  of  programming  languages.  They  can  be  classi 
fied  in  a  variety  of  ways.  One  classification  is  by  generation.  First-generation 
languages  are  the  machine  languages,  second-generation  the  assembly  languages, 
third-generation  the  higher-level  languages  like  Fortran,  Cobol,  Lisp,  C, 
and 
C + +,  C #,  and  Java. 
languages  designed 
for  specific  applications  like  NOMAD  for  report  generation,  SQL  for  database 
queries,  and  Postscript  for  text  formatting.  The  term  fifth-generation  language 
has  been  applied  to  logic-  and  constraint-based  languages  like  Prolog  and  O P S 5. 
Another  classification  of  languages  uses  the  term  imperative  for  languages 
in  which  a  program  specifies  how  a  computation  is  to  be  done  and  declarative 
for  languages  in  which  a  program  specifies  what  computation  is  to  be  done. 
Languages  such  as  C,  C + +,  C #,  and  Java  are  imperative  languages.  In  imper 
ative  languages  there  is  a  notion  of  program  state  and  statements  t h at  change 
the  state.  Functional  languages  such  as  ML  and  Haskell  and  constraint  logic 
languages  such  as  Prolog  are  often  considered  to  be  declarative  languages. 

T he 

t e rm  von  Neumann 

language  is  applied 
whose  computational  model  is  based  on  t he  von  Neumann  computer  archi 
tecture.  Many  of  today's  languages,  such  as  Fortran  and  C  are  von  Neumann 
languages. 

to  programming  languages 

An  object-oriented  language  is  one  t h at  supports  object-oriented  program 
ming,  a  programming  style  in  which  a  program  consists  of a  collection  of objects 
t h at  interact  with  one  another.  Simula  67  and  Smalltalk  are  t he  earliest  major 
object-oriented  languages.  Languages  such  as  C + +,  C #,  Java,  and  Ruby  are 
more  recent  object-oriented  languages. 

Scripting  languages  are  interpreted  languages  with  high-level  operators  de 
signed  for  "gluing  together"  computations.  These  computations  were  originally 

14 

CHAPTER 

1. 

INTRODUCTION 

called  "scripts."  Awk,  JavaScript,  Perl,  P H P,  Python,  Ruby,  and  Tel  are  pop 
ular  examples  of  scripting  languages.  Programs  written  in  scripting  languages 
are  often  much  shorter  t h an  equivalent  programs  written  in  languages  like  C. 

1.3.2 

Impacts  on  Compilers 

Since  the  design  of programming  languages  and  compilers  are  intimately  related, 
the  advances  in  programming  languages  placed  new  demands  on  compiler  writ 
ers.  They  had  to  devise  algorithms  and  representations  to  translate  and  support 
the  new  language  features.  Since  the  1940's,  computer  architecture  has  evolved 
as  well.  Not  only  did  the  compiler  writers  have  to  track  new  language  fea 
tures,  they  also  had  to  devise  translation  algorithms  t h at  would  take  maximal 
advantage  of  the  new  hardware  capabilities. 

Compilers  can  help  promote  the  use  of  high-level  languages  by  minimizing 
the  execution  overhead  of  the  programs  written  in  these  languages.  Compilers 
are  also  critical  in  making  high-performance  computer  architectures  effective 
In  fact,  the  performance  of  a  computer  system  is  so 
on  users'  applications. 
dependent  on  compiler  technology t h at  compilers  are  used  as  a  tool  in  evaluating 
architectural  concepts  before  a  computer  is  built. 

Compiler  writing  is  challenging.  A  compiler  by  itself  is  a  large  program. 
Moreover,  many  modern  language-processing  systems  handle  several  source  lan 
guages  and  target  machines  within  the  same  framework;  t h at  is,  they  serve  as 
collections  of  compilers,  possibly  consisting  of  millions  of  lines  of  code.  Con 
sequently,  good  software-engineering  techniques  are  essential  for  creating  and 
evolving  modern  language  processors. 

A  compiler  must  translate  correctly  the  potentially  infinite  set  of  programs 
t h at  could  be  written  in  the  source  language.  T he  problem  of  generating  t he 
optimal  target  code  from  a  source  program  is  undecidable  in  general;  thus, 
compiler  writers  must  evaluate  tradeoffs  about  what  problems  to  tackle  and 
what  heuristics  to  use  to  approach  t he  problem  of  generating  efficient  code. 

A  study  of  compilers  is  also  a  study  of  how  theory  meets  practice,  as  we 

shall  see  in  Section  1.4. 

T he  purpose  of  this  text  is  to  teach  the  methodology  and  fundamental  ideas 
used  in  compiler  design. 
It  is  not  t he  intention  of  this  text  to  teach  all  t he 
algorithms  and  techniques  t h at  could  be  used  for  building  a  state-of-the-art 
language-processing  system.  However,  readers  of this  text  will  acquire  t he  basic 
knowledge  and  understanding  to  learn  how  to  build  a  compiler  relatively  easily. 

1.3.3  Exercises  for  Section  1.3 

E x e r c i se  1 . 3 . 1:  Indicate  which  of  the following terms: 

a)  imperative 
d)  object-oriented 
g) 

b)  declarative 
b)  declaratf 
e)  functional 
e)  functiona 
fourth-generation  h)  scripting 

c)  von  Neumann 
f)  third-generation 

1.4. 

THE  SCIENCE  OF  BUILDING  A  COMPILER 

15 

apply  to  which  of  t he  following  languages: 

1)  C 
6)  Lisp 

2)  C ++ 
7)  ML 

3)  Cobol 
8)  Perl 

4)  Fortran 
9)  P y t h on 

5)  Java 
10)  V B. 

1.4  The  Science  of Building  a  Compiler 

Compiler  design  is  full  of beautiful  examples  where  complicated  real-world  prob 
lems  are  solved by  abstracting t he  essence  of the  problem  mathematically.  These 
serve  as  excellent  illustrations  of  how  abstractions  can  be  used  to  solve  prob 
lems:  take  a  problem,  formulate  a  mathematical  abstraction  t h at  captures  t he 
key  characteristics,  and  solve  it  using  mathematical  techniques.  The  problem 
formulation  must  be  grounded  in  a  solid  understanding  of  the  characteristics  of 
computer  programs,  and  t he  solution  must  be  validated  and  refined  empirically. 
A  compiler  must  accept  all  source  programs  t h at  conform  to  the  specification 
of  the  language;  the  set  of  source  programs  is  infinite  and  any  program  can  be 
very  large,  consisting  of  possibly  millions  of  lines  of  code.  Any  transformation 
performed  by  the  compiler  while  translating  a  source  program  must  preserve  the 
meaning  of  t he  program  being  compiled.  Compiler  writers  thus  have  influence 
over  not  just  the  compilers  they  create,  but  all  the  programs  t h at  their  com 
pilers  compile.  This  leverage  makes  writing  compilers  particularly  rewarding; 
however,  it  also  makes  compiler  development  challenging. 

1.4.1  Modeling  in  Compiler  Design  and  Implementation 

T he  study  of  compilers  is  mainly  a  study  of  how  we  design  the  right  mathe 
matical  models  and  choose  the  right  algorithms,  while  balancing  the  need  for 
generality  and  power  against  simplicity  and  efficiency. 

Some  of  most  fundamental  models  are  finite-state  machines  and  regular 
expressions,  which  we  shall  meet  in  Chapter  3.  These  models  are  useful  for  de 
scribing  t he  lexical  units  of  programs  (keywords,  identifiers,  and  such)  and  for 
describing  t he  algorithms  used  by  the  compiler  to  recognize  those  units.  Also 
among  the  most  fundamental  models  are  context-free  grammars,  used  to  de 
scribe  the  syntactic  structure  of  programming  languages  such  as  the  nesting  of 
parentheses  or  control  constructs.  We  shall  study  grammars  in  Chapter  4.  Sim 
ilarly,  trees  are  an  important  model  for  representing  t he  structure  of  programs 
and  their  translation  into  object  code,  as  we  shall  see  in  Chapter  5. 

1.4.2  The  Science  of  Code  Optimization 

T he  term  "optimization"  in  compiler  design  refers  to  t he  a t t e m p ts  t h at  a  com 
piler  makes  to  produce  code  t h at  is  more  efficient  t h an  the  obvious  code.  "Op 
timization"  is  thus  a  misnomer,  since  there  is  no  way  t h at  the  code  produced 
by  a  compiler  can  be  guaranteed  to  be  as  fast  or  faster  t h an  any  other  code 
t h at  performs  the  same  task. 

16 

CHAPTER!. 

INTRODUCTION 

In  modern  times,  the  optimization  of  code  t h at  a  compiler  performs  has 
become  both  more  important  and  more  complex.  It  is  more  complex  because 
processor  architectures  have  become  more  complex,  yielding  more  opportunities 
to  improve  the  way  code  executes.  It  is  more  important  because  massively  par 
allel  computers  require  substantial  optimization,  or  their  performance  suffers  by 
orders  of  magnitude.  W i th  the  likely  prevalence  of  multicore  machines  (com 
puters  with  chips  t h at  have  large  numbers  of processors  on  t h e m ),  all  compilers 
will  have  to  face  the  problem  of  taking  advantage  of  multiprocessor  machines. 
It  is  hard,  if  not  impossible,  to  build  a  robust  compiler  out  of  "hacks." 
Thus,  an  extensive  and  useful  theory  has  been  built  up  around  the  problem  of 
optimizing  code.  T he  use  of  a  rigorous  mathematical  foundation  allows  us  to 
show  t h at  an  optimization  is  correct  and  t h at  it  produces  the  desirable  effect 
for  all  possible  inputs.  We  shall  see,  starting  in  Chapter  9,  how  models  such 
as  graphs,  matrices,  and  linear  programs  are  necessary  if  the  compiler  is  to 
produce  well  optimized  code. 

On  the  other  hand,  pure  theory  alone  is  insufficient.  Like  many  real-world 
In  fact,  most  of  the  questions  t h at 
problems,  there  are  no  perfect  answers. 
we  ask  in  compiler  optimization  are  undecidable.  One  of  t he  most  important 
skills  in  compiler  design  is  the  ability  to  formulate  t he  right  problem  to  solve. 
We  need  a  good  understanding  of  the  behavior  of  programs  to  start  with  and 
thorough  experimentation  and  evaluation  to  validate  our  intuitions. 

Compiler  optimizations  must  meet  the  following  design  objectives: 

•  T he  optimization  must  be  correct,  t h at  is,  preserve  the  meaning  of  t he 

compiled  program, 

•  T he  optimization  must  improve  t he  performance  of  many  programs, 

•  The  compilation  time  must  be  kept  reasonable,  and 

•  The  engineering  effort  required  must  be  manageable. 

It  is  impossible  to  overemphasize  the  importance  of  correctness.  It  is  trivial 
to  write  a  compiler  t h at  generates  fast  code  if  the  generated  code  need  not 
be  correct!  Optimizing  compilers  are  so  difficult  to  get  right  t h at  we  dare  say 
t h at  no  optimizing  compiler  is  completely  error-free!  Thus,  t he  most  important 
objective  in  writing  a  compiler  is  t h at  it  is  correct. 

The  second  goal  is  t h at  the  compiler  must  be  effective  in  improving  the  per 
formance  of  many  input  programs.  Normally,  performance  means  t he  speed  of 
the  program  execution.  Especially  in  embedded  applications,  we  may  also  wish 
to  minimize  t he  size  of  the  generated  code.  And  in  the  case  of  mobile  devices, 
it  is  also  desirable  t h at  t he  code  minimizes  power  consumption.  Typically,  t he 
same  optimizations  t h at  speed  up  execution  time  also  conserve  power.  Besides 
performance,  usability  aspects  such  as  error  reporting  and  debugging  are  also 
important. 

Third,  we  need  to  keep  the  compilation  time  short  to  support  a  rapid  devel 
opment  and  debugging  cycle.  This  requirement  has  become  easier  to  meet  as 

1.5. 

APPLICATIONS  OF  COMPILER 

TECHNOLOGY 

17 

machines  get  faster.  Often,  a  program  is  first  developed  and  debugged  without 
program  optimizations.  Not  only  is  the  compilation  time  reduced,  but  more 
importantly,  unoptimized  programs  are  easier  to  debug,  because  the  optimiza 
tions  introduced  by  a  compiler  often  obscure  the  relationship  between  the  source 
code  and  t he  object  code.  Turning  on  optimizations  in  the  compiler  sometimes 
exposes  new  problems  in  the  source  program;  thus  testing  must  again  be  per 
formed  on  t he  optimized  code.  T he  need  for  additional  testing  sometimes  deters 
t he  use  of  optimizations  in  applications,  especially  if  their  performance  is  not 
critical. 

Finally,  a  compiler  is  a  complex  system;  we  must  keep  the  system  sim 
ple  to  assure  t h at  the  engineering  and  maintenance  costs  of  the  compiler  are 
manageable.  There  is  an  infinite  number  of  program  optimizations  t h at  we 
could  implement,  and  it  takes  a  nontrivial  amount  of  effort  to  create  a  correct 
and  effective  optimization.  We  must  prioritize  the  optimizations,  implementing 
only  those  t h at  lead  to  the  greatest  benefits  on  source  programs  encountered  in 
practice. 

Thus,  in  studying  compilers,  we  learn  not  only  how  to  build  a  compiler,  but 
also  the  general  methodology  of solving  complex  and  open-ended  problems.  T he 
approach  used  in  compiler  development  involves  both  theory  and  experimenta 
tion.  We  normally  start  by  formulating  the  problem  based  on  our  intuitions  on 
what  the  important  issues  are. 

1.5  Applications  of  Compiler  Technology 

Compiler  design  is  not  only  about  compilers,  and  many  people  use  the  technol 
ogy  learned  by  studying  compilers  in  school,  yet  have  never,  strictly  speaking, 
written  (even  part  of)  a  compiler  for  a  major  programming  language.  Compiler 
technology  has  other  important  uses  as  well.  Additionally,  compiler  design  im 
In  this  section,  we  review  the 
pacts  several  other  areas  of  computer  science. 
most  important  interactions  and  applications  of  the  technology. 

1.5.1 

Implementation  of  High-Level  Programming 
Languages 

A  high-level  programming  language  defines  a  programming  abstraction: 
t he 
programmer  expresses  an  algorithm  using  the  language,  and  the  compiler  must 
translate  t h at  program  to  the  target  language.  Generally,  higher-level  program 
ming  languages  are  easier  to  program  in,  but  are  less  efficient,  t h at  is,  the  target 
programs  run  more  slowly.  Programmers  using  a  low-level  language  have  more 
control  over  a  computation  and  can,  in  principle,  produce  more  efficient  code. 
Unfortunately,  lower-level  programs  are  harder  to  write  and  —  worse  still  — 
less  portable,  more  prone  to  errors,  and  harder  to  maintain.  Optimizing  com 
pilers  include  techniques  to  improve  the  performance  of  generated  code,  thus 
offsetting  the  inefficiency  introduced  by  high-level  abstractions. 

18 

CHAPTER 

1. 

INTRODUCTION 

E x a m p le  1 . 2:  T he  r e g i s t er  keyword  in  the  C  programming  language  is  an 
early  example  of the  interaction  between  compiler  technology  and  language  evo 
lution.  When  the  C  language  was  created  in  the  mid  1970s,  it  was  considered 
necessary  to  let  a  programmer  control  which  program  variables  reside  in  regis 
ters.  This  control  became  unnecessary  as  effective  register-allocation  techniques 
were  developed,  and  most  modern  programs  no  longer  use  this  language  feature. 
In  fact,  programs  t h at  use  the  r e g i s t er  keyword  may  lose  efficiency,  because 
programmers  often  are  not  t he  best  judge  of  very  low-level  m a t t e rs  like  register 
allocation.  T he  optimal  choice  of  register  allocation  depends  greatly  on  t he 
specifics  of  a  machine  architecture.  Hardwiring  low-level  resource-management 
decisions  like  register  allocation  may  in  fact  hurt  performance,  especially  if  t he 
program  is  run  on  machines  other  t h an  the  one  for  which  it  was  written. 

• 

The  many  shifts  in  the  popular  choice  of  programming  languages  have  been 
in  the  direction  of  increased  levels  of  abstraction.  C  was  the  predominant 
systems  programming  language  of  the  80's;  many  of  the  new  projects  started 
in  the  90's  chose  C + +;  Java,  introduced  in  1995,  gained  popularity  quickly 
in  the  late  90's.  T he  new  programming-language  features  introduced  in  each 
round  spurred  new  research  in  compiler  optimization.  In  t he  following,  we  give 
an  overview  on  the  main  language  features  t h at  have  stimulated  significant 
advances  in  compiler  technology. 

Practically  all  common  programming  languages,  including  C,  Fortran  and 
Cobol,  support  user-defined  aggregate  d a ta types,  such  as  arrays  and  structures, 
and  high-level  control  flow,  such  as  loops  and  procedure  invocations.  If  we  just 
take  each  high-level  construct  or  data-access  operation  and  translate  it  directly 
to  machine  code,  the  result  would  be  very  inefficient.  A  body  of  compiler 
optimizations,  known  as  data-flow  optimizations,  has  been  developed  to  analyze 
the  flow  of  d a ta  through  t he  program  and  removes  redundancies  across  these 
constructs.  They  are  effective  in  generating  code  t h at  resembles  code  written 
by  a  skilled  programmer  at  a  lower  level. 

Object  orientation  was  first  introduced  in  Simula  in  1967,  and  has  been 
incorporated  in  languages  such  as  Smalltalk,  C + +,  C #,  and  Java.  T he  key 
ideas  behind  object  orientation  are 

1.  D a ta  abstraction  and 

2.  Inheritance  of  properties, 

both  of  which  have  been  found  to  make  programs  more  modular  and  easier  to 
maintain.  Object-oriented  programs  are  different  from  those  written  in  many 
other  languages,  in  t h at  they  consist  of  many  more,  but  smaller,  procedures 
(called  methods  in  object-oriented  terms).  Thus,  compiler  optimizations  must 
be  able  to  perform  well  across  the  procedural  boundaries  of the  source  program. 
Procedure  inlining,  which  is  t he  replacement  of  a  procedure  call  by  t he  body 
of the  procedure,  is  particularly  useful  here.  Optimizations  to  speed  up  virtual 
method  dispatches  have  also  been  developed. 

1.5. 

APPLICATIONS  OF  COMPILER 

TECHNOLOGY 

19 

Java  has  many  features  t h at  make  programming  easier,  many  of  which  have 
been  introduced  previously  in  other  languages.  The  Java  language  is  type-safe; 
t h at  is,  an  object  cannot  be  used  as  an  object  of  an  unrelated  type.  All  array 
accesses  are  checked  to  ensure  t h at  they  lie  within  t he  bounds  of  t he  array. 
Java  has  no  pointers  and  does  not  allow  pointer  arithmetic.  It  has  a  built-in 
garbage-collection facility  t h at  automatically  frees  the  memory  of  variables  t h at 
are  no  longer  in  use.  While  all  these  features  make  programming  easier,  they 
incur  a  run-time  overhead.  Compiler  optimizations  have  been  developed  to 
reduce  the  overhead,  for  example,  by  eliminating  unnecessary  range  checks  and 
by  allocating  objects  t h at  are  not  accessible  beyond  a  procedure  on  the  stack 
instead  of the  heap.  Effective  algorithms  also  have  been  developed  to  minimize 
the  overhead  of  garbage  collection. 

In  addition,  Java is  designed to  support  portable  and  mobile  code.  Programs 
are  distributed  as  Java  bytecode,  which  must  either  be  interpreted  or  compiled 
into  native  code  dynamically,  t h at  is,  at  run  time.  Dynamic  compilation  has  also 
been  studied  in  other  contexts,  where  information  is  extracted  dynamically  at 
run  time  and  used  to  produce  better-optimized  code.  In  dynamic  optimization, 
it  is  important  to  minimize  the  compilation  time  as  it  is  part  of  t he  execution 
overhead.  A  common  technique  used  is  to  only  compile  and  optimize  those 
p a r ts  of  t he  program  t h at  will  be  frequently  executed. 

1.5.2  Optimizations  for  Computer  Architectures 

T he  rapid  evolution  of  computer  architectures  has  also  led  to  an  insatiable 
demand  for  new  compiler  technology.  Almost  all  high-performance  systems 
take  advantage  of  the  same  two  basic  techniques:  parallelism  and  memory  hi 
erarchies.  Parallelism  can  be  found  at  several  levels:  at  the  instruction  level, 
where  multiple  operations  are  executed  simultaneously  and  at  the  processor 
level,  where  different  threads  of  the  same  application  are  run  on  different  pro 
cessors.  Memory  hierarchies  are  a  response  to  the  basic  limitation  t h at  we  can 
build  very  fast  storage  or  very  large  storage,  but  not  storage  t h at  is  both  fast 
and  large. 

P a r a l l e l i sm 

All  modern  microprocessors  exploit  instruction-level  parallelism.  However,  this 
parallelism  can  be  hidden  from  the  programmer.  Programs  are  written  as  if  all 
instructions  were  executed  in  sequence;  the  hardware  dynamically  checks  for 
dependencies  in  the  sequential  instruction  stream  and  issues  t h em  in  parallel 
when  possible.  In  some  cases,  the  machine  includes  a  hardware  scheduler  t h at 
can  change  t he  instruction  ordering  to  increase  the  parallelism  in  the  program. 
Whether  the  hardware  reorders  the  instructions  or  not,  compilers  can  rearrange 
the  instructions  to  make  instruction-level  parallelism  more  effective. 

Instruction-level  parallelism  can  also  appear  explicitly  in  the  instruction  set. 
VLIW  (Very  Long  Instruction  Word)  machines  have  instructions  t h at  can  issue 

20 

CHAPTER 

1. 

INTRODUCTION 

multiple  operations  in  parallel.  T he  Intel  IA64  is  a  well-known  example  of  such 
an  architecture.  All  high-performance,  general-purpose  microprocessors  also 
include  instructions  t h at  can  operate  on  a  vector  of  d a ta  at  t he  same  time. 
Compiler  techniques  have  been  developed  to  generate  code  automatically  for 
such  machines  from  sequential  programs. 

Multiprocessors  have  also  become  prevalent;  even  personal  computers  of 
ten  have  multiple  processors.  Programmers  can  write  multithreaded  code  for 
multiprocessors,  or  parallel  code  can  be  automatically  generated  by  a  com 
piler  from  conventional  sequential  programs.  Such  a  compiler  hides  from  the 
programmers  t he  details  of  finding  parallelism  in  a  program,  distributing  t he 
computation  across  the  machine,  and  minimizing  synchronization  and  com 
munication  among  the  processors.  Many  scientific-computing  and  engineering 
applications  are  computation-intensive  and  can  benefit  greatly  from  parallel 
processing.  Parallelization  techniques  have  been  developed  to  translate  auto 
matically  sequential  scientific  programs  into  multiprocessor  code. 

M e m o ry  H i e r a r c h i es 

A  memory  hierarchy  consists  of  several  levels  of  storage  with  different  speeds 
and  sizes,  with  t he  level  closest  to  the  processor  being  t he  fastest  but  small 
est.  T he  average  memory-access  time  of  a  program  is  reduced  if  most  of  its 
accesses  are  satisfied  by  the  faster  levels  of  the  hierarchy.  Both  parallelism  and 
t he  existence  of  a  memory  hierarchy  improve  the  potential  performance  of  a 
machine,  but  they  must  be  harnessed  effectively  by  the  compiler  to  deliver  real 
performance  on  an  application. 

Memory  hierarchies  are  found  in  all  machines.  A  processor  usually  has 
a  small  number  of  registers  consisting  of  hundreds  of  bytes,  several  levels  of 
caches  containing  kilobytes  to  megabytes,  physical  memory  containing  mega 
bytes  to  gigabytes,  and  finally  secondary  storage  t h at  contains  gigabytes  and 
beyond.  Correspondingly,  the  speed  of  accesses  between  adjacent  levels  of  the 
hierarchy  can  differ  by  two  or  three  orders  of magnitude.  T he  performance  of  a 
system  is  often  limited  not  by  the  speed  of the  processor  but  by  t he  performance 
of  t he  memory  subsystem.  While  compilers  traditionally  focus  on  optimizing 
the  processor  execution,  more  emphasis  is  now  placed  on  making  t he  memory 
hierarchy  more  effective. 

Using  registers  effectively  is  probably  the  single  most  important  problem  in 
optimizing  a  program.  Unlike  registers  t h at  have  to  be  managed  explicitly  in 
software,  caches  and  physical  memories  are  hidden  from  the  instruction  set  and 
are  managed  by  hardware.  It  has  been  found  t h at  cache-management  policies 
implemented  by  hardware  are  not  effective  in  some  cases,  especially  in  scientific 
code  t h at  has  large  d a ta  structures  (arrays,  typically).  It  is  possible  to  improve 
the  effectiveness  of  t he  memory  hierarchy  by  changing  t he  layout  of  t he  d a t a, 
or  changing  the  order  of  instructions  accessing  the  data.  We  can  also  change 
the  layout  of  code  to  improve  the  effectiveness  of  instruction  caches. 

1.5. 

APPLICATIONS  OF  COMPILER 

TECHNOLOGY 

21 

1.5.3  Design  of  New  Computer  Architectures 

In  t he  early  days  of  computer  architecture  design,  compilers  were  developed 
after  the  machines  were  built.  T h at  has  changed.  Since  programming  in  high-
level  languages  is  t he  norm,  t he  performance  of a  computer  system  is  determined 
not  by  its  raw  speed  but  also  by  how  well  compilers  can  exploit  its  features. 
T h u s,  in  modern  computer  architecture  development,  compilers  are  developed 
in  the  processor-design  stage,  and  compiled  code,  running  on  simulators,  is  used 
to  evaluate  the  proposed  architectural  features. 

R I SC 

One  of  the  best  known  examples  of  how  compilers  influenced  the  design  of 
computer  architecture  was  the  invention  of  the  RISC  (Reduced  Instruction-Set 
Computer)  architecture.  Prior  to  this  invention,  the  trend  was  to  develop  pro 
gressively  complex  instruction  sets  intended  to  make  assembly  programming 
easier;  these  architectures  were  known  as  CISC  (Complex  Instruction-Set  Com 
puter).  For  example,  CISC  instruction  sets  include  complex  memory-addressing 
modes  to  support  data-structure  accesses  and  procedure-invocation  instructions 
t h at  save  registers  and  pass  parameters  on  the  stack. 

Compiler  optimizations  often  can  reduce  these  instructions  to  a  small  num 
ber  of  simpler  operations  by  eliminating  the  redundancies  across  complex  in 
structions.  Thus,  it  is  desirable  to  build  simple  instruction  sets;  compilers  can 
use  t h em  effectively  and  the  hardware  is  much  easier  to  optimize. 

Most  general-purpose  processor  architectures,  including  PowerPC,  SPARC, 
MIPS,  Alpha,  and  PA-RISC,  are  based  on  the  RISC  concept.  Although  t he 
x86  architecture—the  most  popular  microprocessor—has  a  CISC  instruction 
set,  many  of  the  ideas  developed  for  RISC  machines  are  used  in  t he  imple 
mentation  of  the  processor  itself.  Moreover,  the  most  effective  way  to  use  a 
high-performance  x86  machine  is  to  use  just  its  simple  instructions. 

S p e c i a l i z ed  A r c h i t e c t u r es 

Over  the  last  three  decades,  many  architectural  concepts  have  been  proposed. 
They  include  d a ta  flow  machines,  vector  machines,  VLIW  (Very  Long  Instruc 
tion  Word)  machines,  SIMD  (Single  Instruction,  Multiple  Data)  arrays  of  pro 
cessors,  systolic  arrays,  multiprocessors  with  shared  memory,  and  multiproces 
sors  with  distributed  memory.  The  development  of  each  of  these  architectural 
concepts  was  accompanied  by  t he  research  and  development  of  corresponding 
compiler  technology. 

Some  of  these  ideas  have  made  their  way  into  the  designs  of  embedded 
machines.  Since  entire  systems  can  fit  on  a  single  chip,  processors  need  no 
longer  be  prepackaged  commodity  units,  but  can  be  tailored  to  achieve  better 
cost-effectiveness  for  a  particular  application.  Thus,  in  contrast  to  general-
purpose  processors,  where  economies  of  scale  have  led  computer  architectures 

22 

CHAPTER 

1. 

INTRODUCTION 

to  converge,  application-specific  processors  exhibit  a  diversity  of  computer  ar 
chitectures.  Compiler  technology  is  needed  not  only  to  support  programming 
for  these  architectures,  but  also  to  evaluate  proposed  architectural  designs. 

1.5.4  Program  Translations 

While  we  normally  think  of  compiling  as  a  translation  from  a  high-level  lan 
guage  to  the  machine  level,  the  same  technology  can  be  applied  to  translate 
between  different  kinds  of  languages.  The  following  are  some  of  the  important 
applications  of  program-translation  techniques. 

B i n a ry  T r a n s l a t i on 

Compiler  technology  can  be  used  to  translate  the  binary  code  for  one  machine 
to  t h at  of  another,  allowing  a  machine  to  run  programs  originally  compiled  for 
another  instruction  set.  Binary  translation  technology  has  been  used  by  various 
computer  companies  to  increase  the  availability  of  software  for  their  machines. 
In  particular,  because  of  the  domination  of  t he  x86  personal-computer  mar 
ket,  most  software  titles  are  available  as  x86  code.  Binary  translators  have 
been  developed  to  convert  x86  code  into  both  Alpha  and  Sparc  code.  Binary 
translation  was  also  used  by  Transmeta  Inc.  in  their  implementation  of t he  x86 
instruction  set.  Instead  of executing  t he  complex  x86  instruction  set  directly  in 
hardware,  the  Transmeta  Crusoe  processor  is  a  VLIW  processor  t h at  relies  on 
binary  translation  to  convert  x86  code  into  native  VLIW  code. 

Binary  translation  can  also  be  used  to  provide  backward  compatibility. 
When  the  processor  in  the  Apple  Macintosh  was  changed  from  the  Motorola  MC 
68040  to  t he  PowerPC  in  1994,  binary  translation  was  used  to  allow  PowerPC 
processors  run  legacy  MC  68040  code. 

H a r d w a re  S y n t h e s is 

Not  only  is  most  software  written  in  high-level  languages;  even  hardware  de 
signs  are  mostly  described  in  high-level  hardware  description  languages  like 
Verilog  and  VHDL  (Very  high-speed  integrated  circuit  Hardware  Description 
Language).  Hardware  designs  are  typically  described  at  the  register  trans 
fer  level  (RTL),  where  variables  represent  registers  and  expressions  represent 
combinational  logic.  Hardware-synthesis  tools  translate  RTL  descriptions  auto 
matically  into  gates,  which  are  then  mapped  to  transistors  and  eventually  to  a 
physical  layout.  Unlike  compilers  for  programming  languages,  these  tools  often 
take  hours  optimizing  t he  circuit.  Techniques  to  translate  designs  at  higher 
levels,  such  as  t he  behavior  or  functional  level,  also  exist. 

D a t a b a se  Q u e ry  I n t e r p r e t e rs 

Besides  specifying  software  and  hardware,  languages  are  useful  in  many  other 
applications.  For  example,  query  languages,  especially  SQL  (Structured  Query 

1.5. 

APPLICATIONS  OF  COMPILER 

TECHNOLOGY 

23 

Language),  are  used  to  search  databases.  Database  queries  consist  of predicates 
containing  relational  and  boolean  operators.  They  can  be  interpreted  or  com 
piled  into  commands  to  search  a  database  for  records  satisfying  t h at  predicate. 

C o m p i l ed  S i m u l a t i on 

Simulation  is  a  general  technique  used  in  many  scientific  and  engineering  disci 
plines  to  understand  a  phenomenon  or  to  validate  a  design.  Inputs  to  a  simula 
tor  usually  include  the  description  of  the  design  and  specific  input  parameters 
for  t h at  particular  simulation  run.  Simulations  can  be  very  expensive.  We  typi 
cally  need  to  simulate  many  possible  design  alternatives  on  many  different  input 
sets,  and  each  experiment  may  take  days  to  complete  on  a  high-performance 
machine.  Instead  of  writing  a  simulator  t h at  interprets  t he  design,  it  is  faster 
to  compile  t he  design  to  produce  machine  code  t h at  simulates  t h at  particular 
design  natively.  Compiled  simulation  can  run  orders  of  magnitude  faster  t h an 
an  interpreter-based  approach.  Compiled  simulation  is  used  in  many  state-of-
the-art  tools  t h at  simulate  designs  written  in  Verilog  or  VHDL. 

1.5.5 

Software  Productivity  Tools 

Programs  are  arguably  the  most  complicated  engineering  artifacts  ever  pro 
duced;  they  consist  of  many  many  details,  every  one  of  which  must  be  correct 
before  the  program  will  work  completely.  As  a  result,  errors  are  r a m p a nt  in 
programs;  errors  may  crash  a  system,  produce  wrong  results,  render  a  system 
vulnerable  to  security  attacks,  or  even  lead  to  catastrophic  failures  in  critical 
systems.  Testing  is  the  primary  technique  for  locating  errors  in  programs. 

An  interesting  and  promising  complementary  approach  is  to  use  data-flow 

analysis  to  locate  errors  statically  (that  is,  before  the  program  is  run).  Data 
flow  analysis  can  find  errors  along  all  the  possible  execution  paths,  and  not 
just  those  exercised  by  the  input  d a ta  sets,  as  in  the  case  of  program  testing. 
Many  of  the  data-flow-analysis  techniques,  originally  developed  for  compiler 
optimizations,  can  be  used  to  create  tools  t h at  assist  programmers  in  their 
software  engineering  tasks. 

T he  problem  of finding  all  program  errors  is  undecidable.  A  data-flow  analy 
sis  may  be  designed  to  warn  the  programmers  of all  possible  statements  violating 
a  particular  category  of  errors.  But  if  most  of  these  warnings  are  false  alarms, 
users  will  not  use  the  tool.  Thus,  practical  error  detectors  are  often  neither 
sound  nor  complete.  T h at  is,  they  may  not  find  all  the  errors  in  the  program, 
and  not  all  errors  reported  are  guaranteed  to  be  real  errors.  Nonetheless,  var 
ious  static  analyses  have  been  developed  and  shown  to  be  effective  in  finding 
errors,  such  as  dereferencing  null  or  freed  pointers,  in  real  programs.  The  fact 
t h at  error  detectors  may  be  unsound  makes  them  significantly  different  from 
compiler  optimizations.  Optimizers  must  be  conservative  and  cannot  alter  t he 
semantics  of  the  program  under  any  circumstances. 

24 

CHAPTER 

1. 

INTRODUCTION 

In  the  balance  of  this  section,  we  shall  mention  several  ways  in  which  pro 

gram  analysis,  building  upon  techniques  originally  developed  to  optimize  code 
in  compilers,  have  improved  software  productivity.  Of  special  importance  are 
techniques  t h at  detect  statically  when  a  program  might  have  a  security  vulner 
ability. 

T y pe  C h e c k i ng 

Type  checking  is  an  effective  and  well-established  technique  to  catch  inconsis 
tencies  in  programs. 
It  can  be  used  to  catch  errors,  for  example,  where  an 
operation  is  applied  to  the  wrong  type  of  object,  or  if  parameters  passed  to  a 
procedure  do  not  match  the  signature  of  the  procedure.  P r o g r am  analysis  can 
go  beyond  finding  type  errors  by  analyzing  the  flow  of d a ta  through  a  program. 
For  example,  if  a  pointer  is  assigned  n u ll  and  then  immediately  dereferenced, 
the  program  is  clearly  in  error. 

The  same  technology  can  be  used  to  catch  a  variety  of  security  holes,  in 
which  an  attacker  supplies  a  string  or  other  d a ta  t h at  is  used  carelessly  by  t he 
program.  A  user-supplied  string  can  be  labeled  with  a  type  "dangerous." 
If 
this  string  is  not  checked  for  proper  format,  then  it  remains  "dangerous,"  and 
if  a  string  of  this  type  is  able  to  influence  the  control-flow  of  t he  code  at  some 
point  in  t he  program,  then  there  is  a  potential  security  flaw. 

B o u n ds  C h e c k i ng 

It  is  easier  to  make  mistakes  when  programming  in  a  lower-level  language  t h an 
a  higher-level  one.  For  example,  many  security  breaches  in  systems  are  caused 
by  buffer  overflows  in  programs  written  in  C.  Because  C  does  not  have  array-
bounds  checks,  it  is  up  to  the  user  to  ensure  t h at  the  arrays  are  not  accessed 
out  of  bounds.  Failing  to  check  t h at  the  d a ta  supplied  by  the  user  can  overflow 
a  buffer,  the  program  may  be  tricked  into  storing  user  d a ta  outside  of  t he 
buffer.  An  attacker  can  manipulate  the  input  d a ta  t h at  causes  the  program  to 
misbehave  and  compromise  t he  security  of  t he  system.  Techniques  have  been 
developed  to  find  buffer  overflows  in  programs,  but  with  limited  success. 

Had  the  program  been  written  in  a  safe  language  t h at  includes  automatic 
range  checking,  this  problem  would  not  have  occurred.  T he  same  data-flow 
analysis  t h at  is  used  to  eliminate  redundant  range  checks  can  also  be  used  to 
locate  buffer  overflows.  The  major  difference,  however,  is  t h at  failing  to  elimi 
nate  a  range  check  would  only  result  in  a  small  run-time  cost,  while  failing  to 
identify  a  potential  buffer  overflow  may  compromise  the  security  of  the  system. 
Thus,  while  it  is  adequate  to  use  simple  techniques  to  optimize  range  checks,  so 
phisticated  analyses,  such  as  tracking  t he  values  of pointers  across  procedures, 
are  needed  to  get  high-quality  results  in  error  detection  tools. 

1.6. 

PROGRAMMING  LANGUAGE  BASICS 

25 

M e m o r y - M a n a g e m e nt  T o o ls 

Garbage  collection  is  another  excellent  example  of  t he  tradeoff  between  effi 
ciency  and  a  combination  of  ease  of  programming  and  software  reliability.  Au 
tomatic  memory  management  obliterates  all  memory-management  errors  (e.g., 
"memory  leaks"),  which  are  a  major  source  of  problems  in  C  and  C ++  pro 
grams.  Various  tools  have  been  developed  to  help  programmers  find  memory 
management  errors.  For  example,  Purify  is  a  widely  used  tool  t h at  dynamically 
catches  memory  management  errors  as  they  occur.  Tools  t h at  help  identify 
some  of  these  problems  statically  have  also  been  developed. 

1.6  Programming  Language  Basics 

In  this  section,  we  shall  cover  the  most  important  terminology  and  distinctions 
t h at  appear  in  the  study  of  programming  languages.  It  is  not  our  purpose  to 
cover  all  concepts  or  all  the  popular  programming  languages.  We  assume  t h at 
the  reader  is  familiar  with  at  least  one  of  C,  C + +,  C #,  or  Java,  and  may  have 
encountered  other  languages  as  well. 

1.6.1  The  Static/Dynamic  Distinction 

Among  the  most  important  issues  t h at  we  face  when  designing  a  compiler  for 
a  language  is  what  decisions  can  the  compiler  make  about  a  program. 
If  a 
language  uses  a  policy  t h at  allows  the  compiler  to  decide  an  issue,  then  we  say 
t h at  the  language  uses  a  static  policy  or  t h at  t he  issue  can  be  decided  at  compile 
time.  On  t he  other  hand,  a  policy  t h at  only  allows  a  decision  to  be  m a de  when 
we  execute  the  program  is  said  to  be  a  dynamic  policy  or  to  require  a  decision 
at  run 

time. 

One  issue  on  which  we  shall  concentrate  is  the  scope  of  declarations.  T he 
scope  of a  declaration  of x  is  the  region  of the  program  in  which  uses  of x  refer  to 
this  declaration.  A  language  uses  static  scope  or  lexical  scope  if  it  is  possible  to 
determine  the  scope  of a  declaration  by  looking  only  at  t he  program.  Otherwise, 
t he  language  uses  dynamic  scope.  W i th  dynamic  scope,  as  t he  program  runs, 
the  same  use  of  x  could  refer  to  any  of  several  different  declarations  of  x. 

Most  languages,  such  as  C  and  Java,  use  static  scope.  We  shall  discuss  static 

scoping  in  Section  1.6.3. 

E x a m p le  1.3  :  As  another  example  of the  static/dynamic  distinction,  consider 
t he  use  of the  term  "static"  as  it  applies  to  d a ta  in  a  Java  class  declaration.  In 
Java,  a  variable  is  a  name  for  a  location  in  memory  used  to  hold  a  d a ta  value. 
Here,  "static"  refers  not  to  the  scope  of the  variable,  but  rather  to  the  ability  of 
the  compiler  to  determine  the  location  in  memory  where  the  declared  variable 
can  be  found.  A  declaration  like 

public  static  int  x; 

26 

CHAPTER 

1. 

INTRODUCTION 

makes  x  a  class  variable  and  says  t h at  there  is  only  one  copy  of x,  no  m a t t er  how 
many  objects  of  this  class  are  created.  Moreover,  the  compiler  can  determine  a 
location  in  memory  where  this  integer  x  will  be  held.  In  contrast,  had  "static" 
been  omitted  from  this  declaration,  then  each  object  of the  class  would  have  its 
own  location  where  x  would  be  held,  and  t he  compiler  could  not  determine  all 
these  places  in  advance  of  running  the  program. 

• 

1.6.2  Environments  and  States 

Another  important  distinction  we  must  make  when  discussing  programming 
languages  is  whether  changes  occurring  as  the  program  runs  affect  the  values  of 
d a ta  elements  or  affect  the  interpretation  of  names  for  t h at  data.  For  example, 
the  execution  of  an  assignment  such  as  x = y +1  changes  the  value  denoted  by 
the  name  x.  More  specifically,  t he  assignment  changes  the  value  in  whatever 
location  is  denoted  by  x. 

It  may  be  less  clear  t h at  the  location  denoted  by  x  can  change  at  run  time. 
For  instance,  as  we  discussed  in  Example  1.3,  if  x  is  not  a  static  (or  "class") 
variable,  then  every  object  of  t he  class  has  its  own  location  for  an  instance 
of  variable  x. 
In  t h at  case,  t he  assignment  to  x  can  change  any  of  those  "in 
stance"  variables,  depending  on  t he  object  to  which  a  method  containing  t h at 
assignment  is  applied. 

environment 

state 

names 

locations 
(variables) 

values 

Figure  1.8:  Two-stage  mapping  from  names  to  values 

T he  association  of  names  with  locations  in  memory  (the  store)  and  then 
with  values  can  be  described  by  two  mappings  t h at  change  as  the  program  runs 
(see  Fig.  1.8): 

1.  The  environment  is  a  mapping  from  names  to  locations  in  t he  store.  Since 
variables  refer  to  locations  ("1-values"  in  the  terminology  of  C),  we  could 
alternatively  define  an  environment  as  a  mapping  from  names  to  variables. 

2.  T he  state  is  a  mapping  from  locations  in  store  to  their  values.  T h at  is,  the 
state  maps  1-values  to  their  corresponding  r-values,  in  the  terminology  of 
C. 

Environments  change  according  to  the  scope  rules  of  a  language. 

E x a m p le  1 . 4:  Consider  the  C  program  fragment  in  Fig.  1.9. 
Integer  i  is 
declared  a  global  variable,  and  also  declared  as  a  variable  local  to  function  /. 
When  /  is  executing,  the  environment  adjusts  so  t h at  name  i  refers  to  t he 

1.6. 

PROGRAMMING  LANGUAGE  BASICS 

27 

int  i; 

/*  global  i 

void f(---)  { 

int  i; 

/*  local  i 

*/ 

*/ 

i  =  3; 

/*  use  of  local  i 

*/ 

} 

x  =  i  +  1; 

/*  use  of  global  i  */ 

Figure 1.9:  Two  declarations  of t he  name  i 

location  reserved  for  the  i  t h at  is  local  to  /,  and  any  use  of  i,  such  as  t he 
assignment i  =  3  shown  explicitly,  refers  to  t h at  location.  Typically,  the  local 
i  is  given  a  place  on  t he  run-time  stack. 

Whenever  a  function  g  other  t h an  /  is  executing,  uses  of  i  cannot  refer  to 
the  i  t h at  is  local  to  /.  Uses  of  name  i  in  g  must  be  within  the  scope  of  some 
other  declaration  of  i.  An  example  is  the  explicitly  shown  statement  x  =  i+1, 
which  is  inside  some  procedure  whose  definition  is  not  shown.  T he  i  in  i + 1 
presumably  refers  to  the  global  i.  As  in  most  languages,  declarations  in  C  must 
precede  their  use,  so  a  function  t h at  comes  before  t he  global  i  cannot  refer  to 
it. 

• 

The  environment  and  state  mappings  in  Fig. 1.8  are  dynamic,  but  there  are 

a  few  exceptions: 

1. Static  versus  dynamic  binding  of  names  to  locations.  Most  binding  of 
names  to  locations  is  dynamic,  and  we  discuss  several  approaches  to  this 
binding  throughout  the  section.  Some  declarations,  such  as  the  global  i 
in  Fig. 1.9,  can  be  given  a  location  in  the  store  once  and  for  all,  as  t he 
compiler  generates  object  code.2 

2.  Static  versus  dynamic  binding  of  locations  to  values.  T he  binding  of  lo 
cations  to  values  (the  second  stage  in  Fig. 1.8),  is  generally  dynamic  as 
well,  since  we  cannot  tell  t he  value  in  a  location  until  we  run  t he  program. 
Declared  constants  are  an  exception.  For  instance,  the  C  definition 

#define  ARRAYSIZE  1000 

2 Technically,  the  C  compiler  will  assign  a  location  in  virtual  memory  for  the  global  i, 
leaving  it  to  the  loader  and  the  operating  system  to  determine  where  in  the  physical  memory 
of the  machine  i  will  be  located.  However,  we  shall  not  worry  about  "relocation"  issues  such 
as  these,  which  have  no  impact  on  compiling.  Instead,  we  treat  the  address  space  that  the 
compiler  uses  for  its  output  code  as  if  it  gave  physical  memory  locations. 

28 

CHAPTER 

1. 

INTRODUCTION 

Names,  Identifiers,  and  Variables 

Although  the  terms  "name"  and  "variable,"  often  refer  to  t he  same  thing, 
we  use  them  carefully  to  distinguish  between  compile-time  names  and  t he 
run-time  locations  denoted  by  names. 

An  identifier  is  a  string  of  characters,  typically  letters  or  digits,  t h at 
refers  to  (identifies)  an  entity,  such  as  a  d a ta  object,  a  procedure,  a  class, 
or  a  type.  All  identifiers  are  names,  but  not  all  names  are  identifiers. 
Names  can  also  be  expressions.  For  example,  t he  n a me  x.y  might  denote 
the  field  y  of  a  structure  denoted  by  x.  Here,  x  and  y  are  identifiers,  while 
x.y  is  a  name,  but  not  an  identifier.  Composite  names  like  x.y  are  called 
qualified  names. 

A  variable  refers  to  a  particular  location  of t he  store.  It  is  common  for 
t he  same  identifier  to  be  declared  more  t h an  once;  each  such  declaration 
introduces  a  new  variable.  Even  if  each  identifier  is  declared  just  once,  an 
identifier  local  to  a  recursive  procedure  will  refer  to  different  locations  of 
the  store  at  different  times. 

binds  the  name ARRAYS  IZE  to  t he  value  1000  statically.  We  can  determine 
this  binding  by  looking at  the  statement,  and  we know t h at  it  is  impossible 
for  this  binding  to  change  when  t he  program  executes. 

1.6.3 

Static  Scope  and  Block  Structure 

Most  languages,  including  C  and  its  family,  use  static  scope.  T he  scope  rules 
for  C  are  based  on  program  structure;  the  scope  of  a  declaration  is  determined 
implicitly  by  where  the  declaration  appears  in  t he  program.  Later  languages, 
such  as  C + +,  Java,  and  C #,  also  provide  explicit  control  over  scopes  through 
t he  use  of  keywords  like  p u b l i c,  p r i v a t e,  and  p r o t e c t e d. 

In  this  section  we  consider  static-scope  rules  for  a  language  with  blocks, 
where  a  block is  a  grouping  of declarations  and  statements.  C  uses  braces  {  and 
}  to  delimit  a  block;  the  alternative  use  of b e g in  and  e nd  for  t he  same  purpose 
dates  back  to  Algol. 

E x a m p le  1.5  :  To  a  first  approximation,  the  C  static-scope  policy  is  as  follows: 

1.  A  C  program  consists  of  a  sequence  of  top-level  declarations  of  variables 

and  functions. 

2.  Functions  may  have  variable  declarations  within  them,  where  variables 
include  local  variables  and  parameters.  T he  scope  of each  such  declaration 
is  restricted  to  the  function  in  which  it  appears. 

1.6. 

PROGRAMMING  LANGUAGE  BASICS 

29 

Procedures,  Functions,  and  Methods 

To  avoid  saying  "procedures,  functions,  or  methods,"  each  time  we  want 
to  talk  about  a  subprogram  t h at  may  be  called,  we  shall  usually  refer  to 
all  of t h em  as  "procedures."  The  exception  is  t h at  when  talking  explicitly 
of  programs  in  languages  like  C  t h at  have  only  functions,  we  shall  refer 
to  t h em  as  "functions."  Or,  if  we  are  discussing  a  language  like  Java  t h at 
has  only  methods,  we  shall  use  t h at  term  instead. 

A  function  generally  returns  a  value  of  some  type  (the  "return  t y p e " ), 
while  a  procedure  does  not  return  any  value.  C  and  similar  languages, 
which  have  only  functions,  treat  procedures  as  functions  t h at  have  a  special 
return  type  "void,"  to  signify  no  return  value.  Object-oriented  languages 
like  Java  and  C ++  use  the  t e rm  "methods."  These  can  behave  like  either 
functions  or  procedures,  but  are  associated  with  a  particular  class. 

3.  T he  scope  of  a  top-level  declaration  of  a  name  x  consists  of  the  entire 
program  t h at  follows,  with  t he  exception  of  those  statements  t h at  lie 
within  a  function  t h at  also  has  a  declaration  of  x. 

The  additional  detail  regarding  the  C  static-scope  policy  deals  with  variable 
declarations  within  statements.  We  examine  such  declarations  next  and  in 
Example  1.6. 

• 

In  C,  t he  syntax  of  blocks  is  given  by 

1.  One  type  of statement  is  a  block.  Blocks  can  appear  anywhere  t h at  other 

types  of  statements,  such  as  assignment  statements,  can  appear. 

2.  A  block  is  a  sequence  of declarations  followed  by  a  sequence  of statements, 

all  surrounded  by  braces. 

Note  t h at  this  syntax  allows  blocks  to  be  nested  inside  each  other.  This 
nesting  property  is  referred  to  as  block  structure.  T he  C  family  of  languages 
has  block  structure,  except  t h at  a  function  may  not  be  defined  inside  another 
function. 

We  say  t h at  a  declaration  D  "belongs"  to  a  block  B  if  B  is  the  most  closely 
nested  block  containing  D;  t h at  is,  D  is  located  within  B,  but  not  within  any 
block  t h at  is  nested  within  B. 

T he  static-scope  rule  for  variable  declarations  in  a  block-structured  lan 
guages  is  as  follows.  If  declaration  D  of  name  x  belongs  to  block  B,  then  t he 
scope  of  D  is  all  of  B,  except  for  any  blocks  B'  nested  to  any  depth  within  J5, 
in  which  x  is  redeclared.  Here,  x  is  redeclared  in  B'  if  some  other  declaration 
D'  of  t he  same  name  x  belongs  to  B'. 

30 

CHAPTER 

1. 

INTRODUCTION 

An  equivalent  way  to  express  this  rule  is  to  focus  on  a  use  of  a  name  x. 
Let  Bi, i ? 2,  •  •  •  , Bk  be  all  t he  blocks  t h at  surround  this  use  of  x,  with  Bk  the 
smallest,  nested  within  Bk-i,  which  is  nested  within  Bk-2,  and  so  on.  Search 
for  the  largest  i  such  t h at  there  is  a  declaration  of  x  belonging  to  B^.  This  use 
of  x  refers  to  the  declaration  in  B{.  Alternatively,  this  use  of  x  is  within  t he 
scope  of  the  declaration  in  Bi. 

^ 

^ 

m a i nQ  { 

i nt  a  =  1; 
i nt  b  =  1; 
{ 

f  i nt  b  =  2; 

i nt  a  = 
« 
c o ut 

3; 
a  « b; 

} 
{ 

i nt  b  -
c o ut  << 

4; 
a  « b; 

} 
c o ut  <<  a  «  b; 

B3 

J 

B4 

J 

} 
vc o ut  << a << b; 

} 

Figure  1.10:  Blocks  in  a  C ++  program 

E x a m p le  1 . 6:  T he  C ++  program  in  Fig.  1.10  has  four  blocks,  with  several 
definitions  of  variables  a  and  b.  As  a  memory  aid,  each  declaration  initializes 
its  variable  to  the  number  of  the  block  to  which  it  belongs. 

For  instance,  consider  t he  declaration  i nt  a  =  1  in  block  Bi. 

Its  scope 
is  all  of  Bi,  except  for  those  blocks  nested  (perhaps  deeply)  within  B±  t h at 
have  their  own  declaration  of  a.  Z?2,  nested  immediately  within  B±,  does  not 
have  a  declaration  of  a,  b ut  B3  does.  B4  does  not  have  a  declaration  of  a,  so 
block  B3  is  the  only  place  in  the  entire  program  t h at  is  outside  t he  scope  of t he 
declaration  of  the  name  a  t h at  belongs  to  B\.  T h at  is,  this  scope  includes  B4 
and  all  of  Z?2  except  for  the  part  of  B2  t h at  is  within  B3.  T he  scopes  of  all  five 
declarations  are  summarized  in  Fig.  1.11. 

From  another  point  of  view,  let  us  consider  the  o u t p ut  statement  in  block 
B4  and  bind  t he  variables  a  and  b  used  there  to  t he  proper  declarations.  T he 
list  of  surrounding  blocks,  in  order  of  increasing  size,  is  B4,B2,Bi.  Note  t h at 
#3  does  not  surround  t he  point  in  question.  B4  has  a  declaration  of  b,  so  it 
is  to  this  declaration  t h at  this  use  of  b  refers,  and  t he  value  of  6  printed  is  4. 
However,  B4  does  not  have  a  declaration  of  o,  so  we  next  look  at  £?2-  T h at 
block  does  not  have  a  declaration  of  a  either,  so  we  proceed  to  B\.  Fortunately, 

1.6. 

PROGRAMMING  LANGUAGE  BASICS 

31 

D E C L A R A T I ON 

S C O PE 

i nt  a  =  1 
i nt  b  =  1 
i nt  b  =  2 
i nt  a  =  3 
i nt  b  =  4 

B I - B3 

B ! - B2 

Z?2  —  B^ 
B3 
BA 

Figure  1.11:  Scopes  of  declarations  in  Example  1.6 

there  is  a  declaration  i nt  a  =  1  belonging  to  t h at  block,  so  the  value  of  a 
printed  is  1.  Had  there  been  no  such  declaration,  the  program  would  have  been 
erroneous. 

• 

1.6.4  Explicit  Access  Control 

Classes  and  structures  introduce  a  new  scope  for  their  members. 
If  p  is  an 
object  of  a  class  with  a  field  (member)  x,  then  the  use  of  x  in  p.x  refers  to 
field  x  in  t he  class  definition.  In  analogy  with  block  structure,  t he  scope  of  a 
member  declaration  x  in  a  class  C  extends  to  any  subclass  C,  except  if  C  has 
a  local  declaration  of  the  same  name  x. 

Through  the  use  of  keywords  like  p u b l i c,  p r i v a t e,  and  p r o t e c t e d,  object-
oriented  languages  such  as  C ++  or  Java  provide  explicit  control  over  access 
to  member  names  in  a  superclass.  These  keywords  support  encapsulation  by 
restricting  access.  Thus,  private  names  are  purposely  given  a scope  t h at  includes 
only  the  method  declarations  and  definitions  associated  with  t h at  class  and  any 
"friend"  classes  (the  C ++  t e r m ).  Protected  names  are  accessible  to  subclasses. 
Public  names  are  accessible  from  outside  the  class. 

In  C + +,  a  class  definition  may  be  separated  from  the  definitions  of  some 
or  all  of  its  methods.  Therefore,  a  name  x  associated  with  the  class  C  may 
have  a  region  of the  code  t h at  is  outside  its  scope,  followed  by  another  region  (a 
method  definition)  t h at  is  within  its  scope.  In  fact,  regions  inside  and  outside 
t he  scope  may  alternate,  until  all  t he  methods  have  been  defined. 

1.6.5  Dynamic  Scope 

Technically,  any  scoping  policy  is  dynamic  if  it  is  based  on  factor(s)  t h at  can 
be  known  only  when  the  program  executes.  The  term  dynamic  scope,  however, 
usually  refers  to  t he  following  policy:  a  use  of  a  name  x  refers  to  the  declaration 
of  x  in  t he  most  recently  called  procedure  with  such  a  declaration.  Dynamic 
scoping  of this  type  appears  only  in  special  situations.  We  shall  consider  two  ex 
amples  of dynamic  policies:  macro  expansion  in  t he  C  preprocessor  and  method 
resolution  in  object-oriented  programming. 

32 

CHAPTER 

1. 

INTRODUCTION 

Declarations  and  Definitions 

The  apparently  similar  terms  "declaration"  and  "definition"  for  program-
ming-language  concepts  are  actually  quite  different.  Declarations  tell  us 
about  the  types  of things,  while  definitions  tell  us  about  their  values.  Thus, 
i nt 

i  is  a  declaration  of  i,  while  i  =  1  is  a  definition  of  i. 
The  difference  is  more  significant  when  we  deal  with  methods  or  other 
procedures.  In  C + +,  a  method  is  declared  in  a  class  definition,  by  giving 
the  types  of  the  arguments  and  result  of  the  method  (often  called  t he 
signature  for  the  method.  The  method  is  then  defined,  i.e.,  the  code  for 
executing  the  method  is  given,  in  another  place.  Similarly,  it  is  common 
to  define  a  C  function  in  one  file  and  declare  it  in  other  files  where  t he 
function  is  used. 

In  the  C  program  of  Fig.  1.12,  identifier  a  is  a  macro  t h at 
E x a m p le  1 . 7: 
stands  for  expression  (a?  +  1).  But  what  is  xl  We  cannot  resolve  x  statically, 
t h at  is,  in  terms  of  the  program  text. 

# d e f i ne  a 

(x+1) 

i nt  x  =  2; 

v o id  b ()  { 

i nt  x  =  1;  p r i n tf ("0/.d\n",  a );  } 

v o id  c ()  {  p r i n t f( ",/ . d \ n ",  a );  } 

v o id  mainO  {  b ( );  c ( );  } 

Figure  1.12:  A  macro  whose  names  must  be  scoped  dynamically 

In  fact,  in  order  to  interpret  x,  we  must  use  the  usual  dynamic-scope  rule. 
We  examine  all  the  function  calls  t h at  are  currently  active,  and  we  take  t he  most 
It  is  to  this  declaration  t h at 
recently  called  function  t h at  has  a  declaration  of 
t he  use  of  x  refers. 

In  the  example  of  Fig.  1.12,  t he  function  main  first  calls  function  6.  As  b 
executes,  it  prints  the  value  of  the  macro  a.  Since  (x  +  1)  must  be  substituted 
for  a,  we  resolve  this  use  of  x  to  t he  declaration  i nt  x =l  in  function  b.  T he 
reason  is  t h at  b  has  a  declaration  of  x,  so  the  (x  +  1)  in  the  p r i n tf  in  b  refers 
to  this  x.  Thus,  t he  value  printed  is  1. 

After  b  finishes,  and  c  is  called,  we  again  need  to  print  t he  value  of  macro 
a.  However,  the  only  x  accessible  to  c  is  t he  global  x.  T he  p r i n tf  statement 
in  c  thus  refers  to  this  declaration  of  x,  and  value  2  is  printed. 

• 

Dynamic  scope  resolution  is  also  essential  for  polymorphic  procedures,  those 
t h at  have  two  or  more  definitions  for  t he  same  name,  depending  only  on  t he 

1.6. 

PROGRAMMING  LANGUAGE  BASICS 

33 

Analogy  Between  Static  and  Dynamic  Scoping 

While  there  could  be  any  number  of  static  or  dynamic  policies  for  scoping, 
there  is  an  interesting  relationship  between  the  normal  (block-structured) 
static  scoping  rule  and  the  normal  dynamic  policy.  In  a  sense,  the  dynamic 
rule  is  to  time  as  t he  static  rule  is  to  space.  While  t he  static  rule  asks  us  to 
find  t he  declaration  whose  unit  (block)  most  closely  surrounds  the  physical 
location  of the  use,  the  dynamic  rule  asks  us  to  find  the  declaration  whose 
unit  (procedure  invocation)  most  closely  surrounds  the  time  of  the  use. 

types  of  t he  arguments.  In  some  languages,  such  as  ML  (see  Section  7.3.3),  it 
is  possible  to  determine  statically  types  for  all  uses  of names,  in  which  case  the 
compiler  can  replace  each  use  of  a  procedure  name  p  by  a  reference  to  t he  code 
for  the  proper  procedure.  However,  in  other  languages,  such  as  Java  and  C + +, 
there  are  times  when  the  compiler  cannot  make  t h at  determination. 

E x a m p le  1 . 8:  A  distinguishing  feature  of  object-oriented  programming  is  the 
ability  of each  object  to  invoke the  appropriate method  in  response  to  a message. 
In  other  words,  the  procedure  called  when  x.mQ  is  executed  depends  on  the 
class  of  t he  object  denoted  by  x  at  t h at  time.  A  typical  example  is  as  follows: 

1.  There  is  a  class  C  with  a  method  named  m ( ). 

2.  D  is  a  subclass  of  C,  and  D  has  its  own  method  named  ra(). 

3.  There  is  a  use  of  m  of  the  form  x.mQ,  where  x  is  an  object  of  class  C. 

Normally,  it  is  impossible  to  tell  at  compile  time  whether  x  will  be  of  class 
If  t he  method  application  occurs  several  times,  it  is 
C  or  of  t he  subclass  D. 
highly  likely  t h at  some  will  be  on  objects  denoted  by  x  t h at  are  in  class  C  but 
not  D,  while  others  will  be  in  class  D.  It  is  not  until  run-time  t h at  it  can  be 
decided  which  definition  of m  is  t he  right  one.  Thus,  t he  code  generated  by  the 
compiler  must  determine  the  class  of  t he  object  x,  and  call  one  or  the  other 
method  named  m. 

• 

1.6.6  Parameter  Passing  Mechanisms 

All  programming  languages  have  a  notion  of  a  procedure,  but  they  can  differ 
in  how  these  procedures  get  their  arguments.  In  this  section,  we  shall  consider 
how  the  actual  parameters  (the  parameters  used  in  t he  call  of  a  procedure) 
are  associated  with  the  formal  parameters  (those  used  in  the  procedure  defi 
nition).  Which  mechanism  is  used  determines  how  the  calling-sequence  code 
treats  parameters.  The  great  majority  of  languages  use  either  "call-by-value," 
or  "call-by-reference,"  or  both.  We  shall  explain  these  terms,  and  another 
method  known  as  "call-by-name,"  t h at  is  primarily  of  historical  interest. 

34 

C a l l - b y - V a l ue 

CHAPTER 

1. 

INTRODUCTION 

In  call-by-value,  the  actual  parameter  is  evaluated  (if  it  is  an  expression)  or 
copied  (if  it  is  a  variable).  The  value  is  placed  in  the  location  belonging  to 
the  corresponding  formal  parameter  of  the  called  procedure.  This  method  is 
used  in  C  and  Java,  and  is  a  common  option  in  C + +,  as  well  as  in  most 
other  languages.  Call-by-value  has  the  effect  t h at  all  computation  involving  t he 
formal  parameters  done  by  the  called  procedure  is  local  to  t h at  procedure,  and 
the  actual  parameters  themselves  cannot  be  changed. 

Note,  however,  t h at  in  C  we  can  pass  a  pointer  to  a  variable  to  allow  t h at 
variable  to  be  changed  by  the  callee.  Likewise,  array  names  passed  as  param 
eters  in  C,  C + +,  or  Java  give  t he  called  procedure  what  is  in  effect  a  pointer 
or  reference  to  the  array  itself.  Thus,  if  a  is  the  name  of  an  array  of the  calling 
procedure,  and  it  is  passed  by  value  to  corresponding  formal  parameter  x,  then 
an  assignment  such  as  x [ i]  =  2  really  changes  t he  array  element  a[2].  T he 
reason  is  t h a t,  although  x  gets  a  copy  of  t he  value  of  a,  t h at  value  is  really  a 
pointer  to  the  beginning  of  the  area  of  t he  store  where  t he  array  named  a  is 
located. 

Similarly,  in  Java,  many  variables  are  really  references,  or  pointers,  to  the 
things  they  stand  for.  This  observation  applies  to  arrays,  strings,  and  objects 
of  all  classes.  Even  though  Java  uses  call-by-value  exclusively,  whenever  we 
pass  the  name  of  an  object  to  a  called  procedure,  the  value  received  by  t h at 
procedure  is  in  effect  a  pointer  to  the  object.  Thus,  the  called  procedure  is  able 
to  affect  the  value  of  the  object  itself. 

C a l l - b y - R e f e r e n ce 

In  call-by-reference,  the  address  of t he  actual  parameter  is  passed  to  t he  callee  as 
t he  value  of  the  corresponding  formal  parameter.  Uses  of  the  formal  parameter 
in  the  code  of the  callee  are  implemented  by  following  this  pointer  to  the  location 
indicated  by  the  caller.  Changes  to  the  formal  parameter  thus  appear  as  changes 
to  the  actual  parameter. 

If  t he  actual  parameter  is  an  expression,  however,  then  the  expression  is 
evaluated  before  t he  call,  and  its  value  stored  in  a  location  of  its  own.  Changes 
to  the  formal  parameter  change  this  location,  but  can  have  no  effect  on  t he 
d a ta  of  the  caller. 

Call-by-reference  is  used  for  "ref"  parameters  in  C ++  and  is  an  option  in 
many  other  languages.  It  is  almost  essential  when  the  formal  parameter  is  a 
large  object,  array,  or  structure.  T he  reason  is  t h at  strict  call-by-value  requires 
t h at  the  caller  copy  the  entire  actual  parameter  into  t he  space  belonging  to 
the  corresponding  formal  parameter.  This  copying  gets  expensive  when  t he 
parameter  is  large.  As  we  noted  when  discussing  call-by-value,  languages  such 
as  Java  solve  t he  problem  of passing  arrays,  strings,  or  other  objects  by  copying 
only  a  reference  to  those  objects.  The  effect  is  t h at  Java  behaves  as  if  it  used 
call-by-reference  for  anything  other  t h an  a  basic  type  such  as  an  integer  or  real. 

1.6. 

PROGRAMMING 

LANGUAGE  BASICS 

35 

C a l l - b y - N a me 

A  third  mechanism  —  call-by-name  —  was  used  in  the  early  programming 
language  Algol  60.  It  requires  t h at  the  callee  execute  as  if t he  actual  parameter 
were  substituted  literally  for  the  formal  parameter  in  the  code  of  the  callee,  as 
if  the  formal  parameter  were  a  macro  standing  for  the  actual  parameter  (with 
renaming  of  local  names  in  t he  called  procedure,  to  keep  t h em  distinct).  W h en 
the  actual  parameter  is  an  expression  rather  t h an  a  variable,  some  unintuitive 
behaviors  occur,  which  is  one  reason  this  mechanism  is  not  favored  today. 

1.6.7  Aliasing 

There  is  an  interesting  consequence  of  call-by-reference  parameter  passing  or 
its  simulation,  as  in  Java,  where  references  to  objects  are  passed  by  value.  It 
is  possible  t h at  two  formal  parameters  can  refer  to  t he  same  location;  such 
variables  are  said  to  be  aliases  of  one  another.  As  a  result,  any  two  variables, 
which  may  appear  to  take  their  values  from  two  distinct  formal  parameters,  can 
become  aliases  of  each  other,  as  well. 

E x a m p le  1 . 9:  Suppose  a  is  an  array  belonging  to  a  procedure  p,  and  p  calls 
another  procedure  q(x,y)  with  a  call  q(a,a). 
Suppose  also  t h at  parameters 
are  passed  by  value,  but  t h at  array  names  are  really  references  to  the  location 
where  the  array  is  stored,  as  in  C  or  similar  languages.  Now,  x  and  y  have 
become  aliases  of  each  other.  The  important  point  is  t h at  if  within  q  there  is 
an  assignment  x [ 1 0]  =  2,  then  t he  value  of  y[10]  also  becomes  2. 

• 

It  t u r ns  out  t h at  understanding  aliasing  and  the  mechanisms  t h at  create  it 
is  essential  if  a  compiler  is  to  optimize  a  program.  As  we  shall  see  starting  in 
Chapter  9,  there  are  many  situations  where  we  can  only  optimize  code  if  we 
can  be  sure  certain  variables  are  not  aliased.  For  instance,  we  might  determine 
t h at  x  =  2  is  the  only  place  t h at  variable  x  is  ever  assigned.  If  so,  then  we  can 
replace  a  use  of  x  by  a  use  of  2;  for  example,  replace  a  =  x+3  by  the  simpler 
a  =  5.  But  suppose  there  were  another  variable  y  t h at  was  aliased  to  x.  Then 
an  assignment  y  =  4  might  have  the  unexpected  effect  of  changing  x.  It  might 
also  mean  t h at  replacing  a  =  x+3  by  a  =  5  was  a  mistake;  the  proper  value  of 
a  could  be  7  there. 

1.6.8  Exercises  for  Section  1.6 

E x e r c i se  1 . 6 . 1:  For  the  block-structured  C  code  of  Fig.  1.13(a),  indicate  the 
values  assigned  to  w,  x,  y,  and  z. 

E x e r c i se  1 . 6 . 2:  Repeat  Exercise  1.6.1  for  the  code  of  Fig.  1.13(b). 

E x e r c i se  1 . 6 . 3:  For  the  block-structured  code  of Fig.  1.14,  assuming  t he  usual 
static  scoping  of declarations,  give  the  scope  for  each  of the  twelve  declarations. 

36 

CHAPTER 

1. 

INTRODUCTION 

int w,  x,  y,  z; 
int  i  = 4;  int  j  = 5; 
< 

int  j  =  7; 
i = 6; 
w  =  i + j; 

} 
x  =  i  + j; 
{ 

int  i  =  8; 
y  =  i  + j; 

} 
z  =  i  + j; 

int w,  x,  y,  z; 
int  i  = 3;  int  j  = 4; 
{ 

int  i  =  5; 
w =  i  + j; 

} 
x  =  i  + j; 
{ 

int  j  =  6; 
i  =  7; 

y =  i  + j; 

} 
z  =  i  +  j; 

(a)  Code  for  Exercise 1.6.1 

(b)  Code  for  Exercise 1.6.2 

Figure 1.13:  Block-structured  code 

int w,  x,  y,  z; 

/*  Block Bl  */ 

{ 

int  x,  z; 

/*  Block B2  */ 

{ 

int  w,  x; 

/*  Block B3  */  } 

} 
{ 

} 

int  w,  x; 
{ 

int  y,  z; 

/*  Block B4  */ 
/*  Block B5  */  } 

Figure 1.14:  Block  structured  code  for  Exercise 1.6.3 

Exercise  1 . 6 . 4:  W h at  is  printed  by  the  following  C  code? 

#define  a  (x+1) 

int  x  =  2; 

void b()  { x = a; printf ("°/,d\nM, x) ;  } 

void c()  {  int x = 1;  printf ("°/,d\n"),  a;  > 

void m a i nO  { b ( );  c ( );  } 

1.7  Summary  of  Chapter  1 

•  Language  Processors.  An  integrated  software  development  environment 
includes  many  different  kinds  of  language  processors  such  as  compilers, 
interpreters,  assemblers,  linkers,  loaders,  debuggers,  profilers. 

•  Compiler  Phases.  A  compiler  operates  as  a  sequence  of  phases,  each  of 
which  transforms  t he  source  program  from  one  intermediate  representa 
tion  to  another. 

1.7. 

SUMMARY  OF  CHAPTER  1 

37 

4>  Machine  and  Assembly  Languages.  Machine 

languages  were  t he  first-
generation  programming  languages, followed by  assembly  languages.  P r o 
gramming  in  these  languages  was  time  consuming  and  error  prone. 

4  Modeling  in  Compiler  Design.  Compiler  design  is  one  of  t he  places  where 
theory  has  had  the  most  impact  on  practice.  Models  t h at  have  been  found 
useful  include  a u t o m a t a,  grammars,  regular  expressions,  trees,  and  many 
others. 

4  Code  Optimization.  Although  code  cannot  truly  be  "optimized,"  the  sci 
ence  of  improving  t he  efficiency  of  code  is  b o th  complex  and  very  impor 
t a n t.  It  is  a  major  portion  of  the  study  of  compilation. 

4  Higher-Level  Languages.  As  time  goes  on,  programming  languages  take 
on  progressively  more  of the  tasks  t h at  formerly  were  left  to  the  program 
mer,  such  as  memory  management,  type-consistency  checking,  or  parallel 
execution  of  code. 

4  Compilers  and  Computer  Architecture. 

Compiler 

technology 

influences 

computer  architecture,  as  well  as  being  influenced  by  t he  advances  in  ar 
chitecture.  Many  modern  innovations  in  architecture  depend  on  compilers 
being  able  to  extract  from  source  programs  the  opportunities  to  use  the 
hardware  capabilities  effectively. 

4  Software  Productivity  and  Software  Security.  The  same  technology  t h at 
allows  compilers  to  optimize  code  can  be  used  for  a  variety  of  program-
analysis  tasks,  ranging  from  detecting  common  program  bugs  to  discov 
ering  t h at  a  program  is  vulnerable  to  one  of  the  many  kinds  of  intrusions 
t h at  "hackers"  have  discovered. 

4  Scope  Rules.  T he  scope  of  a  declaration  of  x  is  the  context  in  which  uses 
of  x  refer  to  this  declaration.  A  language  uses  static  scope  or  lexical  scope 
if  it  is  possible  to  determine  the  scope  of  a  declaration  by  looking  only  at 
the  program.  Otherwise,  the  language  uses  dynamic  scope. 

4  Environments.  The  association  of  names  with  locations  in  memory  and 
then  with  values  can  be  described  in  terms  of  environments,  which  m ap 
names  to  locations  in  store,  and  states,  which  m ap  locations  to  their 
values. 

4-  Block  Structure.  Languages  t h at  allow  blocks  to  be  nested  are  said  to 
have  block  structure.  A  name  a:  in  a  nested  block  B  is  in  t he  scope  of  a 
declaration  D  of  x  in  an  enclosing  block  if  there  is  no  other  declaration 
of  x  in  an  intervening  block. 

4  Parameter  Passing.  Parameters  are  passed  from  a  calling  procedure  to 
t he  callee  either  by  value  or  by  reference.  When  large  objects  are  passed 
by  value,  the  values  passed  are  really  references  to  t he  objects  themselves, 
resulting  in  an  effective  call-by-reference. 

38 

CHAPTER 

1. 

INTRODUCTION 

•  Aliasing.  When  parameters  are  (effectively)  passed  by  reference,  two  for 
mal  parameters  can  refer  to  the  same  object.  This  possibility  allows  a 
change  in  one  variable  to  change  another. 

1.8  References  for  Chapter  1 

For  the  development  of  programming  languages  t h at  were  created  and  in  use 
by  1967,  including  Fortran,  Algol,  Lisp,  and  Simula,  see  [7].  For  languages  t h at 
were  created  by  1982,  including  C,  C + +,  Pascal,  and  Smalltalk,  see  [1]. 

The  GNU  Compiler  Collection,  gcc,  is  a  popular  source  of  open-source 
compilers  for  C,  C + +,  Fortran,  Java,  and  other  languages  [2].  Phoenix  is  a 
compiler-construction  toolkit  t h at  provides  an  integrated  framework  for  build 
ing  the  program  analysis,  code  generation,  and  code  optimization  phases  of 
compilers  discussed  in  this  book  [3]. 

For  more  information  about  programming  language  concepts,  we  recom 
mend  [5,6].  For  more  on  computer  architecture  and  how  it  impacts  compiling, 
we  suggest  [4]. 

1.  Bergin,  T.  J.  and  R.  G.  Gibson,  History  of  Programming  Languages,  ACM 

Press,  New  York,  1996. 

2.  http://gcc.gnu.org/. 

3.  http://research.microsoft.com/phoenix/default.aspx . 

4.  Hennessy,  J.  L.  and  D.  A.  Patterson,  Computer  Organization  and  De 
Interface,  Morgan-Kaufmann,  San  Fran 

The  Hardware/Software 

sign: 
cisco,  CA,  2004. 

5.  Scott,  M.  L.,  Programming  Language  Pragmatics,  second  edition,  Morgan-

Kaufmann,  San  Francisco,  CA,  2006. 

6.  Sethi,  R.,  Programming  Languages:  Concepts  and  Constructs,  Addison-

Wesley,  1996. 

7.  Wexelblat,  R.  L.,  History  of  Programming  Languages,  Academic  Press, 

New  York,  1981. 

Chapter  2 

A  Simple  Syntax-Directed 
Translator 

This  chapter  is  an  introduction  to  t he  compiling  techniques  in  Chapters  3 
through  6  of  this  book.  It  illustrates  the  techniques  by  developing  a  working 
Java  program  t h at  translates  representative  programming  language  statements 
In  this  chapter,  the 
into  three-address  code,  an  intermediate  representation. 
emphasis  is  on  t he  front  end  of  a  compiler,  in  particular  on  lexical  analysis, 
parsing,  and  intermediate  code  generation.  Chapters  7  and  8  show  how  to 
generate  machine  instructions  from  three-address  code. 

We  start  small  by  creating  a  syntax-directed  translator  t h at  maps  infix  arith 
metic  expressions  into  postfix  expressions.  We  then  extend  this  translator  to 
m ap  code  fragments  as  shown  in  Fig.  2.1  into  three-address  code  of  the  form 
in  Fig.  2.2. 

T he  working  Java  translator  appears  in  Appendix  A.  The  use  of  Java  is 
In  fact,  the  ideas  in  this  chapter  predate  t he 

convenient,  but  not  essential. 
creation  of  both  Java  and  C. 

{ 

} 

i nt 

i; 

i nt 

j; 

f l o a t [ 1 0 0]  a; 

f l o at  v; 

f l o at  x; 

w h i le  (  t r ue  )  { 

do  i  =  i + 1;  w h i le  (  a [ i]  <  v  ); 
do  j  =  j - 1;  w h i le  (  a [ j]  >  v  ); 
if 
)  b r e a k; 
x  =  a [ i ];  a [ i]  =  a [ j]  ;  a [ j]  =  x; 

i  >=  j 

( 

} 

Figure  2.1:  A  code  fragment  to  be  translated 

39 

40 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

1 

2 

3: 

4: 

5: 

6: 
7: 
8: 
9: 

10: 

11: 

12: 

i  =  i +  1 

tl  = a  [  i  ] 

if  tl  <  v goto 

1 

4 

goto  9 

J  = J  -  1 
t2  -  a  [  j  ] 
if  t2  >  v goto 
ifFalse  i  >= j 
goto  14 
x =  a  [  i ] 
t3 = a  [ j  ] 
a  [ i ]  = t3 
a  [ j  ]  = x 

13: 

goto  1 

14: 

Figure 2.2:  Simplified  intermediate  code  for  the  program  fragment  in  Fig. 2.1 

2.1 

Introduction 

T he  analysis  phase  of  a  compiler  breaks  up  a  source  program  into  constituent 
pieces  and  produces  an  internal  representation  for  it,  called  intermediate  code. 
T he  synthesis  phase  translates  the  intermediate  code  into  the  target  program. 
Analysis  is  organized  around  the  "syntax"  of  t he  language  to  be  compiled. 
The  syntax  of  a  programming  language  describes  the  proper  form  of  its  pro 
grams,  while  t he  semantics  of t he  language  defines  what  its  programs  mean;  t h at 
is,  what  each  program  does  when  it  executes.  For  specifying  syntax,  we  present 
a  widely  used  notation,  called  context-free  grammars  or  B NF  (for  Backus-Naur 
Form)  in  Section 2.2.  W i th  t he  notations  currently  available,  t he  semantics  of 
a  language  is  much  more  difficult  to  describe  t h an  t he  syntax.  For  specifying 
semantics,  we  shall  therefore  use  informal  descriptions  and  suggestive  examples. 

Besides  specifying  the  syntax  of  a  language,  a  context-free  g r a m m ar  can  be 
used  to  help  guide  the  translation  of  programs.  In  Section 2.3,  we  introduce 
a  grammar-oriented  compiling  technique  known  as  syntax-directed 
translation. 
Parsing  or  syntax  analysis  is  introduced  in  Section 2.4. 

T he  rest  of  this  chapter  is  a  quick  tour  through  t he  model  of  a  compiler 
front  end  in  Fig. 2.3.  We  begin  with  t he  parser.  For  simplicity,  we  consider  t he 
syntax-directed  translation  of  infix  expressions  to  postfix  form,  a  notation  in 
which  operators  appear  after  their  operands.  For  example,  t he  postfix  form  of 
t he  expression 9 - 5 + 2  is 95 - 2 +.  Translation  into  postfix  form  is  rich  enough 
to  illustrate  syntax  analysis,  yet  simple  enough  t h at  t he  translator  is  shown  in 
full  in  Section 2.5.  T he  simple  translator  handles  expressions  like 9 -5 + 2, 
consisting  of  digits  separated  by  plus  and  minus  signs.  One  reason  for  starting 
with  such  simple  expressions  is  t h at  t he  syntax  analyzer  can  work  directly  with 
the  individual  characters  for  operators  and  operands. 

2.1. 

INTRODUCTION 

41 

source 
Lexical 
program  Analyzer 

tokens 

Parser 
Parser 

Intermediate 
syntax  Intermediate 
Code 
Code 
tree 
Generator 
Generator 

three-address 
code 

Symbol 
Table 

Figure  2.3:  A  model  of  a  compiler  front  end 

A  lexical  analyzer  allows  a  translator  to  handle  multicharacter  constructs 
like  identifiers,  which  are  written  as  sequences  of  characters,  b ut  are  treated 
as  units  called  tokens  during  syntax  analysis;  for  example,  in  the  expression 
c o u n t+ 1,  the  identifier  count  is  treated  as  a  unit.  The  lexical  analyzer  in 
Section  2.6  allows  numbers,  identifiers,  and  "white  space"  (blanks,  t a b s,  and 
newlines)  to  appear  within  expressions. 

Next,  we  consider  intermediate-code  generation.  Two  forms  of  intermedi 
ate  code  are  illustrated  in  Fig.  2.4.  One  form,  called  abstract  syntax  trees  or 
simply  syntax  trees,  represents  the  hierarchical  syntactic  structure  of  the  source 
In  t he  model  in  Fig.  2.3,  the  parser  produces  a  syntax  tree,  t h at 
program. 
is  further  translated  into  three-address  code.  Some  compilers  combine  parsing 
and  intermediate-code  generation  into  one  component. 

i  =  i  +  1 

tl  =  a  [  i  ] 

if  tl  <  v  goto  1 

(b) 

do-while 

> 

body 

assign 

+ 

(a) 

Figure  2.4:  Intermediate  code  for  "do  i =  i +  1;  w h i le  (  a [ i]  < v ) ;" 

The  root  of  the  abstract  syntax  tree  in  Fig.  2.4(a)  represents  an  entire  do-
while  loop.  T he  left  child  of  the  root  represents  the  body  of  the  loop,  which 
consists  of  only  t he  assignment  i =  i +  1 ;.  T he  right  child  of  t he  root  repre 
sents  the  condition  a[ i]  <v.  An  implementation  of  syntax  trees  appears  in 
Section  2.8(a). 

T he  other  common  intermediate  representation,  shown  in  Fig.  2.4(b),  is  a 

42 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

sequence  of  "three-address"  instructions;  a  more  complete  example  appears  in 
Fig.  2.2.  This  form  of  intermediate  code  takes  its  name  from  instructions  of 
the  form  x  =  y  op  z,  where  op  is  a  binary  operator,  y  and  z  the  are  addresses 
for  the  operands,  and  x  is  the  address  for  t he  result  of  the  operation.  A  three-
address  instruction  carries  out  at  most  one  operation,  typically  a  computation, 
a  comparison,  or  a  branch. 

In  Appendix  A,  we  put  the  techniques  in  this  chapter  together  to  build  a 
compiler  front  end  in  Java.  The  front  end  translates  statements  into  assembly-
level  instructions. 

2.2  Syntax  Definition 

In  this  section,  we  introduce  a  notation  —  the  "context-free  grammar,"  or 
"grammar"  for  short  —  t h at  is  used  to  specify  t he  syntax  of  a  language.  Gram 
mars  will  be  used  throughout  this  book  to  organize  compiler  front  ends. 

A  g r a m m ar  naturally  describes  t he  hierarchical  structure  of  most  program 
ming  language  constructs.  For  example,  an  if-else  statement  in  Java  can  have 
t he  form 

if  (  expression  )  statement  e l se  statement 

T h at  is,  an  if-else  statement  is  t he  concatenation  of the  keyword  if,  an  open 

ing  parenthesis,  an  expression,  a  closing  parenthesis,  a  statement,  t he  keyword 
else,  and  another  statement.  Using  the  variable  expr  to  denote  an  expres 
sion  and  t he  variable  stmt  to  denote  a  statement,  this  structuring  rule  can  be 
expressed  as 

stmt  —> 

if  (  expr  )  stmt  e l se  stmt 

in  which  t he  arrow  m ay  be  read  as  "can  have  the  form."  Such  a  rule  is  called  a 
production.  In  a  production,  lexical  elements  like  the  keyword  if and  the  paren 
theses  are  called  terminals.  Variables  like  expr  and  stmt  represent  sequences  of 
terminals  and  are  called  nonterminals. 

2.2.1  Definition  of  Grammars 

A  context-free  grammar  has  four  components: 

1.  A  set  of  terminal  symbols,  sometimes  referred  to  as  "tokens."  T he  termi 
nals  are  t he  elementary  symbols  of the  language  defined  by  the  grammar. 

2.  A  set  of  nonterminals,  sometimes  called  "syntactic  variables."  Each  non 
terminal  represents  a  set  of  strings  of  terminals,  in  a  manner  we  shall 
describe. 

3.  A  set  of  productions,  where  each  production  consists  of  a  nonterminal, 
called  the  head  or  left  side  of  t he  production,  an  arrow,  and  a  sequence  of 

2.2. 

SYNTAX  DEFINITION 

43 

Tokens  Versus  Terminals 

In  a  compiler,  t he  lexical  analyzer  reads  the  characters  of  the  source  pro 
gram,  groups  t h em  into  lexically  meaningful  units  called  lexemes,  and  pro 
duces  as  output  tokens  representing  these  lexemes.  A  token  consists  of two 
components,  a  token  name  and  an  a t t r i b u te  value.  T he  token  names  are 
abstract  symbols  t h at  are  used  by  t he  parser  for  syntax  analysis.  Often, 
we  shall  call  these  token  names  terminals,  since  they  appear  as  terminal 
symbols  in  t he  grammar  for  a  programming language.  T he  a t t r i b u te  value, 
if  present,  is  a  pointer  to  the  symbol  table  t h at  contains  additional  infor 
mation  about  the  token.  This  additional  information  is  not  part  of  t he 
grammar,  so  in  our  discussion  of  syntax  analysis,  often  we  refer  to  tokens 
and  terminals  synonymously. 

terminals  a n d / or  nonterminals,  called  t he  body  or  right  side  of t he  produc 
tion.  T he  intuitive  intent  of  a  production  is  to  specify  one  of  the  written 
forms  of  a  construct;  if  the  head  nonterminal  represents  a  construct,  then 
t he  body  represents  a  written  form  of  t he  construct. 

4.  A  designation  of  one  of  t he  nonterminals  as  the  start  symbol. 

We  specify  grammars  by  listing  their  productions,  with  t he  productions 
for  the  start  symbol  listed  first.  We  assume  t h at  digits,  signs  such  as  <  and 
<=,  and  boldface  strings  such  as  w h i le  are  terminals.  An  italicized  name  is  a 
nonterminal,  and  any  nonitalicized  name  or  symbol  may  be  assumed  to  be  a 
terminal.1  For  notational  convenience,  productions  with  the  same  nonterminal 
as  the  head  can  have  their  bodies  grouped,  with  the  alternative  bodies  separated 
by  the  symbol  |,  which  we  read  as  "or." 

E x a m p le  2 . 1:  Several  examples  in  this  chapter  use  expressions  consisting  of 
digits  and  plus  and  minus  signs;  e.g.,  strings  such  as  9-5+2,  3 - 1,  or  7.  Since  a 
plus  or  minus  sign  must  appear  between  two  digits,  we  refer  to  such  expressions 
as  "lists  of  digits  separated  by  plus  or  minus  signs."  The  following  grammar 
describes  t he  syntax  of  these  expressions.  T he  productions  are: 

list 

list 

list 

-> 

-+ 

list  +  digit 

list  -  digit 

-»•  digit 

digit 

0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |9 

(2.1) 

(2.2) 

(2.3) 

(2.4) 

1 Individual  italic  letters  will  be  used  for  additional  purposes,  especially  when  grammars 
are  studied  in  detail  in  Chapter  4.  For  example,  we  shall  use  X,  Y,  and  Z  to  talk  about  a 
symbol  that  is  either  a  terminal  or  a  nonterminal.  However,  any  italicized  name  containing 
two  or  more  characters  will  continue  to  represent  a  nonterminal. 

44 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

The  bodies  of  the  three  productions  with  nonterminal  list  as  head  equiva-

lently  can  be  grouped: 

list 

-+ 

list  +  digit 

| 

list  -  digit 

|  digit 

According  to  our  conventions,  the  terminals  of the  g r a m m ar  are  the  symbols 

+ 

- 0 1 2 3 4 5 6 7 89 

T he  nonterminals  are  the  italicized  names  list  and  digit,  with  list  being  t he  start 
symbol  because  its  productions  are  given  first. 

• 

We  say  a  production  is  for  a  nonterminal  if  t he  nonterminal  is  t he  head  of 
the  production.  A  string  of  terminals  is  a  sequence  of  zero  or  more  terminals. 
The  string  of  zero  terminals,  written  as  e,  is  called  t he  empty  string.2 

2.2.2  Derivations 

A  grammar  derives  strings  by  beginning  with  the  start  symbol  and  repeatedly 
replacing  a  nonterminal  by  t he  body  of  a  production  for  t h at  nonterminal.  T he 
terminal  strings  t h at  can  be  derived  from  the  start  symbol  form  t he  language 
defined  by  the  grammar. 

E x a m p le  2 . 2:  The  language  defined  by  t he  g r a m m ar  of  Example  2.1  consists 
of lists  of digits  separated  by  plus  and  minus  signs.  T he  ten  productions  for  the 
nonterminal  digit  allow  it  to  stand  for  any  of  the  terminals  0 , 1 , . ..  , 9.  From 
production  (2.3),  a  single  digit  by  itself  is  a  list.  Productions  (2.1)  and  (2.2) 
express  the  rule  t h at  any  list  followed  by  a  plus  or  minus  sign  and  then  another 
digit  makes  up  a  new  list. 

Productions  (2.1)  to  (2.4)  are  all  we  need  to  define  the  desired  language. 

For  example,  we  can  deduce  t h at  9-5+2  is  a  list  as  follows. 

a)  9  is  a  list  by  production  (2.3),  since  9  is  a  digit. 

b)  9-5  is  a  list  by  production  (2.2),  since  9  is  a  list  and  5  is  a  digit. 

c)  9-5+2  is  a  list  by  production  (2.1),  since  9 -5  is  a  list  and  2  is  a  digit. 

• 

E x a m p le  2 . 3:  A  somewhat  different  sort  of  list  is  the  list  of  parameters  in  a 
function  call. 
In  Java,  the  parameters  are  enclosed  within  parentheses,  as  in 
the  call  max(x , y)  of function  max  with  parameters  x  and  y.  One  nuance  of such 
lists  is  t h at  an  empty  list  of  parameters  m ay  be  found  between  t he  terminals 
(  and  ).  We  may  start  to  develop  a  grammar  for  such  sequences  with  the 
productions: 

2Technically,  e  can  be  a  string  of  zero  symbols  from  any  alphabet  (collection  of  symbols). 

2.2. 

SYNTAX  DEFINITION 

45 

call 
optparams 

->• 
-> 

id  (  optparams  ) 
\  e 

params 

params  —> 

params  ,  param 

\  param 

Note  t h at  t he  second  possible  body  for  optparams  ("optional  parameter  list") 
is  e,  which  stands  for  the  empty  string  of  symbols.  T h at  is,  optparams  can  be 
replaced  by  the  empty  string,  so  a  call  can  consist  of  a  function  name  followed 
by  the  two-terminal  string  ( ).  Notice  t h at  the  productions  for  params  are 
analogous  to  those  for  list in  Example  2.1,  with  comma  in  place  of t he  arithmetic 
operator  +  or  -,  and  param  in  place  of  digit.  We  have  not  shown  t he  productions 
for  param,  since  parameters  are  really  arbitrary  expressions.  Shortly,  we  shall 
discuss  t he  appropriate  productions  for  t he  various  language  constructs,  such 
as  expressions,  statements,  and  so  on. 

• 

Parsing  is  t he  problem  of  taking  a  string  of  terminals  and  figuring  out  how 
to  derive  it  from  the  start  symbol  of  the  grammar,  and  if  it  cannot  be  derived 
from  the  start  symbol  of  the  grammar,  then  reporting  syntax  errors  within  t he 
string.  Parsing  is  one  of  t he  most  fundamental  problems  in  all  of  compiling; 
t he  main  approaches  to  parsing  are  discussed  in  Chapter  4.  In  this  chapter,  for 
simplicity,  we  begin  with  source  programs  like  9-5+2  in  which  each  character 
is  a  terminal;  in  general,  a  source  program  has  multicharacter  lexemes  t h at  are 
grouped  by  t he  lexical  analyzer  into  tokens,  whose  first  components  are  the 
terminals  processed  by  the  parser. 

2.2.3  Parse  Trees 

A  parse  tree  pictorially  shows  how  the  start  symbol  of  a  grammar  derives  a 
string  in  the  language.  If  nonterminal  A  has  a  production  A 
->  XYZ,  then  a 
parse  tree  may  have  an  interior  node  labeled  A  with  three  children  labeled  X, 
Y,  and  Z,  from  left  to  right: 

A 

X

YZ 

Formally,  given  a  context-free  grammar,  a  parse  tree  according  to  the  gram 

m ar  is  a  tree  with  t he  following  properties: 

1.  T he  root  is  labeled  by  t he  s t a rt  symbol. 

2.  Each  leaf  is  labeled  by  a  terminal  or  by  e. 

3.  Each  interior  node  is  labeled  by  a  nonterminal. 

4.  If A  is  t he  nonterminal  labeling  some  interior  node  and  X\,  X2,  •  •  •  ,  Xn  are 
t he  labels  of  t he  children  of  t h at  node  from  left  to  right,  then  there  must 
be  a  production  A  —>  X1X2  •  •  •  Xn.  Here,  X\,X2,..  •  ,Xn  each  stand 

46 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

Tree  Terminology 

Tree  d a ta  structures  figure  prominently  in  compiling. 

•  A  tree  consists  of  one  or  more  nodes.  Nodes  may  have  labels,  which 
in  this  book  typically  will  be  grammar  symbols.  W h en  we  draw  a 
tree,  we  often  represent  t he  nodes  by  these  labels  only. 

•  Exactly  one  node  is  the  root.  All  nodes  except  the  root  have  a  unique 
parent;  t he  root  has  no  parent.  W h en  we  draw  trees,  we  place  the 
parent  of  a  node  above  t h at  node  and  draw  an  edge  between  them. 
T he  root  is  then  the  highest  (top)  node. 

•  If  node  N  is  the  parent  of  node  M,  then  M  is  a  child  of  N.  The 
children  of  one  node  are  called  siblings.  They  have  an  order,  from 
the  left,  and  when  we  draw  trees,  we  order  the  childen  of  a  given 
node  in  this  manner. 

•  A  node  with  no  children  is  called  a  leaf.  Other  nodes  —  those  with 

one  or  more  children  —  are  interior  nodes. 

•  A  descendant  of  a  node  N  is  either  N  itself,  a  child  of  N,  a  child  of 
a  child  of  N,  and  so  on,  for  any  number  of  levels.  We  say  node  N  is 
an  ancestor  of  node  M  if  M  is  a  descendant  of  N. 

for  a  symbol  t h at  is  either  a  terminal  or  a  nonterminal.  As  a  special  case, 
if  A  ->•  e  is  a  production,  then  a  node  labeled  A  may  have  a  single  child 
labeled  e. 

E x a m p le  2 . 4:  T he  derivation  of  9-5+2  in  Example  2.2  is  illustrated  by  t he 
tree  in  Fig.  2.5.  Each  node  in  t he  tree  is  labeled  by  a  grammar  symbol.  An 
interior  node  and  its  children  correspond  to  a  production;  the  interior  node 
corresponds  to  the  head  of  the  production,  the  children  to  t he  body. 

In  Fig.  2.5,  the  root  is  labeled  list,  the  start  symbol  of  the  g r a m m ar  in 
Example  2.1.  T he  children  of  t he  root  are  labeled,  from  left  to  right,  list,  +, 
and  digit.  Note  t h at 

list  —>• 

list  +  digit 

is  a  production  in  the  grammar  of  Example  2.1.  T he  left  child  of  the  root  is 
similar  to  t he  root,  with  a  child  labeled  -  instead  of  +.  T he  three  nodes  labeled 
digit  each  have  one  child  t h at  is  labeled  by  a  digit. 

• 

From  left  to  right,  the  leaves  of a  parse  tree  form  t he  yield  of t he  tree,  which 
is  the  string  generated  or  derived  from  t he  nonterminal  at  the  root  of  t he  parse 

2.2. 

SYNTAX  DEFINITION 

47 

list 

list 

digit 

digit 

5 

+ 

2 

list 

digit 

9 

Figure  2.5:  Parse  tree  for  9-5+2  according  to  the  grammar  in  Example  2.1 

tree.  In  Fig.  2.5,  the  yield  is  9-5+2;  for  convenience,  all  the  leaves  are  shown 
at  the  b o t t om  level.  Henceforth,  we  shall  not  necessarily  line  up  the  leaves  in 
this  way.  Any  tree  imparts  a  natural  left-to-right  order  to  its  leaves,  based  on 
the  idea  t h at  if  X  and  Y  are  two  children  with  the  same  parent,  and  X  is  to 
the  left  of  y,  then  all  descendants  of  X  are  to  the  left  of  descendants  of  Y. 

Another  definition  of  t he  language  generated  by  a  grammar  is  as  t he  set  of 
strings  t h at  can  be  generated  by  some  parse  tree.  The  process  of finding  a  parse 
tree  for  a  given  string  of  terminals  is  called  parsing  t h at  string. 

2.2.4  Ambiguity 

We  have  to  be  careful  in  talking  about  the  structure  of  a  string  according  to  a 
grammar.  A  grammar  can  have  more  t h an  one  parse  tree  generating  a  given 
string  of  terminals.  Such  a  grammar  is  said  to  be  ambiguous.  To  show  t h at  a 
grammar  is  ambiguous,  all  we  need  to  do  is  find  a  terminal  string  t h at  is  the 
yield  of  more  t h an  one  parse  tree.  Since  a  string  with  more  t h an  one  parse  tree 
usually  has  more  t h an  one  meaning,  we  need  to  design  unambiguous  grammars 
for  compiling  applications,  or  to  use  ambiguous  grammars  with  additional  rules 
to  resolve  t he  ambiguities. 

E x a m p le  2 . 5:  Suppose  we  used  a  single  nonterminal  string  and  did  not  dis 
tinguish  between  digits  and  lists,  as  in  Example  2.1.  We  could  have  written  t he 
g r a m m ar 

string 

-» 

string  +  string  \  string  -  string  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 J9 

Merging  the  notion  of  digit  and  list  into  the  nonterminal  string  makes  superficial 
sense,  because  a  single  digit  is  a  special  case  of  a  list. 

However,  Fig.  2.6  shows  t h at  an  expression  like  9-5+2  has  more  t h an  one 
parse  tree  with  this  grammar.  The  two  trees  for  9-5+2  correspond  to  the  two 
( 9 - 5 ) +2  and  9 - ( 5 + 2 ).  This  second 
ways  of  parenthesizing  t he  expression: 
parenthesization  gives  the  expression  the  unexpected  value  2  rather  t h an  the 
customary  value  6.  T he  grammar  of  Example  2.1  does  not  permit  this  inter 
pretation. 

• 

48 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

string 

/ 
string 

l 
+ 

\ 
string 

string 

string 

2 

string 

- 

string 

string 
i 
9 

string 
/  I  \ 
+ 

string 

9 

5 

5 

2 

Figure  2.6:  Two  parse  trees  for  9-5+2 

2.2.5  Associativity  of  Operators 

By  convention,  9+5+2  is  equivalent  to  (9+5)+2  and  9 - 5 -2  is  equivalent  to 
( 9 - 5 ) - 2.  When  an  operand  like  5  has  operators  to  its  left  and  right,  con 
ventions  are  needed  for  deciding  which  operator  applies  to  t h at  operand.  We 
say  t h at  the  operator  +  associates  to  the  left,  because  an  operand  with  plus  signs 
on  both  sides  of  it  belongs  to  the  operator  to  its  left. 
In  most  programming 
languages  the  four  arithmetic  operators,  addition,  subtraction,  multiplication, 
and  division  are  left-associative. 

Some  common  operators  such  as  exponentiation  are  right-associative.  As 
another  example,  the  assignment  operator  =  in  C  and  its  descendants  is  right-
associative;  t h at  is,  the  expression  a=b=c  is  treated  in  t he  same  way  as  t he 
expression  a= ( b = c ). 

Strings  like  a=b=c  with  a  right-associative  operator  are  generated  by  the 

following  grammar: 

right 
letter 

->• 
-> 

letter  =  right 
a  |  b  |  • • •  |  z 

| 

letter 

T he  contrast  between  a  parse  tree  for  a  left-associative  operator  like  -  and 
a  parse  tree  for  a  right-associative  operator  like  =  is  shown  by  Fig.  2.7.  Note 
t h at  the  parse  tree  for  9 - 5 -2  grows  down  towards  t he  left,  whereas  the  parse 
tree  for  a-b=c  grows  down  towards  the  right. 

2.2.6  Precedence  of  Operators 

Consider  the  expression  9+5*2.  There  are  two  possible  interpretations  of  this 
expression:  (9+5)*2  or  9 + ( 5 * 2 ).  The  associativity  rules  for  +  and  *  apply  to 
occurrences  of t he  same  operator,  so  they  do  not  resolve  this  ambiguity.  Rules 
defining  t he  relative  precedence  of  operators  are  needed  when  more  t h an  one 
kind  of  operator  is  present. 

We  say  t h at  *  has  higher  precedence  t h an  +  if  *  takes  its  operands  before  + 
does.  In  ordinary  arithmetic,  multiplication  and  division  have  higher  precedence 
t h an  addition  and  subtraction.  Therefore,  5  is  taken  by  *  in  b o th  9+5*2  and 
9*5+2;  i.e.,  the  expressions  are equivalent  to  9+(5*2)  and  (9*5)+2,  respectively. 

2.2. 

SYNTAX  DEFINITION 

49 

list 

right 

list 

- 

digit 

letter 

= 

right 

Figure  2.7:  Parse  trees  for  left-  and  right-associative  grammars 

E x a m p le  2.6  :  A  grammar  for  arithmetic  expressions  can  be  constructed  from 
a  table  showing  the  associativity  and  precedence  of  operators.  We  start  with 
the  four  common  arithmetic  operators  and  a  precedence  table,  showing  the 
operators  in  order  of  increasing  precedence.  Operators  on  the  same  line  have 
t he  same  associativity  and  precedence: 

left-associative: 
left-associative: 

+  -
*  / 

We  create  two  nonterminals  expr  and  term  for  the  two  levels  of  precedence, 
and  an  extra  nonterminal  factor  for  generating  basic  units  in  expressions.  T he 
basic  units  in  expressions  are  presently  digits  and  parenthesized  expressions. 

factor  —> 

digit 

| 

(  expr) 

Now  consider  the  binary  operators,  *  and  /,  t h at  have  t he  highest  prece 
dence.  Since  these  operators  associate  to  the  left,  the  productions  are  similar 
to  those  for  lists  t h at  associate  to  the  left. 

term  —> 

| 
| 

term  *  factor 
term  /  factor 
factor 

Similarly,  expr  generates  lists  of  terms  separated  by  t he  additive  operators. 

expr  —> 
| 
| 

expr  +  term 
expr  - 
term 
term 

T he  resulting  g r a m m ar  is  therefore 

expr 
term 
factor 

-» 
-> 
->• 

expr  +  term 
\ 
term  *  factor 
| 
digit 

| 
(  expr) 

expr  -  term 

\ 
term  /  factor 

term 
| 

factor 

50 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

Generalizing  the  Expression  Grammar  of  Example  2.6 

We  can  think  of  a  factor  as  an  expression  t h at  cannot  be  "torn  a p a r t"  by 
any  operator.  By  "torn  apart,"  we  mean  t h at  placing  an  operator  next 
to  any  factor,  on  either  side,  does  not  cause  any  piece  of  the  factor,  other 
t h an  the  whole,  to  become  an  operand  of  t h at  operator.  If  the  factor  is  a 
parenthesized  expression,  the  parentheses  protect  against  such  "tearing," 
while  if  the  factor  is  a  single  operand,  it  cannot  be  torn  apart. 

A  term  (that  is  not  also  a  factor)  is  an  expression  t h at  can  be  torn 
apart  by  operators  of  the  highest  precedence:  *  and  /,  but  not  by  the 
lower-precedence  operators.  An  expression  (that  is  not  a  t e rm  or  factor) 
can  be  torn  apart  by  any  operator. 

We  can  generalize  this  idea  to  any  number  n  of precedence  levels.  We 
need  n+1  nonterminals.  T he  first,  like  factor  in  Example  2.6,  can  never  be 
torn  apart.  Typically,  the  production  bodies  for  this  nonterminal  are  only 
single  operands  and  parenthesized  expressions.  Then,  for  each  precedence 
level,  there  is  one  nonterminal  representing  expressions  t h at  can  be  torn 
apart  only  by  operators  at  t h at  level  or  higher.  Typically,  t he  productions 
for  this  nonterminal  have  bodies  representing  uses  of t he  operators  at  t h at 
level,  plus  one  body  t h at  is  just  the  nonterminal  for  t he  next  higher  level. 

W i th  this  grammar,  an  expression  is  a  list  of  terms  separated  by  either  +  or 
-  signs,  and  a  t e rm  is  a  list  of  factors  separated  by  *  or  /  signs.  Notice  t h at 
any  parenthesized  expression  is  a  factor,  so  with  parentheses  we  can  develop 
• 
expressions  t h at  have  arbitrarily  deep  nesting  (and  arbitrarily  deep  trees). 

E x a m p le  2 . 7:  Keywords  allow  us  to  recognize  statements,  since  most  state 
ment  begin  with  a  keyword  or  a  special  character.  Exceptions  to  this  rule 
include  assignments  and  procedure  calls.  The  statements  defined  by  the  (am 
biguous)  grammar  in  Fig.  2.8  are  legal  in  Java. 

In  the  first  production  for  stmt,  t he  terminal  id  represents  any  identifier. 
The  productions  for  expression  are  not  shown.  T he  assignment  statements 
specified  by  t he  first  production  are  legal  in  Java,  although  Java  treats  =  as  an 
assignment  operator  t h at  can  appear  within  an  expression.  For  example,  Java 
allows  a = b = c,  which  this  grammar  does  not. 

The  nonterminal  stmts  generates  a  possibly  empty  list  of  statements.  T he 
second  production  for  stmts  generates  the  empty  list  e.  The  first  production 
generates  a  possibly  empty  list  of  statements  followed  by  a  statement. 

T he  placement  of semicolons  is  subtle;  they  appear  at  the  end  of every  body 
t h at  does  not  end  in  stmt.  This  approach  prevents  the  build-up  of  semicolons 
after  statements  such  as  if-  and  while-,  which  end  with  nested  substatements. 
When  the  nested  substatement  is  an  assignment  or  a  do-while,  a  semicolon  will 
be  generated  as  part  of  the  substatement. 

• 

2.2. 

SYNTAX  DEFINITION 

51 

stmt  —>• 

| 
| 
| 
| 
| 

id  =  expression  ; 
if  (  expression  )  s£ra£ 
if  (  expression  )  stmi  e l se  stmt 
w h i le  (  expression  )  sirai 
do  stmt  w h i le  (  expression  ) 
{  stmts  } 

; 

stmts 

->• 

s£m£s  s£ra£ 

Figure  2.8:  A  grammar  for  a  subset  of  Java  statements 

2.2.7  Exercises  for  Section  2.2 

E x e r c i se  2 . 2 . 1:  Consider  t he  context-free  grammar 

S 

-> 

5 5+ 

|  5 5* 

|  a 

a)  Show  how  the  string  aa+a*  can  be  generated  by  this  grammar. 

b)  Construct  a  parse  tree  for  this  string. 

c)  W h at  language  does  this  grammar  generate?  Justify  your  answer. 

E x e r c i se  2 . 2 . 2:  W h at  language  is  generated  by  t he  following  grammars?  In 
each  case  justify  your  answer. 

a)  5 

-4 

0  5  1|  0  1 

b)  5 

-»•  +  55 

| 

- 55 

|  a 

c)  5 

-> 

5 ( 5 )5 

|  e 

d)  5 

-» 

a 5 b5 

|  b  5  a  5 

| 

e 

e)  5 

-> 

a|5  +  5 | 5 5 | 5 * | ( 5) 

E x e r c i se  2 . 2 . 3:  Which  of  the  grammars  in  Exercise  2.2.2  are  ambiguous? 

E x e r c i se  2 . 2 . 4:  Construct  unambiguous  context-free  g r a m m a rs  for  each  of 
the  following  languages.  In  each  case  show  t h at  your  g r a m m ar  is  correct. 

a)  Arithmetic  expressions  in  postfix  notation. 

b)  Left-associative  lists  of  identifiers  separated  by  commas. 

c)  Right-associative  lists  of  identifiers  separated  by  commas. 

d)  Arithmetic  expressions  of  integers  and  identifiers  with  t he  four  binary 

operators  +,  -,  *,  /. 

52 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

!  e)  Add  unary  plus  and  minus  to  t he  arithmetic  operators  of  (d). 

E x e r c i se  2 . 2 . 5: 

a)  Show  t h at  all  binary  strings  generated  by  the  following  g r a m m ar  have 
values  divisible  by  3.  Hint.  Use  induction  on  t he  number  of  nodes  in  a 
parse  tree. 

num 

->• 

11 

|  1001 

|  numO 

|  num  num 

b)  Does  t he  g r a m m ar  generate  all  binary  strings  with  values  divisible  by  3? 

E x e r c i se  2 . 2 . 6:  Construct  a  context-free  grammar  for  roman  numerals. 

2.3  Syntax-Directed  Translation 

Syntax-directed  translation  is  done  by  attaching  rules  or  program  fragments  to 
productions  in  a  grammar.  For  example,  consider  an  expression  expr  generated 
by  the  production 

expr 

-» 

exprx  +  term 

Here,  expr is  the  sum  of the  two  subexpressions  exprx  and  term.  (The  subscript 
in  exprx  is  used  only  to  distinguish  t he  instance  of  expr in  t he  production  body 
from  the  head  of  the  production).  We  can  translate  expr  by  exploiting  its 
structure,  as  in  the  following  pseudo-code: 

translate  exprx; 
translate 
term; 
handle  +; 

Using  a  variant  of  this  pseudocode,  we  shall  build  a  syntax  tree  for  expr  in 
Section  2.8  by  building  syntax  trees  for  exprt  and  term  and  then  handling  +  by 
constructing  a  node  for  it.  For  convenience,  the  example  in  this  section  is  the 
translation  of  infix  expressions  into  postfix  notation. 

This  section  introduces  two  concepts  related  to  syntax-directed  translation: 

•  Attributes.  An  attribute  is  any  quantity  associated  with  a  programming 
construct.  Examples  of attributes  are  d a ta  types  of expressions,  the  num 
ber  of  instructions  in  t he  generated  code,  or  t he  location  of  t he  first  in 
struction  in  the  generated  code  for  a  construct,  among  many  other  pos 
sibilities.  Since  we  use  g r a m m ar  symbols  (nonterminals  and  terminals) 
to  represent  programming  constructs,  we  extend  the  notion  of  attributes 
from  constructs  to  the  symbols  t h at  represent  them. 

2.3. 

SYNTAX-DIRECTED 

TRANSLATION 

53 

• 

(Syntax-directed) 

translation  schemes.  A 

translation  scheme  is  a  notation 

for  attaching  program  fragments  to  the  productions  of  a  grammar.  T he 
program  fragments  are  executed  when  t he  production  is  used  during  syn 
t ax  analysis.  T he  combined  result  of  all  these  fragment  executions,  in 
t he  order  induced  by  t he  syntax  analysis,  produces  t he  translation  of  the 
program  to  which  this  analysis/synthesis  process  is  applied. 

Syntax-directed  translations  will  be  used  throughout  this  chapter  to  trans 
late  infix  expressions  into  postfix  notation,  to  evaluate  expressions,  and  to  build 
syntax  trees  for  programming  constructs.  A  more  detailed  discussion  of  syntax-
directed  formalisms  appears  in  Chapter  5. 

2.3.1  Postfix  Notation 

T he  examples  in  this  section  deal  with  translation  into  postfix  notation.  T he 
postfix  notation  for  an  expression  E  can  be  defined  inductively  as  follows: 

1.  If  E  is  a  variable  or  constant,  then  the  postfix  notation  for  E  is  E  itself. 

2.  If  E  is  an  expression  of  the  form  E\  op  E2,  where  op  is  any  binary 
operator,  then  the  postfix  notation  for  E  is  E[  E'2  o p,  where  E[  and  E'2 
are  the  postfix  notations  for  E\  and  E2,  respectively. 

3.  If  E  is  a  parenthesized  expression  of  the  form  (Ei), 

then  the  postfix 

notation  for  E  is  the  same  as  t he  postfix  notation  for  E\. 

E x a m p le  2.8  :  The  postfix  notation  for  ( 9 - 5 ) +2  is  95-2+.  T h at  is,  t he  trans 
lations  of  9,  5,  and  2  are  the  constants  themselves,  by  rule  (1).  Then,  t he 
translation  of  9-5  is  9 5-  by  rule  (2).  The  translation  of  ( 9 - 5)  is  t he  same 
by  rule  (3).  Having  translated  the  parenthesized  subexpression,  we  may  apply 
rule  (2)  to  the  entire  expression,  with  ( 9 - 5)  in  t he  role  of  E\  and  2  in  the  role 
of  E2:  to  get  the  result  95-2+. 

As  another  example,  the  postfix  notation  for  9- (5+2)  is  952+-.  T h at  is,  5+2 
is  first  translated  into  52+,  and  this  expression  becomes  the  second  argument 
of  t he  minus  sign. 

• 

No  parentheses  are  needed  in  postfix  notation,  because  t he  position  and 
arity  (number  of  arguments)  of  the  operators  permits  only  one  decoding  of  a 
postfix  expression.  T he  "trick"  is  to  repeatedly  scan  the  postfix  string  from  the 
left,  until  you  find  an  operator.  Then,  look  to  the  left  for  t he  proper  number 
of  operands,  and  group  this  operator  with  its  operands.  Evaluate  the  operator 
on  t he  operands,  and  replace  t h em  by  the  result.  Then  repeat  t he  process, 
continuing  to  the  right  and  searching  for  another  operator. 

E x a m p le  2 . 9:  Consider  the  postfix  expression  952+-3*.  Scanning  from  t he 
left,  we  first  encounter  the  plus  sign.  Looking  to  its  left  we  find  operands  5  and 
2.  Their  sum,  7,  replaces  52+,  and  we  have  t he  string  9 7 - 3 *.  Now,  t he  leftmost 

54 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

operator  is  the  minus  sign,  and  its  operands  are  9  and  7.  Replacing  these  by 
the  result  of the  subtraction  leaves  23*.  Last,  the  multiplication  sign  applies  to 
2  and  3,  giving  the  result  6. 

• 

2.3.2  Synthesized  Attributes 

T he  idea  of  associating  quantities  with  programming  constructs—for  example, 
values  and  types  with  expressions—can  be  expressed  in  terms  of g r a m m a r s.  We 
associate  attributes  with  nonterminals  and  terminals.  Then,  we  a t t a ch  rules  to 
the  productions  of  t he  grammar;  these  rules  describe  how  the  attributes  are 
computed  at  those  nodes  of  the  parse  tree  where  the  production  in  question  is 
used  to  relate  a  node  to  its  children. 

A 

syntax-directed  definition  associates 

1.  W i th  each  g r a m m ar  symbol,  a  set  of  attributes,  and 

2.  W i th  each  production,  a  set  of  semantic  rules  for  computing  t he  values  of 
t he  attributes  associated  with  t he  symbols  appearing  in  the  production. 

Attributes  can  be  evaluated  as  follows.  For  a  given  input  string  x,  construct 
a  parse  tree  for  x.  Then,  apply  the  semantic  rules  to  evaluate  a t t r i b u t es  at  each 
node  in  the  parse  tree,  as  follows. 

Suppose  a  node  A?"  in  a  parse  tree  is  labeled  by  the  g r a m m ar  symbol  X.  We 
write  X.a  to  denote  t he  value  of  a t t r i b u te  a  of  X  at  t h at  node.  A  parse  tree 
showing  the  a t t r i b u te  values  at  each  node  is  called  an  annotated  parse  tree.  For 
example,  Fig.  2.9  shows  an  annotated  parse  tree  for  9-5+2  with  an  a t t r i b u te 
t  associated  with  t he  nonterminals  expr  and  term.  T he  value  95-2+  of  the 
a t t r i b u te  at  the  root  is  t he  postfix  notation  for  9-5+2.  We  shall  see  shortly  how 
these  expressions  are  computed. 

expr.t  =  95-2+ 

expr.t  =  95' 

+ 

term.t  =  2 

expr.t  =  9 

term.t  =  5 

2 

term.t  =  9 

5 

9 

Figure  2.9:  Attribute  values  at  nodes  in  a  parse  tree 

An  a t t r i b u te  is  said  to  be  synthesized if its  value  at  a  parse-tree  node  N  is  de 
termined  from  a t t r i b u te  values  at  t he  children  of  N  and  at  N  itself.  Synthesized 

2.3. 

SYNTAX-DIRECTED 

TRANSLATION 

55 

attributes  have  the  desirable  property  t h at  they  can  be  evaluated  during  a  sin 
gle b o t t o m - up  traversal of a parse tree.  In  Section  5.1.1  we shall  discuss  another 
important  kind  of attribute:  the  "inherited"  a t t r i b u t e.  Informally,  inherited  at 
tributes  have  their  value  at  a  parse-tree  node  determined  from  a t t r i b u te  values 
at  t he  node  itself,  its  parent,  and  its  siblings  in  the  parse  tree. 

E x a m p le  2 . 1 0:  T he  annotated  parse  tree  in  Fig.  2 .9  is  based  on  t he  syntax-
directed  definition  in  Fig.  2 . 10  for  translating  expressions  consisting  of  digits 
separated  by  plus  or  minus  signs  into  postfix  notation.  Each  nonterminal  has  a 
string-valued  a t t r i b u te  t  t h at  represents  the  postfix  notation  for  t he  expression 
generated  by  t h at  nonterminal  in  a  parse  tree.  T he  symbol  ||  in  t he  semantic 
rule  is  the  operator  for  string  concatenation. 

P R O D U C T I ON 

S E M A N T IC  R U L ES 

expr —>  exprx  +  term 

expr.t  =  exprx.t  ||  term.t  ||  '+' 

expr  —>  exprx  -  term 

expr.t  = 

exprx.t  ||  term.t  ||  '-' 

expr  -> 

term 

expr.t  = 

term.t 

term  -»  0 

term  ->  1 

term.t  = 

' 0' 

term.t  = 

' 1' 

term —)• 9 

term.t  — 

' 9' 

Figure  2 . 1 0:  Syntax-directed  definition  for  infix  to  postfix  translation 

T he  postfix  form  of  a  digit  is  the  digit  itself;  e.g.,  t he  semantic  rule  associ 
ated  with  t he  production  term  -»  9  defines  term.t  to  be  9  itself  whenever  this 
production  is  used  at  a  node  in  a  parse  tree.  The  other  digits  are  translated 
similarly.  As  another  example,  when  t he  production  expr 
term  is  applied, 
the  value  of  term.t  becomes  the  value  of  expr.t. 

T he  production  expr —>  exprx  +  term derives  an  expression  containing  a plus 

o p e r a t o r .3  T he  left  operand  of the  plus  operator  is  given  by  exprx  and  the  right 
operand  by  term.  T he  semantic  rule 

expr.t  =  expr.t  \\  term.t  \\  '+' 

associated  with  this  production  constructs  the  value  of  a t t r i b u te  expr.t  by  con 
catenating  the  postfix  forms  expr.t  and  term.t  of  the  left  and  right  operands, 
respectively,  and  then  appending  the  plus  sign.  This  rule  is  a  formalization  of 
t he  definition  of  "postfix  expression." 

• 

3In  this  and  many  other  rules,  the  same  nonterminal  (expr,  here)  appears  several  times. 
The  purpose  of  the  subscript  1  in  exprx  is  to  distinguish  the  two  occurrences  of  expr  in  the 
production;  the  " 1"  is not  part  of the nonterminal.  See the box on  "Convention Distinguishing 
Uses  of  a  Nonterminal"  for  more  details. 

56 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

Convention  Distinguishing  Uses  of  a  Nonterminal 

In  rules,  we  often  have  a  need  to  distinguish  among  several  uses  of  t he 
same  nonterminal  in  the  head  a n d / or  body  of  a  production;  e.g.,  see  Ex 
ample  2.10.  T he  reason  is  t h at  in  t he  parse  tree,  different  nodes  labeled 
by  the  same  nonterminal  usually  have  different  values  for  their  transla 
tions.  We  shall  adopt  the  following  convention:  t he  nonterminal  appears 
unsubscripted  in  the  head  and  with  distinct  subscripts  in  t he  body.  These 
are  all  occurrences  of the  same  nonterminal,  and  t he  subscript  is  not  part 
of  its  name.  However,  the  reader  should  be  alert  to  t he  difference  be 
tween  examples  of specific  translations,  where  this  convention  is  used,  and 
generic  productions  like  A  —>  X1X2,  •  •  •  ,Xn,  where  t he  subscripted  X 's 
represent  an  arbitrary  list  of  grammar  symbols,  and  are  not  instances  of 
one  particular  nonterminal  called  X. 

2.3.3 

Simple  Syntax-Directed  Definitions 

The  syntax-directed  definition  in  Example  2.10  has  the  following  important 
property:  the  string  representing  the  translation  of the  nonterminal  at  the  head 
of  each  production  is  t he  concatenation  of  the  translations  of  the  nonterminals 
in  the  production  body,  in  the  same  order  as  in  t he  production,  with  some 
optional  additional  strings  interleaved.  A  syntax-directed  definition  with  this 
property  is  termed  simple. 

E x a m p le  2 . 1 1:  Consider  the  first  production  and  semantic  rule  from  Fig.  2.10: 

P R O D U C T I ON 

S E M A N T IC  R U LE 

expr^r  exprx  + 

term 

expr.t 

=  exprx.t  ||  term.t  ||  '+' 

(2.5) 

Here  t he  translation  expr.t  is  t he  concatenation  of  t he  translations  of  exprx  and 
term,  followed  by  t he  symbol  +.  Notice  t h at  expr\  and  term  appear  in  the 
same  order  in  b o th  the  production  body  and  t he  semantic  rule.  There  are  no 
additional  symbols  before  or  between  their  translations.  In  this  example,  t he 
only  extra  symbol  occurs  at  t he  end. 

• 

W h en  translation  schemes  are  discussed,  we  shall  see  t h at  a  simple  syntax-
directed  definition  can  be  implemented  by  printing  only  the  additional  strings, 
in  t he  order  they  appear  in  the  definition. 

2.3.4  Tree  Traversals 

Tree  traversals  will  be  used  for  describing  a t t r i b u te  evaluation  and  for  specifying 
t he  execution  of  code  fragments  in  a  translation  scheme.  A  traversal  of  a  tree 
starts  at  t he  root  and  visits  each  node  of t he  tree  in  some  order. 

2.3. 

SYNTAX-DIRECTED 

TRANSLATION 

57 

A  depth-first  traversal  starts  at  the  root  and  recursively  visits  t he  children 
of each  node  in  any  order,  not  necessarily  from  left  to  right.  It  is  called  "depth-
first"  because  it  visits  an  unvisited  child  of  a  node  whenever  it  can,  so  it  visits 
nodes  as  far  away  from  t he  root  (as  "deep")  as  quickly  as  it  can. 

T he  procedure  visit(N)  in  Fig.  2.11  is  a  depth  first  traversal  t h at  visits  the 
children  of a  node  in  left-to-right  order,  as  shown  in  Fig.  2.12.  In  this  traversal, 
we  have  included  t he  action  of  evaluating  translations  at  each  node,  just  before 
we  finish  with  t he  node  (that  is,  after  translations  at  t he  children  have  surely 
In  general,  the  actions  associated  with  a  traversal  can  be 
been  computed). 
whatever  we  choose,  or  nothing  at  all. 

p r o c e d u re  visit (node  N)  { 

for  (  each  child  C  of  N,  from  left  to  right  )  { 

visit  (C); 

} 
evaluate  semantic  rules  at  node  N; 

} 

Figure  2.11:  A  depth-first  traversal  of  a  tree 

Figure  2.12:  Example  of  a  depth-first  traversal  of  a  tree 

A  syntax-directed  definition  does  not  impose  any  specific  order  for  the  eval 
uation  of  attributes  on  a  parse  tree;  any  evaluation  order  t h at  computes  an 
a t t r i b u te  a  after  all  the  other  attributes  t h at  a  depends  on  is  acceptable.  Syn 
thesized  attributes  can  be  evaluated  during  any  bottom-up  traversal,  t h at  is,  a 
traversal  t h at  evaluates  attributes  at  a  node  after  having  evaluated  attributes 
at  its  children.  In  general,  with  both  synthesized  and  inherited  attributes,  t he 
m a t t er  of  evaluation  order  is  quite  complex;  see  Section  5.2. 

2.3.5  Translation  Schemes 

T he  syntax-directed  definition  in  Fig.  2.10  builds  up  a  translation  by  attaching 
strings  as  attributes  to  the  nodes  in  the  parse  tree.  We  now  consider  an  alter 
native  approach  t h at  does  not  need  to  manipulate  strings;  it  produces  t he  same 
translation  incrementally,  by  executing  program  fragments. 

58 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

Preorder  and  Postorder  Traversals 

Preorder  and  postorder  traversals  are  two  important  special  cases  of depth-
first  traversals  in  which  we  visit  t he  children  of each  node  from  left  to  right. 
Often,  we  traverse  a  tree  to  perform  some  particular  action  at  each 
node.  If  the  action  is  done  when  we  first  visit  a  node,  then  we  may  refer 
to  the  traversal  as  a  preorder  traversal.  Similarly,  if  the  action  is  done 
just  before  we  leave  a  node  for  the  last  time,  then  we  say  it  is  a  postorder 
traversal  of  t he  tree.  T he  procedure  visit(N)  in  Fig.  2.11  is  an  example  of 
a  postorder  traversal. 

Preorder  and  postorder  traversals  define  corresponding  orderings  on 
nodes,  based  on  when  t he  action  at  a  node  would  be  performed.  T he 
preorder  of  a  (sub)tree  rooted  at  node  JV  consists  of  N,  followed  by  t he 
preorders  of  t he  subtrees  of  each  of  its  children,  if  any,  from  the  left.  T he 
postorder  of  a  (sub)tree  rooted  at  TV"  consists  of  the  postorders  of  each  of 
the  subtrees  for  the  children  of  N,  if  any,  from  t he  left,  followed  by  N 
itself. 

A  syntax-directed  translation  scheme  is  a  notation  for  specifying  a  transla 
tion  by  attaching  program  fragments  to  productions  in  a  grammar.  A  transla 
tion  scheme  is  like  a  syntax-directed  definition,  except  t h at  t he  order  of  evalu 
ation  of  t he  semantic  rules  is  explicitly  specified. 

Program  fragments  embedded  within  production  bodies  are  called  semantic 
actions.  T he  position  at  which  an  action  is  to  be  executed  is  shown  by  enclosing 
it  between  curly  braces  and  writing  it  within  the  production  body,  as  in 

rest  —>  +  term  {print('+')}  rest\ 

We  shall  see  such  rules  when  we  consider  an  alternative  form  of  g r a m m ar  for 
expressions,  where  the  nonterminal  rest  represents  "everything  but  the  first 
term  of  an  expression."  This  form  of  grammar  is  discussed  in  Section  2.4.5. 
Again,  the  subscript  in  rest\  distinguishes  this  instance  of  nonterminal  rest  in 
the  production  body  from  t he  instance  of  rest  at  the  head  of  t he  production. 

W h en  drawing  a  parse  tree  for  a  translation  scheme,  we  indicate  an  action 
by  constructing  an  extra  child  for  it,  connected  by  a  dashed  line  to  the  node 
t h at  corresponds  to  the  head  of  t he  production.  For  example,  the  portion  of 
the  parse  tree  for  the  above  production  and  action  is  shown  in  Fig.  2.13.  T he 
node  for  a  semantic  action  has  no  children,  so  t he  action  is  performed  when 
t h at  node  is  first  seen. 

E x a m p le  2 . 1 2:  The  parse  tree  in  Fig.  2.14  has  print  statements  at  extra 
leaves,  which  are  attached  by  dashed  lines  to  interior  nodes  of  t he  parse  tree. 
T he  translation  scheme  appears  in  Fig.  2.15.  T he  underlying  grammar  gen 
erates  expressions  consisting  of  digits  separated  by  plus  and  minus  signs.  T he 

2.3. 

SYNTAX-DIRECTED 

TRANSLATION 

59 

rest 

^^^^^^^ 

+ 

term 

{print ('+')} 

resh 

Figure  2.13:  An  extra  leaf  is  constructed  for  a  semantic  action 

actions  embedded  in  the  production  bodies  translate  such  expressions  into  post 
fix  notation,  provided  we  perform  a  left-to-right  depth-first  traversal  of t he  tree 
and  execute  each  print  statement  when  we  visit  its  leaf. 

expr  . 

term 
\, 
/ 
2  {print 

{print ('+')} 

('2')} 

expr 

- 

term 

{print 

('-')} 

5 

{print ('5')} 

term 

/  \ 

9  {print 

('9')} 

Figure  2.14:  Actions  translating  9-5+2  into  95-2+ 

expr 
expr 
expr 
term 
term 

-¥ 
-> 

-¥ 
-t 
-» 

exprx  + 
exprx 
- 
term 
0 
1 

term 
term 

{print('+')} 
{print  ('-')} 

{printCO')} 
{ p r i n t ( T )} 

term 

-> 

9 

{print('9')} 

Figure  2.15:  Actions  for  translating  into  postfix  notation 

The  root  of  Fig.  2.14  represents  t he  first  production  in  Fig.  2.15. 

In  a 
postorder  traversal,  we  first  perform  all  the  actions  in  the  leftmost  subtree  of 
the  root,  for  the  left  operand,  also  labeled  expr  like  the  root.  We  then  visit  t he 
leaf  +  at  which  there  is  no  action.  We  next  perform  the  actions  in  t he  subtree 
for  t he  right  operand  term  and,  finally,  the  semantic  action  {  print('+')  }  at  t he 
extra  node. 

Since  the  productions  for  term  have  only  a  digit  on  the  right  side,  t h at  digit 
is  printed  by  t he  actions  for  the  productions.  No  output  is  necessary  for  the 
term,  and  only  the  operator  needs  to  be  printed  in  t he 
production  expr  -> 

60 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

action  for  each  of the  first  two  productions.  When  executed  during  a  postorder 
traversal  of  the  parse  tree,  t he  actions  in  Fig.  2.14  print  95-2+. 

• 

Note  t h at  although  the  schemes  in  Fig.  2.10  and  Fig.  2.15  produce  the  same 
translation,  they  construct  it  differently;  Fig.  2.10  attaches  strings  as  attributes 
to the  nodes  in the  parse tree,  while  the  scheme in  Fig.  2.15  prints t he translation 
incrementally,  through  semantic  actions. 

The  semantic  actions  in  t he  parse  tree  in  Fig.  2.14  translate  the  infix  ex 
pression  9-5+2  into  95-2+  by  printing  each  character  in  9-5+2  exactly  once, 
without  using  any  storage  for  t he  translation  of  subexpressions.  When  the  out 
put  is  created  incrementally  in  this  fashion,  the  order  in  which  the  characters 
are  printed  is  significant. 

The  implementation  of  a  translation  scheme  must  ensure  t h at  semantic  ac 
tions  are  performed  in  the  order  they  would  appear  during  a  postorder  traversal 
of  a  parse  tree.  The  implementation  need  not  actually  construct  a  parse  tree 
(often  it  does  not),  as  long  as  it  ensures  t h at  the  semantic  actions  are  per 
formed  as  if  we  constructed  a  parse  tree  and  then  executed  t he  actions  during 
a  postorder  traversal. 

2.3.6  Exercises  for  Section  2.3 

E x e r c i se  2 . 3 . 1:  Construct  a  syntax-directed  translation  scheme  t h at  trans 
lates  arithmetic  expressions  from  infix  notation  into  prefix  notation  in  which  an 
operator  appears  before  its  operands;  e.g.,  —xy  is  the  prefix  notation  for  x  —  y. 
Give  annotated  parse  trees  for  t he  inputs  9-5+2  and  9-5*2. 

E x e r c i se  2 . 3 . 2:  Construct  a  syntax-directed  translation  scheme  t h at  trans 
lates  arithmetic  expressions  from  postfix  notation  into  infix  notation.  Give 
annotated  parse  trees  for  the  inputs  9 5 - 2*  and  9 5 2 * -. 

E x e r c i se  2 . 3 . 3:  Construct  a  syntax-directed  translation  scheme  t h at  t r a n s 
lates  integers  into  roman  numerals. 

E x e r c i se  2 . 3 . 4:  Construct  a  syntax-directed  translation  scheme  t h at  trans 
lates  roman  numerals  into  integers. 

E x e r c i se  2 . 3 . 5:  Construct  a  syntax-directed  translation  scheme  t h at  t r a n s 
lates  postfix  arithmetic  expressions  into  equivalent  infix  arithmetic  expressions. 

2.4  Parsing 

Parsing  is  the  process  of  determining  how  a  string  of terminals  can  be  generated 
by  a  grammar.  In  discussing  this  problem,  it  is  helpful  to  think  of  a  parse  tree 
being  constructed,  even  though  a  compiler  may  not  construct  one,  in  practice. 
However,  a  parser  must  be  capable  of  constructing  t he  tree  in  principle,  or  else 
t he  translation  cannot  be  guaranteed  correct. 

2.4. 

PARSING 

61 

This  section  introduces  a  parsing  method  called  "recursive  descent,"  which 

can  be  used  b o th  to  parse  and  to  implement  syntax-directed  translators.  A  com 
plete  Java  program,  implementing  t he  translation  scheme  of  Fig.  2.15,  appears 
in  t he  next  section.  A  viable  alternative  is  to  use  a  software  tool  to  generate 
a  translator  directly  from  a  translation  scheme.  Section  4.9  describes  such  a 
tool  —  Yacc;  it  can  implement  the  translation  scheme  of  Fig.  2.15  without 
modification. 

For  any  context-free  grammar  there  is  a  parser  t h at  takes  at  most  0 ( n3) 
time  to  parse  a  string  of  n  terminals.  But  cubic  time  is  generally  too  expen 
sive.  Fortunately,  for  real  programming  languages,  we  can  generally  design  a 
grammar  t h at  can  be  parsed  quickly.  Linear-time  algorithms  suffice  to  parse 
essentially  all  languages  t h at  arise  in  practice.  Programming-language  parsers 
almost  always  make  a  single  left-to-right  scan  over  t he  input,  looking  ahead  one 
terminal  at  a  time,  and  constructing  pieces  of  the  parse  tree  as  they  go. 

Most  parsing  methods  fall  into  one  of  two  classes,  called  the  top-down  and 
bottom-up  methods.  These  terms  refer  to  the  order  in  which  nodes  in  the  parse 
tree  are  constructed.  In  top-down  parsers,  construction  starts  at  t he  root  and 
proceeds  towards  the  leaves,  while  in  bottom-up  parsers,  construction  starts  at 
the  leaves  and  proceeds  towards  the  root.  T he  popularity  of  top-down  parsers 
is  due  to  the  fact  t h at  efficient  parsers  can  be  constructed  more  easily  by  hand 
using  top-down  methods.  Bottom-up  parsing,  however,  can  handle  a larger  class 
of  grammars  and  translation  schemes,  so  software  tools  for  generating  parsers 
directly  from  grammars  often  use  bottom-up  methods. 

2.4.1  Top-Down  Parsing 

We  introduce  top-down  parsing  by  considering  a  grammar  t h at  is  well-suited 
for  this  class  of  methods.  Later  in  this  section,  we  consider  t he  construction 
of  top-down  parsers  in  general.  T he  grammar  in  Fig.  2.16  generates  a  subset 
of  t he  statements  of  C  or  Java.  We  use  t he  boldface  terminals  if  and  for  for 
the  keywords  "if"  and  " f o r ",  respectively,  to  emphasize  t h at  these  character 
sequences  are  treated  as  units,  i.e.,  as  single  terminal  symbols.  Further,  the 
terminal  e x pr  represents  expressions;  a  more  complete  grammar  would  use  a 
nonterminal  expr  and  have  productions  for  nonterminal  expr.  Similarly,  o t h er 
is  a  terminal  representing  other  statement  constructs. 

T he  top-down  construction  of  a  parse  tree  like  t he  one  in  Fig.  2.17,  is  done 
by  starting  with  the  root,  labeled  with  the  starting  nonterminal  stmt,  and  re 
peatedly  performing  the  following  two  steps. 

1.  At  node  JV,  labeled  with  nonterminal  A,  select  one  of  the  productions  for 
A  and  construct  children  at  N  for  the  symbols  in  the  production  body. 

2.  Find  t he  next  node  at  which  a  subtree  is  to  be  constructed,  typically  the 

leftmost  unexpanded  nonterminal  of  the  tree. 

For  some  grammars,  the  above  steps  can  be  implemented  during  a  single 
left-to-right  scan  of t he  input  string.  T he  current  terminal  being  scanned  in  t he 

62 

CHAPTER 

2.  A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

stmt  —y 

e x pr  ; 
if  (  e x pr  )  stmt 
for  (  optexpr  ;  optexpr  ;  optexpr  )  stmt 
o t h er 

optexpr  —> 

e 
e x pr 

Figure  2.16:  A  grammar  for  some  statements  in  C  and  Java 

stmt 

for 

e 

expr 

expr 

stmt 

other 

Figure  2.17:  A  parse  tree  according  to  t he  grammar  in  Fig.  2.16 

input  is  frequently  referred  to  as  the  lookahead  symbol.  Initially,  t he  lookahead 
symbol  is  t he  first,  i.e.,  leftmost,  terminal  of  the  input  string.  Figure  2.18 
illustrates  the  construction  of  the  parse  tree  in  Fig.  2.17  for  t he  input  string 

for  (  ;  e x pr  ;  e x pr  )  o t h er 

Initially,  the  terminal  for  is  the  lookahead  symbol,  and  the  known  part  of  the 
parse  tree  consists  of  the  root,  labeled  with  the  starting  nonterminal  stmt  in 
Fig.  2.18(a).  The  objective  is  to  construct  the  remainder  of  the  parse  tree  in 
such  a  way  t h at  t he  string  generated  by  the  parse  tree  matches  t he  input  string. 
For  a  match  to  occur,  the  nonterminal  stmt  in  Fig.  2.18(a)  must  derive  a 
string  t h at  starts  with  the  lookahead  symbol  for.  In  the  g r a m m ar  of  Fig.  2.16, 
there  is  just  one  production  for  stmt that  can  derive  such  a  string,  so  we  select  it, 
and  construct  the  children  of the  root  labeled  with  the  symbols  in  the  production 
body.  This  expansion  of  the  parse  tree  is  shown  in  Fig.  2.18(b). 

Each  of  the  three  snapshots  in  Fig.  2.18  has  arrows  marking  t he  lookahead 
symbol  in  the  input  and  the  node  in  the  parse  tree  t h at  is  being  considered. 
Once  children  are  constructed  at  a  node,  we  next  consider  the  leftmost  child.  In 
Fig.  2.18(b),  children  have  just  been  constructed  at  t he  root,  and  the  leftmost 
child  labeled  with  for  is  being  considered. 

When  the  node  being  considered  in  the  parse  tree  is  for  a  terminal,  and 
the  terminal  matches  the  lookahead  symbol,  then  we  advance  in  b o th  the  parse 
tree  and  the  input.  T he  next  terminal  in  the  input  becomes  the  new  lookahead 
symbol,  and  t he  next  child  in  t he  parse  tree  is  considered.  In  Fig.  2.18(c),  t he 
arrow  in  t he  parse  tree  has  advanced  to  t he  next  child  of the  root,  and  t he  arrow 

2.4.  PARSING 

63 

P A R SE 
T R EE 

(a)  — 

stmt 

I N P UT 

f or 

( 

; 

e x pr 

; 

e x pr 

) 

o t h er 

Figure  2.18:  Top-down  parsing  while  scanning  the  input  from  left  to  right 

in  t he  input  has  advanced  to  the  next  terminal,  which  is  (.  A  further  advance 
will  take  t he  arrow  in  the  parse  tree  to  the  child  labeled  with  nonterminal 
optexpr  a nd  take  t he  arrow  in  the  input  to  t he  terminal  ;. 

At  the  nonterminal  node  labeled  optexpr,  we  repeat  the  process  of selecting  a 
production  for  a  nonterminal.  Productions  with  e  as  t he  body  ("e-productions") 
require  special  treatment.  For  the  moment,  we  use  them  as  a  default  when 
no  other  production  can  be  used;  we  return  to  them  in  Section  2.4.3.  W i th 
nonterminal  optexpr  and  lookahead 
;  does 
not  m a t ch  t he  only  other  production  for  optexpr,  which  has  terminal  e x pr  as 
its  body. 

;,  the  e-production  is  used,  since 

In  general,  the  selection  of  a  production  for  a  nonterminal  may  involve  trial-
and-error;  t h at  is,  we  may  have  to  try  a  production  and  backtrack to  try  another 
production  if  the  first  is  found  to  be  unsuitable.  A  production  is  unsuitable 
if,  after  using  t he  production,  we  cannot  complete  t he  tree  to  match  t he  input 

64 

CHAPTER  2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

string.  Backtracking is  not  needed,  however,  in  an  important  special  case  called 
predictive  parsing,  which  we  discuss  next. 

2.4.2 

Predictive  Parsing 

Recursive-descent  parsing  is  a  top-down  method  of  syntax  analysis  in  which 
a  set  of  recursive  procedures  is  used  to  process  the  input.  One  procedure  is 
associated with  each  nonterminal  of a grammar.  Here,  we  consider  a  simple  form 
of  recursive-descent  parsing,  called  predictive  parsing,  in  which  the  lookahead 
symbol  unambiguously  determines  the  flow  of  control  through  the  procedure 
body  for  each  nonterminal.  T he  sequence  of procedure  calls  during  the  analysis 
of  an  input  string  implicitly  defines  a  parse  tree  for  the  input,  and  can  be  used 
to  build  an  explicit  parse  tree,  if  desired. 

The  predictive  parser  in  Fig.  2 . 19  consists  of  procedures  for  the  nontermi 
nals  stmt  and  optexpr  of the  grammar  in  Fig.  2 . 16  and  an  additional  procedure 
match,  used  to  simplify  the  code  for  stmt  and  optexpr.  Procedure  match(t)  com 
pares  its  argument  t  with  the  lookahead  symbol  and  advances  to  the  next  input 
terminal  if  they  match.  Thus  match  changes  the  value  of  variable  lookahead,  a 
global  variable  t h at  holds  the  currently  scanned  input  terminal. 

Parsing  begins  with  a  call  of the  procedure  for  the  starting  nonterminal  stmt. 

With  the  same  input  as  in  Fig.  2 . 1 8,  lookahead is  initially  the  first  terminal  for. 
Procedure  stmt  executes  code  corresponding  to  the  production 

stmt  ->•  for  (  optexpr  ;  optexpr  ;  optexpr  )  stmt 

In  the  code  for  the  production  body  —  t h at  is,  the  for  case  of procedure  stmt — 
each  terminal  is  matched  with  the  lookahead  symbol,  and  each  nonterminal 
leads  to  a  call  of  its  procedure,  in  the  following  sequence  of  calls: 

match(for); 
optexprQ; 
match(')'); 

matched); 

match(';'); 
stmtQ; 

optexprQ; 

match(';'); 

optexprQ; 

Predictive  parsing  relies  on  information  about  the  first  symbols  t h at  can  be 
generated  by  a  production  body.  More  precisely,  let  a  be  a  string  of  g r a m m ar 
symbols  (terrninals  a n d / or  nonterminals).  We  define  F I R S T( a)  to  be  the  set  of 
terminals  t h at  appear  as  the  first  symbols  of  one  or  more  strings  of  terminals 
generated  from  a.  If  a  is  e  or  can  generate  e,  then  e  is  also  in  F I R ST  (a). 

The  details  of  how  one  computes  F I R S T( o ;)  are  in  Section  4 . 4 . 2.  Here,  we 
shall  just  use  ad  hoc  reasoning  to  deduce  the  symbols  in  F I R ST  ( a );  typically,  a 
will  either  begin  with  a  terminal,  which  is  therefore  the  only  symbol  in  F I R S T ( Q ; ), 
or  a  will  begin  with  a  nonterminal  whose  production  bodies  begin  with  termi 
nals,  in  which  case these  terminals  are  the  only  members  of F I R S T( a ). 

For  example,  with  respect  to  the  grammar  of  Fig.  2 . 1 6,  the  following  are 

correct  calculations  of  F I R S T. 

2.4. 

PARSING 

65 

void  stmt()  { 

switch  (  lookahead  )  { 
case  expr: 

match(expr); 

match(';'); 

break; 

case  if: 

match(it);  match('  (');  match  (expr);  match(')'); 
break; 

stmtQ; 

case  for: 

match(for);  match('  ('); 
optexprQ;  match(';'); 
match(')'); 

stmtQ;  break; 

optexpr();  match(';'); 

optexprQ; 

case  other; 

match (other);  break; 

default: 

report ( " s y n t ax 

e r r o r " ); 

} 

} 

void  optexpr()  { 
if  ( 

lookahead  ==  e x pr  )  match(expr); 

} 

void  match (terminal  £)  { 

if  (  lookahead  ==  £  )  lookahead  —  next  Terminal; 
else  report ( " s y n t ax  e r r o r " ); 

} 

Figure  2.19:  Pseudocode  for  a  predictive  parser 

FIRST(stmt) 
FIRST(expr  ;) 

= 
= 

{ e x p r,  if,  for,  o t h e r} 
{ e x p r} 

T he  FIRST  sets  must  be  considered  if  there  are  two  productions  A  -»  a  and 
A  —>  0. 
Ignoring  e-productions  for  the  moment,  predictive  parsing  requires 
FlRST(a)  and  FIRST(/3)  to  be  disjoint.  T he  lookahead  symbol  can  t h en  be  used 
to  decide  which  production  to  use;  if the  lookahead  symbol  is  in  F I R S T ( O J),  then 
a  is  used.  Otherwise,  if  the  lookahead  symbol  is  in  FIRST(/3),  then  0  is  used. 

2.4.3  When  to  Use  e-Productions 

Our  predictive  parser  uses  an  e-production  as  a  default  when  no  other  produc 
tion  can  be  used.  W i th  the  input  of  Fig.  2.18,  after  the  terminals  for  and  (  are 
matched,  t he  lookahead  symbol  is  ;.  At  this  point  procedure  optexpr  is  called, 
and  t he  code 

66 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

if  (  lookahead  ===  e x pr  )  match (expr); 

in  its  body  is  executed.  Nonterminal  optexpr  has  two  productions,  with  bodies 
e x pr  and  e.  The  lookahead  symbol  " ;"  does  not  match  t he  terminal  e x p r,  so 
the  production  with  body  e x pr  cannot  apply. 
In  fact,  t he  procedure  returns 
without  changing  the  lookahead  symbol  or  doing  anything  else.  Doing  nothing 
corresponds  to  applying  an  e-production. 

More  generally,  consider  a  variant  of  the  productions  in  Fig.  2.16  where 

optexpr  generates  an  expression  nonterminal  instead  of  the  terminal  expr: 

optexpr  —>• 
I 

expr 
e 

Thus,  optexpr  either  generates  an  expression  using  nonterminal  expr  or  it  gen 
erates  e.  While  parsing  optexpr,  if  the  lookahead  symbol  is  not  in  FIRST  (espr), 
then  the  e-production  is  used. 

For  more  on  when to  use  e-productions,  see  the  discussion  of LL(1)  grammars 

in  Section  4.4.3. 

2.4.4  Designing  a  Predictive  Parser 

We  can  generalize  the  technique  introduced  informally  in  Section  2.4.2,  to  apply 
to  any g r a m m ar t h at  has  disjoint  FIRST  sets  for  the  production  bodies  belonging 
to  any nonterminal.  We  shall  also  see t h at  when  we  have  a translation  scheme — 
t h at  is,  a  grammar  with  embedded  actions  —  it  is  possible  to  execute  those 
actions  as  part  of  the  procedures  designed  for  the  parser. 

Recall  t h at  a  predictive  parser  is  a  program  consisting  of  a  procedure  for 

every  nonterminal.  The  procedure  for  nonterminal  A  does  two  things. 

1.  It  decides  which  A-production  to  use  by  examining  t he  lookahead  symbol. 
T he  production  with  body  a  (where  a  is  not  e,  the  empty  string)  is  used 
if  the  lookahead  symbol  is  in  F i R S T ( a ). 
If  there  is  a  conflict  between 
two  nonempty  bodies  for  any  lookahead  symbol,  then  we  cannot  use  this 
parsing  method  on  this  grammar.  In  addition,  t he  e-production  for  A,  if 
it  exists,  is  used  if  t he  lookahead  symbol  is  not  in  t he  FIRST  set  for  any 
other  production  body  for  A. 

2.  T he  procedure  then  mimics  t he  body  of  t he  chosen  production.  T h at 
is,  the  symbols  of  the  body  are  "executed"  in  t u r n,  from  the  left.  A 
nonterminal  is  "executed"  by  a  call  to  t he  procedure  for  t h at  nonterminal, 
and  a  terminal  matching  the  lookahead  symbol  is  "executed"  by  reading 
If  at  some  point  the  terminal  in  t he  body  does 
the  next  input  symbol. 
not  match  t he  lookahead  symbol,  a  syntax  error  is  reported. 

Figure  2.19  is  t he  result  of  applying  these  rules  to  the  grammar  in  Fig.  2.16. 

2.4. 

PARSING 

67 

Just  as  a  translation  scheme  is  formed  by  extending  a  grammar,  a  syntax-
directed  translator  can  be  formed  by  extending  a  predictive  parser.  An  algo 
rithm  for  this  purpose  is  given  in  Section  5.4.  The  following  limited  construction 
suffices  for  the  present: 

1.  Construct  a  predictive  parser,  ignoring  t he  actions  in  productions. 

2.  Copy  t he  actions  from  t he  translation  scheme  into  t he  parser.  If  an  action 
appears  after  grammar  symbol  X  in  production  p,  then  it  is  copied  after 
the  implementation  of  X  in  the  code  for  p.  Otherwise,  if  it  appears  at  t he 
beginning  of t he  production,  then  it  is  copied  just  before  the  code  for  t he 
production  body. 

We  shall  construct  such  a  translator  in  Section  2.5. 

2.4.5  Left  Recursion 
It  is  possible  for  a  recursive-descent  parser  to  loop  forever.  A  problem  arises 
with  "left-recursive"  productions  like 

expr  —y 

expr  +  term 

where  t he  leftmost  symbol  of  t he  body  is  t he  same  as  t he  nonterminal  at  the 
head  of  the  production.  Suppose  the  procedure  for  expr  decides  to  apply  this 
production.  T he  body  begins  with  expr  so  the  procedure  for  expr  is  called 
recursively.  Since  the  lookahead  symbol  changes  only  when  a  terminal  in  t he 
b o dy  is  matched,  no  change  to  the  input  took  place  between  recursive  calls  of 
expr.  As  a  result,  the  second  call  to  expr  does  exactly  what  the  first  call  did, 
which  means  a  third  call  to  expr,  and  so  on,  forever. 

A  left-recursive  production  can  be  eliminated  by  rewriting  the  offending 

production.  Consider  a  nonterminal  A  with  two  productions 

A  ->•  Aa  |  /3 

where  a  and  /3  are  sequences  of  terminals  and  nonterminals  t h at  do  not  start 
with  A.  For  example,  in 

expr  —y 

expr  +  term 

\ 

term 

nonterminal  A  —  expr,  string  a  =  +  term,  and  string  (3  =  term. 

T he  nonterminal  A  and  its  production  are  said  to  be  left  recursive,  because 
t he  production  A  ->  Aa  has  A  itself  as  the  leftmost  symbol  on  the  right  side.4 
Repeated  application  of this  production  builds  up  a  sequence  of  a 's  to  the  right 
of A,  as  in  Fig.  2.20(a).  W h en  A  is  finally  replaced  by  /3,  we  have  a  /3  followed 
by  a  sequence  of  zero  or  more  a ' s. 

T he  same  effect  can  be  achieved,  as  in  Fig.  2.20(b),  by  rewriting  t he  pro 

ductions  for  A  in  t he  following  manner,  using  a  new  nonterminal  R: 

4 In  a  general  left-recursive  grammar,  instead  of  a  production  A A a,  the  nonterminal  A 

may  derive  Aa  through  intermediate  productions. 

68 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

A 

A 

R 

R 

(b) 

(a) 

A 

A 

A 

R 

R 

a 

a 

a 

a 

(3  a 

a 

Figure  2.20:  Left-  and  right-recursive  ways  of  generating  a  string 

A 
R 

-> 
->• 

/3R 
aR  |  e 

Nonterminal  R  and  its  production  R  -»  aR  are 
recursive  because  this  pro 
duction  for  R  has  R  itself  as  the  last  symbol  on  the  right  side.  Right-recursive 
productions  lead  to  trees  t h at  grow  down  towards  t he  right,  as  in  Fig.  2.20(b). 
Trees  growing  down  to  the  right  make  it  harder  to  translate  expressions  con 
taining  left-associative  operators,  such  as  minus.  In  Section  2.5.2,  however,  we 
shall  see  t h at  the  proper  translation  of  expressions  into  postfix  notation  can 
still  be  attained  by  a  careful  design  of  t he  translation  scheme. 

In  Section  4.3.3,  we  shall  consider  more  general  forms  of  left  recursion  and 

show  how  all  left  recursion  can  be  eliminated  from  a  grammar. 

2.4.6  Exercises  for  Section  2.4 

E x e r c i se  2 . 4 . 1:  Construct  recursive-descent  parsers,  starting  with  t he  follow 
ing  grammars: 

a)  S 

->  +  SS 

| 

-SS 

| 

a 

b)  S 

c)  S 

->  5 ( 5 )5 

|  e 

0  5  1 

|  0  1 

2.5  A  Translator  for  Simple  Expressions 

Using  the  techniques  of  the  last  three  sections,  we  now  construct  a  syntax-
directed  translator,  in  the  form  of  a  working  Java  program,  t h at  translates 
arithmetic  expressions  into  postfix  form.  To  keep  t he  initial  program  manage 
ably  small,  we  start  with  expressions  consisting  of  digits  separated  by  binary 
plus  and  minus  signs.  We  extend  the  program  in  Section  2.6  to  translate  ex 
pressions  t h at  include  numbers  and  other  operators.  It  is  worth  studying  t he 

2.5. 

A 

TRANSLATOR  FOR  SIMPLE  EXPRESSIONS 

69 

translation  of expressions  in  detail,  since  they  appear  as  a  construct  in  so  many 
languages. 

A  syntax-directed  translation  scheme  often  serves  as  t he  specification  for 
a  translator.  T he  scheme  in  Fig.  2.21  (repeated  from  Fig.  2.15)  defines  t he 
translation  to  be  performed  here. 

expr 

term 

-> 
| 
| 

-» 
| 

expr  +  term 
expr  -  term 
term 

{  print('+/)  } 
{  p r i n t ( ' - ')  } 

0 
1 

{  print('O')  } 
{  p r i n t ( ' l ')  } 

| 

9 

{  print('9')  } 

Figure  2.21:  Actions  for  translating  into  postfix  notation 

Often,  t he  underlying  g r a m m ar  of  a  given  scheme  has  to  be  modified  before 
it  can  be  parsed  with  a  predictive  parser.  In  particular,  the  grammar  underlying 
the  scheme  in  Fig.  2.21  is  left  recursive,  and  as  we  saw  in  the  last  section,  a 
predictive  parser  cannot  handle  a  left-recursive  grammar. 

We  appear  to  have  a  conflict:  on  the  one  hand  we  need  a  g r a m m ar  t h at 
facilitates  translation,  on  t he  other  h a nd  we  need  a  significantly  different  gram 
mar  t h at  facilitates  parsing.  T he  solution  is  to  begin  with  the  g r a m m ar  for 
easy  translation  and  carefully  transform  it  to  facilitate  parsing.  By  eliminating 
t he  left  recursion  in  Fig.  2.21,  we  can  obtain  a  grammar  suitable  for  use  in  a 
predictive  recursive-descent  translator. 

2.5.1  Abstract  and  Concrete  Syntax 

A  useful  starting  point  for  designing  a  translator  is  a  d a ta  structure  called 
an  abstract  syntax  tree. 
In  an  abstract  syntax  tree  for  an  expression,  each 
interior  node  represents  an  operator;  t he  children  of  t he  node  represent  t he 
operands  of  t he  operator.  More  generally,  any  programming  construct  can  be 
handled  by  making  up  an  operator  for  the  construct  and  treating  as  operands 
t he  semantically  meaningful  components  of  t h at  construct. 

In  t he  abstract  syntax  tree  for  9 - 5 +2  in  Fig.  2.22,  the  root  represents  the 
operator  +.  T he  subtrees  of  t he  root  represent  t he  subexpressions  9 -5  and 
2.  T he  grouping  of  9 -5  as  an  operand  reflects  t he  left-to-right  evaluation  of 
operators  at  the  same  precedence  level.  Since  -  and  +  have t he  same  precedence, 
9 - 5 +2  is  equivalent  to 

( 9 - 5 ) + 2. 

Abstract  syntax  trees,  or  simply  syntax  trees,  resemble  parse  trees  to  an 
extent.  However,  in  t he  syntax  tree,  interior  nodes  represent  programming 
constructs  while  in  the  parse  tree,  the  interior  nodes  represent  nonterminals. 
Many  nonterminals  of a  g r a m m ar  represent  programming  constructs,  but  others 

70 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

+ 

\ 

5 

2 

9 

Figure  2.22:  Syntax  tree  for  9-5+2 

are  "helpers"  of  one  sort  of  another,  such  as  those  representing  terms,  factors, 
or  other  variations  of expressions.  In  t he  syntax  tree,  these  helpers  typically  are 
not  needed  and  are  hence  dropped.  To  emphasize  t he  contrast,  a  parse  tree  is 
sometimes  called  a  concrete  syntax  tree,  and  the  underlying  grammar  is  called 
a  concrete  syntax  for  the  language. 

In  the  syntax  tree  in  Fig.  2.22,  each  interior  node  is  associated  with  an 
operator,  with  no  "helper"  nodes  for  single  productions  (a  production  whose 
body  consists  of a  single  nonterminal,  and  nothing  else)  like  expr —»•  term  or  for 
e-productions  like  rest  ->  e. 

It  is  desirable  for  a translation  scheme  to  be  based  on  a  g r a m m ar  whose  parse 
trees  are  as  close  to  syntax  trees  as  possible.  T he  grouping  of  subexpressions 
by  t he  g r a m m ar  in  Fig.  2.21  is  similar  to  their  grouping  in  syntax  trees.  For 
example,  subexpressions  of  t he  addition  operator  are  given  by  expr  and  term  in 
t he  production  body  expr+  term. 

2.5.2  Adapting  the  Translation  Scheme 

T he  left-recursion-elimination  technique  sketched  in  Fig.  2.20  can  also  be  ap 
plied  to  productions  containing  semantic  actions.  First,  the  technique  extends 
to  multiple  productions  for  A.  In  our  example,  A  is  expr,  and  there  are  two  left-
recursive  productions  for  expr and  one  t h at  is  not  left  recursive.  T he  technique 
transforms  the  productions  A  ->•  Aa  |  A/3  |  7  into 

-»• 

7.R 

A 
R 

aR\/3R\e 

Second,  we  need  to  transform  productions  t h at  have  embedded  actions,  not 
just  terminals  and  nonterminals.  Semantic  actions  embedded  in  t he  productions 
are  simply  carried  along  in  the  transformation,  as  if  they  were  terminals. 

E x a m p le  2 . 1 3:  Consider  t he  translation  scheme  of  Fig.  2.21.  Let 

A 
a 

1 

expr 
+  term  {  print('+')  } 
-  term  {  p r i n t ( ' - ')  } 
term 

2.5. 

A 

TRANSLATOR  FOR  SIMPLE  EXPRESSIONS 

71 

t he 

left-recursion-eliminating  transformation  produces 

translation 
Then 
scheme  in  Fig. 2.23.  T he  expr productions  in  Fig. 2.21  have  been  transformed 
into  t he  productions  for  expr,  and  a  new  nonterminal  rest  plays  t he  role  of  R. 
T he  productions  for  term  are  repeated  from  Fig. 2.21.  Figure 2.24  shows  how 
9-5+2  is  translated  using  the  g r a m m ar  in  Fig. 2.23.  • 

t he 

expr  —y 

term  rest 

rest  —y  +  term  {  print('+/)  } 
-  term  {  p r i n t ( ' - ')  } 

rest 
rest 

| 
I 
-» 
| 

term 

c 

0  {  print ('0')  } 
1  {  print('1')  } 

|  9  {  print('9') } 

Figure 2.23:  Translation  scheme  after  left-recursion  elimination 

Figure 2.24:  Translation  of 9-5+2  to 95-2+ 

Left-recursion  elimination  must  be  done  carefully,  to  ensure  t h at  we  preserve 
t he  ordering  of  semantic  actions.  For  example,  the  transformed  scheme  in 
Fig.  2.23  has  the  actions  {  print ('+')  }  and  {  p r i n t ( ' - ')  }  in  the  middle  of 
a  production  body,  in  each  case  between  nonterminals  term  and  rest. 
If  t he 
actions  were  to  be  moved  to  t he  end,  after  rest,  then  the  translations  would 
become  incorrect.  We  leave  it  to  the  reader  to  show  t h at 9-5+2  would  then  be 
translated  incorrectly  into 952+-,  t he  postfix  notation  for 9-(5+2),  instead  of 
t he  desired 95-2+,  the  postfix  notation  for (9-5)+2. 

72 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

2.5.3  Procedures  for  the  Nonterminals 

Functions  expr,  rest,  and  term  in  Fig.  2.25  implement  the  syntax-directed  trans 
lation  scheme  in  Fig.  2.23.  These  functions  mimic  t he  production  bodies  of 
the  corresponding  nonterminals. 
Function  expr  implements  the  production 
expr-\ 

termQ  followed  by  restQ. 

term  rest  by  the  calls 

v o id  exprQ  { 
termi); 

restQ; 

} 

v o id  restQ  { 

if  (  lookahead  ==  '+'  )  { 
termQ; 
match('+'); 

print('+'); 

restQ; 

} 
e l se  if  (  lookahead  ==  '-'  )  { 

match('-'); 

termQ; 

p r i n t ( ' - ' ); 

restQ; 

} 
e l se  {  }  /*  do  nothing  with  the  input  */  ; 

} 

v o id  termQ  { 

if  (  lookahead  is  a  digit  )  { 

t  =  lookahead;  match(lookahead); 

print(t); 

} 
e l se  report (" syntax  error"); 

} 

Figure  2.25:  Pseudocode  for  nonterminals  expr,  rest,  and  term. 

Function  rest  implements 

the  three  productions  for  nonterminal  rest  in 
It  applies  t he  first  production  if  t he  lookahead  symbol  is  a  plus 
Fig.  2.23. 
sign,  t he  second  production  if  t he  lookahead  symbol  is  a  minus  sign,  and  the 
production  rest 
e  in  all  other  cases.  The  first  two  productions  for  rest  are 
implemented  by  the  first  two  branches  of  the  if-statement  in  procedure  rest. 
If  t he  lookahead  symbol  is  +,  the  plus  sign  is  matched  by  the  call  match('+'). 
After  the  call  termQ,  t he  semantic  action  is  implemented  by  writing  a  plus 
character.  T he  second  production  is  similar,  with  -  instead  of  +.  Since  t he 
third  production  for  rest  has  e  as  its  right  side,  the  last  else-clause  in  function 
rest  does  nothing. 

T he  ten  productions  for  term  generate  t he  ten  digits.  Since  each  of  these 
productions  generates  a  digit  and  prints  it,  the  same  code  in  Fig.  2.25  imple 
ments  t h em  all.  If  t he  test  succeeds,  variable  t  saves  the  digit  represented  by 
lookahead  so  it  can  be  written  after  t he  call  to  match.  Note  t h at  match  changes 

2.5. 

A 

TRANSLATOR  FOR  SIMPLE  EXPRESSIONS 

73 

t he  lookahead  symbol,  so  t he  digit  needs  to  be  saved  for  later  printing.5 

2.5.4 

Simplifying  the  Translator 

Before  showing  a  complete  program,  we  shall  make  two  simplifying  transfor 
mations  to  t he  code  in  Fig.  2.25.  T he  simplifications  will  fold  procedure  rest 
into  procedure  expr.  When  expressions  with  multiple  levels  of  precedence  are 
translated,  such  simplifications  reduce  the  number  of  procedures  needed. 

First,  certain  recursive  calls  can  be  replaced  by  iterations.  W h en  the  last 
statement  executed  in  a  procedure  body  is  a  recursive  call  to  t he  same  proce 
dure,  the  call  is  said  to  be  tail  recursive.  For  example,  in  function  rest,  the 
calls  of  rest()  with  lookahead  +  and  -  are  tail  recursive  because  in  each  of these 
branches,  t he  recursive  call  to  rest  is  the  last  statement  executed  by  t he  given 
call  of  rest. 

For  a  procedure  without  parameters,  a  tail-recursive  call  can  be  replaced 
simply  by  a  j u mp  to  the  beginning  of  the  procedure.  The  code  for  rest  can  be 
rewritten  as  the  pseudocode  of  Fig.  2.26.  As  long  as  the  lookahead  symbol  is 
a  plus  or  a  minus  sign,  procedure  rest  matches  the  sign,  calls  term  to  match 
a  digit,  and  continues  the  process.  Otherwise,  it  breaks  out  of  while  loop  and 
returns  from  rest. 

v o id  restQ  { 

w h i l e(  t r ue  )  { 

if(  lookahead  ==  '+'  )  { 
match('+'); 

termQ;  print('+');  c o n t i n u e; 

} 
e l se  if  (  lookahead  —=  '-'  )  { 

match('-'); 

termQ;  p r i n t ( ' - ' );  c o n t i n u e; 

} 
b r e ak  ; 

} 

} 

Figure  2.26:  Eliminating  tail  recursion  in  t he  procedure  rest  of  Fig.  2.25. 

Second,  the  complete  Java  program  will  include  one  more  change.  Once 
the  tail-recursive  calls  to  rest  in  Fig.  2.25  are  replaced  by  iterations,  the  only 
remaining  call  to  rest  is  from  within  procedure  expr.  The  two  procedures  can 
therefore  be  integrated  into  one,  by  replacing  the  call  restQ  by  the  body  of 
procedure  rest. 

5  As  a  minor  optimization,  we  could  print  before  calling  match  to  avoid  the  need  to  save 
the  digit.  In  general,  changing  the  order  of  actions  and  grammar  symbols  is  risky,  since  it 
could  change  what  the  translation  does. 

74 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

2.5.5  The  Complete  Program 

T he  complete  Java  program  for  our  translator  appears  in  Fig.  2.27.  The  first 
line of Fig. 2.27, beginning with import, provides access to t he package j ava. io 
for  system  input  and  output.  T he  rest  of  t he  code  consists  of  t he  two  classes 
Parser  and Postfix.  Class Parser  contains  variable lookahead  and  functions 
Parser, expr, term,  and match. 

Execution  begins  with  function main,  which  is  defined  in  class Postfix. 

Function main  creates  an  instance parse  of  class Parser  and  calls  its  function 
expr  to  parse  an  expression. 

The  function Parser,  with  t he  same  name  as  its  class,  is  a  constructor, 
it  is  called  automatically  when  an  object  of  t he  class  is  created.  Notice  from 
its  definition  at  t he  beginning  of  class Parser  t h at  t he  constructor Parser 
initializes  variable lookahead  by  reading  a  token.  Tokens,  consisting  of  single 
characters,  are  supplied  by  t he  system  input  routine read,  which  reads  t he  next 
character from  t he  input  file.  Note  t h at lookahead is  declared  to  be  an  integer, 
rather  t h an  a  character,  to  anticipate  t he  fact  t h at  additional  tokens  other  t h an 
single  characters  will  be  introduced  in  later  sections. 

Function expr  is  the  result  of t he  simplifications  discussed  in  Section  2.5.4; 

it  implements  nonterminals  expr  and  rest  in  Fig.  2.23.  T he  code  for expir 
in  Fig.  2.27  calls term  and  then  has  a  while-loop  t h at  forever  tests  whether 
lookahead  matches  either  ' + '  or  ' - '.  Control  exits  from  this  while-loop  when 
it  reaches  the  return  statement.  Within  the  loop,  the  i n p u t / o u t p ut  facilities  of 
the System  class  are  used  to  write  a  character. 

Function term  uses  the  routine  isDigit  from  the  Java  class Character 

to  test  if  t he  lookahead  symbol  is  a  digit.  T he  routine isDigit  expects  to 
be  applied  to  a  character;  however, lookahead  is  declared  to  be  an  integer, 
anticipating  future  extensions.  T he  construction (char) lookahead  casts  or 
coerces lookahead  to  be  a  character. 
In  a  small  change  from  Fig.  2.25,  t he 
semantic  action  of  writing  the  lookahead  character  occurs  before  t he  call  to 
match. 

T he  function match  checks  terminals;  it  reads  the  next  input  terminal  if t he 

lookahead  symbol  is  matched  and  signals  an  error  otherwise  by  executing 

throw  new  Error("syntax  error"); 

This  code  creates  a  new  exception  of  class  E r r or  and  supplies  it  t he  string 
syntax error  as  an  error  message.  Java  does  not  require  E r r or  exceptions 
to  be  declared  in  a throws  clause,  since  they  are  meant  to  be  used  only  for 
abnormal  events  t h at  should  never  occur.6 

6 Error  handling  can  be  streamlined  using  the  exception-handling  facilities  of Java.  One  ap 
proach  is to define  a new  exception,  say SyntaxError,  that  extends  the system class Exception. 
Then,  throw SyntaxError  instead  of Error  when  an  error  is  detected  in  either term  or match. 
Further,  handle  the  exception  in main  by  enclosing  the  call parse.expr()  within  a try  state 
ment  that  catches  exception SyntaxError,  writes  a  message,  and  terminates.  We  would  need 
to  add  a class SyntaxError  to  the  program  in  Fig.  2.27.  To  complete  the  extension,  in  addition 
to IOException,  functions match and term must now declare that they can throw SyntaxError. 
Function expr,  which  calls  them,  must  also  declare  that  it  can  throw SyntaxError. 

2.5. 

A 

TRANSLATOR  FOR  SIMPLE  EXPRESSIONS 

75 

import  java.io.*; 
class  Parser  { 

static  int  lookahead; 

public  Parser()  throws  IOException  { 
lookahead =  System.in.read(); 

} 

void  expr()  throws  IOException  { 

term(); 
while(true)  { 

if(  lookahead == 

)  { 

match('+'); t e r mO ; System, out .write (' + ' ); 

} 
else  if(  lookahead ==  '-'  )  { 

match('-');  term();  System.out.write('-'); 

} 
else  return; 

} 

} 

void term()  throws  IOException  { 

if(  Character.isDigit((char)lookahead)  )  { 

System.out.write((char)lookahead); match(lookahead); 

} 
else  throw new Error("syntax  error"); 

} 

void match(int  t)  throws  IOException  { 

if(  lookahead ==  t  )  lookahead =  System.in.read(); 
else  throw new  Error("syntax error"); 

} 

> 

public  class  Postfix  { 

public  static  void main(String[]  args)  throws  IOException { 

Parser  parse  =  new  P a r s e r O; 

parse.expr(); System.out.write('\n'); 

> 

} 

Figure  2.27:  Java  program  to  translate  infix  expressions  into  postfix  form 

76 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

A  Few  Salient  Features  of  Java 

Those  unfamiliar  with  Java  may  find  the  following  notes  on  Java  helpful 
in  reading  the  code  in  Fig.  2.27: 

•  A  class  in  Java  consists  of  a  sequence  of  variable  and  function  defi 

nitions. 

•  Parentheses  enclosing  function  parameter  lists  are  needed  even  if 
there  are  no  parameters;  hence  we  write expr()  and term().  These 
functions  are  actually  procedures,  because  they  do  not  return  values, 
signified  by  the  keyword void  before  the  function  name. 

•  Functions  communicate  either  by  passing  parameters  "by  value" 
or  by  accessing  shared  data.  For  example,  t he  functions expr() 
and term()  examine  the  lookahead  symbol  using  the  class  variable 
lookahead t h at  they  can  all  access  since  they  all  belong  to  t he  same 
class Parser. 

•  Like  C,  Java  uses  =  for  assignment,  ==  for  equality,  and  !=  for  in 

equality. 

•  T he  clause  "throws IOException"  in  t he  definition  of term()  de 
clares  t h at  an  exception  called IOException  can  occur.  Such  an 
exception  occurs  if  there  is  no  input  to  be  read  when  t he  function 
match uses the routine read.  Any function t h at calls match must also 
declare  t h at  an IOException  can  occur  during  its  own  execution. 

2.6  Lexical  Analysis 

A  lexical  analyzer  reads  characters  from  the  input  and  groups  t h em  into  "token 
objects."  Along  with  a  terminal  symbol  t h at  is  used  for  parsing  decisions, 
a  token  object  carries  additional  information  in  the  form  of  a t t r i b u te  values. 
So  far,  there  has  been  no  need  to  distinguish  between  t he  terms  "token"  and 
"terminal,"  since  t he  parser  ignores  t he  a t t r i b u te  values  t h at  are  carried  by  a 
token.  In  this  section,  a  token  is  a  terminal  along  with  additional  information. 
A  sequence  of  input  characters  t h at  comprises  a  single  token  is  called  a 
lexeme.  Thus,  we  can  say  t h at  the  lexical  analyzer  insulates  a  parser  from  t he 
lexeme  representation  of  tokens. 

T he  lexical  analyzer  in  this  section  allows  numbers,  identifiers,  and  "white 
space"  (blanks,  tabs,  and  newlines)  to  appear  within  expressions.  It  can  be  used 
to  extend  t he  expression  translator  of the  previous  section.  Since  t he  expression 
grammar  of  Fig.  2.21  must  be  extended  to  allow  numbers  and  identifiers,  we 

2.6. 

LEXICAL  ANALYSIS 

77 

shall  take  this  opportunity  to  allow  multiplication  and  division  as  well.  T he 
extended  translation  scheme  appears  in  Fig.  2.28. 

expr 

term 

factor 

-» 
| 
| 

-»• 
| 
| 

-» 
| 
| 

expr  +  term 
expr  -  term 
term 

term  *  factor 
term  I  factor 
factor 

(  expr) 
n um 
id 

{  print ('+')  } 
{  print ('-')  } 

{  print('*')  } 
{  p r i n t ( ' / ')  } 

{  print ( n u m. value)  } 
{  print (id .lexeme)  } 

Figure  2.28:  Actions  for  translating  into  postfix  notation 

In  Fig.  2.28,  the  terminal  n um  is  assumed  to  have  an  a t t r i b u te  imm.value, 
which  gives  the  integer  value  corresponding  to  this  occurrence  of  n u m.  Termi 
nal  id  has  a  string-valued  a t t r i b u te  written  as  id.lexeme;  we  assume  this  string 
is  t he  actual  lexeme  comprising  this  instance  of  t he  token  id. 

T he  pseudocode  fragments  used  to  illustrate  the  workings  of  a  lexical  ana 
lyzer  will  be  assembled  into  Java  code  at  t he  end  of this  section.  T he  approach 
in  this  section  is  suitable  for  hand-written  lexical  analyzers.  Section  3.5  de 
scribes  a  tool  called  Lex  t h at  generates  a  lexical  analyzer  from  a  specification. 
Symbol  tables  or  d a ta  structures  for  holding  information  about  identifiers  are 
considered  in  Section  2.7. 

2.6.1  Removal  of  White  Space  and  Comments 

T he  expression  translator  in  Section  2.5  sees  every  character  in  the  input,  so 
extraneous  characters,  such  as  blanks,  will  cause  it  to  fail.  Most  languages 
allow  arbitrary  amounts  of  white  space  to  appear  between  tokens.  Comments 
are  likewise  ignored  during  parsing,  so  they  may  also  be  treated  as  white  space. 

If  white  space  is  eliminated  by  t he  lexical  analyzer,  t he  parser  will  never 
have  to  consider  it.  T he  alternative  of  modifying  the  grammar  to  incorporate 
white  space  into  the  syntax  is  not  nearly  as  easy  to  implement. 

T he  pseudocode  in  Fig.  2.29  skips  white  space  by  reading  input  characters 
as  long  as  it  sees  a  blank,  a  t a b,  or  a  newline.  Variable  peek  holds  the  next 
input  character.  Line  numbers  and  context  are  useful  within  error  messages  to 
help  pinpoint  errors;  t he  code  uses  variable  line  to  count  newline  characters  in 
the  input. 

78 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

for  (  ;  ;  peek  =  next  input  character  )  { 

if  (  peek  is  a  blank  or  a  t ab  )  do  nothing; 
e l se  if  (  peek  is  a  newline  )  line  =  line+1; 
e l se  break; 

} 

Figure  2.29:  Skipping  white  space 

2.6.2  Reading  Ahead 

A  lexical  analyzer  may  need  to  read  ahead  some  characters  before  it  can  decide 
on  the  token  to  be  returned  to  t he  parser.  For  example,  a  lexical  analyzer  for 
C  or  Java  must  read  ahead  after  it  sees  the  character  >.  If  t he  next  character 
is  =,  then  >  is  part  of  t he  character  sequence  >=,  the  lexeme  for  t he  token  for 
the  "greater  t h an  or  equal  t o"  operator.  Otherwise  >  itself  forms  t he  "greater 
t h a n"  operator,  and  the  lexical  analyzer  has  read  one  character  too  many. 

A  general  approach  to  reading  ahead  on  t he  input,  is  to  maintain  an  input 
buffer  from  which  the  lexical  analyzer  can  read  and  push  back  characters.  Input 
buffers  can  be  justified  on  efficiency  grounds  alone,  since  fetching  a  block  of 
characters  is  usually  more  efficient  t h an  fetching  one  character  at  a  time.  A 
pointer  keeps  track  of  the  portion  of t he  input  t h at  has  been  analyzed;  pushing 
back  a  character  is  implemented  by  moving  back  the  pointer.  Techniques  for 
input  buffering  are  discussed  in  Section  3.2. 

One-character  read-ahead  usually  suffices,  so  a  simple  solution  is  to  use  a 
variable,  say  peek,  to  hold  t he  next  input  character.  T he  lexical  analyzer  in 
this  section  reads  ahead  one  character  while  it  collects  digits  for  numbers  or 
characters  for  identifiers;  e.g.,  it  reads  past  1  to  distinguish  between  1  and  10, 
and  it  reads  past  t  to  distinguish  between  t  and  t r u e. 

T he  lexical  analyzer  reads  ahead  only  when  it  must.  An  operator  like  *  can 
be  identified  without  reading  ahead.  In  such  cases,  peek  is  set  to  a  blank,  which 
will  be  skipped  when  the  lexical  analyzer  is  called  to  find  the  next  token.  T he 
invariant  assertion  in  this  section  is  t h at  when  the  lexical  analyzer  returns  a 
token,  variable  peek either  holds  t he  character  beyond  t he  lexeme  for  t he  current 
token,  or  it  holds  a  blank. 

2.6.3  Constants 

Anytime  a  single  digit  appears  in  a grammar  for  expressions,  it  seems  reasonable 
to  allow  an  arbitrary  integer  constant  in  its  place. 
Integer  constants  can  be 
allowed  either  by  creating  a  terminal  symbol,  say  n u m,  for  such  constants  or 
by  incorporating  the  syntax  of  integer  constants  into  t he  grammar.  T he  job 
of  collecting  characters  into  integers  and  computing  their  collective  numerical 
value  is  generally  given  to  a  lexical  analyzer,  so  numbers  can  be  treated  as  single 
units  during  parsing  and  translation. 

2.6. 

LEXICAL  ANALYSIS 

79 

W h en  a  sequence  of  digits  appears  in  the  input  stream,  the  lexical  analyzer 
passes  to  t he  parser  a  token  consisting  of  the  terminal  n um  along  with  an 
integer-valued  a t t r i b u te  computed  from  the  digits.  If  we  write  tokens  as  tuples 
enclosed  between  (  ),  t he  input 31 + 28 + 59  is  transformed  into  t he  sequence 

( n u m, 31) 

(+) 

( n u m, 28) 

(+) 

( n u m, 59) 

Here,  the  terminal  symbol  +  has  no  attributes,  so  its  tuple  is  simply  (+).  T he 
pseudocode  in  Fig.  2.30  reads  the  digits  in  an  integer  and  accumulates  t he  value 
of  t he  integer  using  variable  v. 

if  (  peek  holds  a  digit  )  { 

v  =  0; 
do  { 

v  =  v  *  10  +  integer  value  of  digit  peek; 
peek  =  next  input  character; 

}  w h i le  (  peek  holds  a  digit  ); 
r e t u rn  token  ( n u m,  v); 

} 

Figure  2.30:  Grouping  digits  into  integers 

2.6.4  Recognizing  Keywords  and  Identifiers 

Most  languages  use  fixed  character  strings  such  as  f o r,  do,  and  i f,  as  punctua 
tion  marks  or  to  identify  constructs.  Such  character  strings  are  called  keywords. 
Character  strings  are  also  used  as  identifiers  to  name  variables,  arrays,  func 
tions,  and  t he  like.  G r a m m a rs  routinely  treat  identifiers  as  terminals  to  sim 
plify  the  parser,  which  can  then  expect  the  same  terminal,  say  id,  each  time 
any  identifier  appears  in  the  input.  For  example,  on  input 

count  =  count  +  increment; 

(2.6) 

t he  parser  works  with  t he  terminal  stream  id  =  id  +  id.  T he  token  for  id  has 
an  a t t r i b u te  t h at  holds  the  lexeme.  Writing  tokens  as  tuples,  we  see  t h at  t he 
tuples  for  the  input  stream  (2.6)  are 

(id,  "count")  (=)  (id,  "count")  (+)  (id,  "increment")  (;) 

Keywords  generally  satisfy  the  rules  for  forming  identifiers,  so  a  mechanism 
is  needed  for  deciding  when  a  lexeme  forms  a  keyword  and  when  it  forms  an 
identifier.  T he  problem  is  easier  to  resolve  if  keywords  are  reserved;  i.e.,  if  they 
cannot  be  used  as  identifiers.  Then,  a  character  string  forms  an  identifier  only 
if  it  is  not  a  keyword. 

80 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

T he  lexical  analyzer  in  this  section  solves  two  problems  by  using  a  table  to 

hold  character  strings: 

•  Single  Representation.  A  string  table  can  insulate  t he  rest  of  the  compiler 
from  t he  representation  of  strings,  since  t he  phases  of  the  compiler  can 
work  with  references  or  pointers  to  t he  string  in  the  table.  References  can 
also  be  manipulated  more  efficiently  t h an  the  strings  themselves. 

•  Reserved  Words.  Reserved  words  can  be  implemented  by  initializing  t he 
string  table  with  the  reserved  strings  and  their  tokens.  When  t he  lexical 
analyzer  reads  a  string  or  lexeme  t h at  could  form  an  identifier,  it  first 
checks  whether  the  lexeme  is  in  the  string  table. 
If  so,  it  returns  the 
token  from  the  table;  otherwise,  it  returns  a  token  with  terminal  id. 

In  Java,  a  string  table  can  be  implemented  as  a  hash  table  using  a  class 

called  Hashtable.  T he  declaration 

Hashtable  words  =  n ew  HashtableQ; 

sets  up  words  as  a  default  hash  table  t h at  maps  keys  to  values.  We  shall  use  it 
to  m ap  lexemes  to  tokens.  T he  pseudocode  in  Fig.  2.31  uses  t he  operation  get 
to  look  up  reserved  words. 

if  (  peek  holds  a  letter  )  { 

collect  letters  or  digits  into  a  buffer  6; 
s  =  string  formed  from  the  characters  in  6; 
w  =  token  returned  by  words.get(s); 
if  (  w  is  not  n u l l)  r e t u rn  w; 
e l se  { 

Enter  t he  key-value  pair  (s,  (id,  s))  into  words 
r e t u rn  token  (id,  s); 

} 

} 

Figure  2.31:  Distinguishing  keywords  from  identifiers 

This  pseudocode  collects  from  the  input  a  string  s  consisting  of  letters  and 
digits  beginning  with  a  letter.  We  assume  t h at  s  is  made  as  long  as  possible; 
i.e.,  t he  lexical  analyzer  will  continue  reading  from  t he  input  as  long  as  it 
encounters  letters  and  digits.  W h en  something  other  t h an  a  letter  or  digit,  e.g., 
white  space,  is  encountered,  the  lexeme  is  copied  into  a  buffer  6.  If  t he  table 
has  an  entry  for  s,  then  t he  token  retrieved  by  words.get  is  returned.  Here,  s 
could  be  either  a  keyword,  with  which  t he  words  table  was  initially  seeded,  or 
it  could  be  an  identifier  t h at  was  previously  entered  into  t he  table.  Otherwise, 
token  id  and  a t t r i b u te  s  are  installed  in  the  table  and  returned. 

2.6. 

LEXICAL  ANALYSIS 

81 

2.6.5  A  Lexical  Analyzer 

T he  pseudocode  fragments  so  far  in  this  section  fit  together  to  form  a  function 
scan  t h at  returns  token  objects,  as  follows: 

Token  scanQ  { 

skip  white  space,  as  in  Section  2.6.1; 
handle  numbers,  as  in  Section  2.6.3; 
handle  reserved  words  and  identifiers,  as  in  Section  2.6.4; 
/*  if  we  get  here,  treat  read-ahead  character  peek  as  a  token  */ 
Token  t  =  n ew  Token(peek); 
peek  =  blank  /*  initialization,  as  discussed  in  Section  2.6.2  */  ; 
r e t u rn  i; 

} 

The  rest  of  this  section  implements  function  scan  as  part  of  a  Java  package 
for  lexical  analysis.  The  package,  called  l e x er  has  classes  for  tokens  and  a  class 
Lexer  containing  function  s c a n. 

T he  classes  for  tokens  and  their  fields  are  illustrated  in  Fig.  2.32;  their 
methods  are  not  shown.  Class  Token  has  a  field  t ag  t h at  is  used  for  parsing 
decisions.  Subclass  Num  adds  a  field  v a l ue  for  an  integer  value.  Subclass  Word 
adds  a  field  lexeme  t h at  is  used  for  reserved  words  and  identifiers. 

c l a ss  Token 

i nt 

tag 

c l a ss  Num 

i nt  value 

c l a ss  Word 

s t r i ng 

lexeme 

Figure  2.32:  Class  Token  and  subclasses  Num  and  Word 

Each  class  is  in  a  file  by  itself.  T he  file  for  class  Token  is  as  follows: 

1)  p a c k a ge  l e x e r; 
2)  p u b l ic  c l a ss  Token  { 
t a g; 
p u b l ic  f i n al 
3) 
p u b l ic  T o k e n ( i nt  t)  { 
4) 

i nt 

5)  > 

//  File  Token.java 

t ag  =  t;  } 

Line  1  identifies  the  package  l e x e r.  Field  t ag  is  declared  on  line  3  to  be  f i n al 
so  it  cannot  be  changed  once  it  is  set.  T he  constructor  Token  on  line  4  is  used 
to  create  token  objects,  as  in 

new  T o k e n ( ' + ') 

which  creates  a  new  object  of  class  Token  and  sets  its  field  t ag  to  an  integer 
representation  of  ' + '.  (For  brevity,  we  omit  t he  customary  m e t h od  t o S t r i n g, 
which  would  return  a  string  suitable  for  printing.) 

82 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

Where  the  pseudocode  had  terminals  like  n um  and  id,  the  Java  code  uses 

integer  constants.  Class  Tag  implements  such  constants: 

1)  package  l e x e r; 
2)  p u b l ic  c l a ss  Tag  { 
3) 
4) 

p u b l ic  f i n al  s t a t ic 

//  File  Tag.java 

i nt 

NUM  =  2 5 6,  ID  =  2 5 7,  TRUE  =  2 5 8,  FALSE  =  259; 

5) > 

In  addition  to  the  integer-valued  fields  NUM  and  ID,  this  class  defines  two  addi 
tional  fields,  TRUE  and  FALSE,  for  future  use;  they  will  be  used  to  illustrate  the 
treatment  of  reserved  keywords.7 

The  fields  in  class  Tag  are  p u b l i c,  so  they  can  be  used  outside  the  package. 
They  are  s t a t i c,  so  there  is  just  one  instance  or  copy  of  these  fields.  The 
fields  are  f i n a l,  so  they  can  be  set  just  once.  In  effect,  these  fields  represent 
constants.  A  similar  effect  is  achieved  in  C  by  using  define-statements  to  allow 
names  such  as  NUM  to  be  used  as  symbolic  constants,  e.g.: 

# d e f i ne  NUM  256 

The  Java code refers  to  Tag. NUM and  Tag. ID in  places  where the pseudocode 
referred  to  terminals  n um  and  id.  The  only  requirement  is  that  Tag.NUM  and 
Tag. ID  must  be  initialized  with  distinct  values  that  differ  from  each  other  and 
from  the  constants  representing  single-character  tokens,  such  as  ' +'  or  ' * '. 

1)  package  l e x e r; 
2)  p u b l ic  c l a ss  Num  e x t e n ds  Token  { 
3) 
4) 

p u b l ic  f i n al 
p u b l ic  Num(int  v)  {  super(Tag.NUM);  v a l ue  =  v;  } 

//  File  Num.Java 

i nt  v a l u e; 

5) > 

1)  package  l e x e r; 
2)  p u b l ic  c l a ss  Word  e x t e n ds  Token  { 
3) 
4) 
5) 

p u b l ic  f i n al  S t r i ng 
p u b l ic  WordQnt  t,  S t r i ng  s)  { 

s u p e r ( t ); 

lexeme; 

lexeme  =  new  S t r i n g ( s ); 

//  File  Word.java 

> 

6) 
7) > 

Figure  2.33:  Subclasses  Num  and  Word  of Token 

Classes  Num  and  Word  appear  in  Fig.  2.33.  Class  Num  extends  Token  by 
declaring  an  integer  field  v a l ue  on  line  3.  The  constructor  Num  on  line  4  calls 
super (Tag. NUM),  which  sets  field  t ag  in  the  superclass  Token  to  Tag. NUM. 

7ASCII  characters  are  typically  converted  into  integers  between  0  and  255.  We  therefore 

use  integers  greater  than  255  for  terminals. 

2.6. 

LEXICAL  ANALYSIS 

83 

1) package lexer; 
2)  import  java.io.*;  import  java.util.*; 

//  File  Lexer.Java 

3)  public  class  Lexer  { 

4) 
5) 
6) 
7) 

8) 
9) 

10) 

11) 

12) 

13) 

14) 

15) 

16) 

17) 

public  int  line  =  1; 
private char peek =  '  '; 
private  Hashtable  words  =  new  H a s h t a b l e O; 
void reserve(Word t)  { words.put(t.lexeme,  t );  } 

public Lexer ()  { 

reserve( new Word(Tag.TRUE,  "true")  ); 

reserve( new Word(Tag.FALSE,  "false")  ); 

> 

public  Token  scan()  throws  IOException  { 

for(  ;  ;  peek =  (char)System.in.read()  )  { 

if( peek ==  '  '  II  peek ==  '\t'  )  continue; 

else  if( peek ==  ' \ n;  )  line = line +  1; 

else  break; 

} 
/*  continues  in  Fig. 2.35 */ 

Figure 2.34:  Code  for  a  lexical  analyzer,  part 1  of 2 

Class Word  is  used  for  b o th  reserved  words  and  identifiers,  so  the  constructor 
Word  on  line 4  expects  two  parameters:  a  lexeme  and  a  corresponding  integer 
value for tag.  An  object  for  the  reserved word true  can  be  created  by executing 

new  Word(Tag.TRUE,  "true") 

which  creates  a new  object  with field tag  set  to Tag.TRUE and  field lexeme  set 
to  the  string "true". 

Class Lexer  for  lexical  analysis  appears  in  Figs. 2.34  and 2.35.  T he  integer 
variable line  on  line 4  counts  input  lines,  and  character  variable peek  on  line 5 
holds  the  next  input  character. 

Reserved  words  are  handled  on  lines 6  through 11.  The  table words  is 
declared  on  line 6.  T he  helper  function reserve  on  line 7  puts  a  string-word 
pair  in  t he  table.  Lines 9  and 10  in  t he  constructor Lexer  initialize  t he  table. 
They  use  t he  constructor Word  to  create  word  objects,  which  are  passed  to  t he 
helper  function reserve.  T he  table  is  therefore  initialized  with  reserved  words 
"true"  and "false"  before  the  first  call  of scan. 

T he  code  for scan  in  Fig. 2.34-2.35  implements  the  pseudocode  fragments 
in  this  section.  T he  for-statement  on  lines 13  through 17  skips  blank,  t a b, 
and  newline  characters.  Control  leaves  the  for-statement  with peek  holding  a 
non-white-space  character. 

T he  code  for  reading  a  sequence  of  digits  is  on  lines 18  through 25.  The 
function isDigit  is  from  the  built-in  Java  class Character. 
It  is  used  on 
line 18  to  check  whether peek  is  a  digit.  If so,  the  code  on  lines 19  through 24 

84 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

i f(  C h a r a c t e r . i s D i g i t ( p e e k) 

)  { 

i nt  v  =  0; 
do  { 

v  =  10*v  +  C h a r a c t e r . d i g i t ( p e e k,  1 0 ); 
( c h a r ) S y s t e m . i n . r e a d ( ); 
peek  = 

}  w h i l e(  C h a r a c t e r . i s D i g i t ( p e e k) 
r e t u rn  new  Num(v); 

); 

} 
i f(  C h a r a c t e r . i s L e t t e r ( p e e k) 

)  { 

S t r i n g B u f f er  b  =  new  S t r i n g B u f f e r ( ); 
do  { 

b . a p p e n d ( p e e k ); 
peek  = 

( c h a r ) S y s t e m . i n . r e a d ( ); 

); 

}  w h i l e(  C h a r a c t e r . i s L e t t e r O r D i g i t ( p e e k) 
S t r i ng  s  =  b . t o S t r i n gO  ; 
Word  w  =  ( W o r d ) w o r d s . g e t ( s ); 
i f(  w  !=  n u ll  )  r e t u rn  w; 
w  =  new  Word(Tag.ID,  s ); 
w o r d s . p u t ( s,  w); 
r e t u rn  w; 

} 
Token  t  =  new  Token(peek); 
peek  = 
r e t u rn 

' 
t; 

'; 

18) 
19) 
20) 
21) 
22) 
23) 
24) 
25) 
26) 
27) 
28) 
29) 
30) 
31) 
32) 
33) 
34) 
35) 
36) 
37) 
38) 
39) 
40) 
41) 
42) 
43) 

} 

} 

Figure  2.35:  Code  for  a  lexical  analyzer,  part  2  of  2 

accumulates  t he  integer  value  of t he  sequence  of digits  in  t he  input  and  returns 
a  new  Num  object. 

Lines  26  through  38  analyze  reserved  words  and  identifiers.  Keywords  t r ue 
and  false  have  already  been  reserved  on  lines  9  and  10.  Therefore,  line  35  is 
reached  if  string  s  is  not  reserved,  so  it  must  be  t he  lexeme  for  an  identifier. 
Line  35  therefore  returns  a  new  word  object  with  lexeme  set  to  s  and  t ag  set 
to  Tag. ID.  Finally,  lines  39  through  41  return  the  current  character  as  a  token 
and  set  peek  to  a  blank  t h at  will  be  stripped  t he  next  time  scan  is  called. 

2.6.6  Exercises  for  Section  2.6 

E x e r c i se  2 . 6 . 1:  Extend  t he  lexical  analyzer  in  Section  2.6.5  to  remove  com 
ments,  defined  as  follows: 

2.7. 

SYMBOL  TABLES 

85 

a)  A  comment  begins  with  //  and  includes  all  characters  until  t he  end  of 

t h at  line. 

b)  A  comment  begins  with  /*  and  includes  all  characters  through  t he  next 

occurrence  of  t he  character  sequence  * /. 

E x e r c i se  2 . 6 . 2:  Extend  the  lexical  analyzer  in  Section  2.6.5  to  recognize  the 
relational  operators  <,  <=,  ==,  !=,  >=,  >. 

E x e r c i se  2 . 6 . 3:  Extend  the  lexical  analyzer  in  Section  2.6.5  to  recognize  float 
ing  point  numbers  such  as  2 .,  3 . 1 4,  and  . 5. 

2.7  Symbol  Tables 

Symbol  tables  are  d a ta  structures  t h at  are  used  by  compilers  to  hold  information 
about  source-program  constructs.  T he  information  is  collected  incrementally  by 
the  analysis  phases  of  a  compiler  and  used  by  the  synthesis  phases  to  generate 
the  target  code.  Entries  in  the  symbol  table  contain  information  about  an 
identifier  such  as  its  character string  (or  lexeme),  its  type,  its  position  in  storage, 
and  any  other  relevant  information.  Symbol  tables  typically  need  to  support 
multiple  declarations  of  the  same  identifier  within  a  program. 

From  Section  1.6.1,  the  scope  of  a  declaration  is  the  portion  of  a  program 
to  which  the  declaration  applies.  We  shall  implement  scopes  by  setting  up  a 
separate  symbol  table  for  each  scope.  A  program  block  with  declarations8  will 
have  its  own  symbol  table  with  an  entry  for  each  declaration  in  the  block.  This 
approach  also  works  for  other  constructs  t h at  set  up  scopes;  for  example,  a  class 
would  have  its  own  table,  with  an  entry  for  each  field  and  method. 

This  section  contains  a  symbol-table  module  suitable  for  use  with  the  Java 
translator  fragments  in  this  chapter.  The  module  will  be  used  as  is  when  we 
put  together  t he  translator  in  Appendix  A.  Meanwhile,  for  simplicity,  t he  main 
example  of this  section  is  a  stripped-down  language  with  just  the  key  constructs 
t h at  touch  symbol  tables;  namely,  blocks,  declarations,  and  factors.  All  of  t he 
other  statement  and  expression  constructs  are  omitted  so  we  can  focus  on  the 
symbol-table  operations.  A  program  consists  of  blocks  with  optional  declara 
tions  and  "statements"  consisting  of  single  identifiers.  Each  such  statement 
represents  a  use  of  the  identifier.  Here  is  a  sample  program  in  this  language: 

{  i nt  x;  c h ar  y;  {  b o ol  y;  x;  y;  }  x;  y;  } 

(2.7) 

T he  examples  of  block  structure  in  Section  1.6.3  dealt  with  t he  definitions  and 
uses  of  names;  the  input  (2.7)  consists  solely  of  definitions  and  uses  of  names. 
The  task  we  shall  perform  is  to  print  a  revised  program,  in  which  the  decla 
rations  have  been  removed  and  each  "statement"  has  its  identifier  followed  by 
a  colon  and  its  type. 

8In  C,  for  instance,  program  blocks  are  either  functions  or  sections  of  functions  that  are 

separated  by  curly  braces  and  that  have  one  or  more  declarations  within  them. 

86 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

Who  Creates  Symbol-Table  Entries? 

Symbol-table  entries  are  created  and  used  during  the  analysis  phase  by  t he 
lexical  analyzer,  t he  parser,  and  t he  semantic  analyzer. 
In  this  chapter, 
we  have  the  parser  create  entries.  W i th  its  knowledge  of  t he  syntactic 
structure  of  a  program,  a  parser  is  often  in  a  better  position  t h an  t he 
lexical  analyzer  to  distinguish  among  different  declarations  of an  identifier. 
In  some  cases,  a  lexical  analyzer  can  create  a  symbol-table  entry  as 
soon  as  it  sees  the  characters  t h at  make  up  a  lexeme.  More  often,  the 
lexical  analyzer  can  only  return  to  t he  parser  a  token,  say  id,  along  with 
a  pointer  to  the  lexeme.  Only  the  parser,  however,  can  decide  whether  to 
use  a  previously  created  symbol-table  entry  or  create  a  new  one  for  the 
identifier. 

E x a m p le  2 . 1 4:  On  the  above  input  (2.7),  t he  goal  is  to  produce: 

{  {  x : i n t;  y r b o o l;  }  x : i n t;  y : c h a r;  } 

T he  first  x  and  y  are  from  the  inner  block  of  input  (2.7).  Since  this  use  of  x 
refers  to  t he  declaration  of  x  in  t he  outer  block,  it  is  followed  by  i n t,  t he  type 
of  t h at  declaration.  T he  use  of  y  in  the  inner  block  refers  to  the  declaration  of 
y  in  t h at  very  block  and  therefore  has  boolean  type.  We  also  see  t he  uses  of  x 
and  y  in  the  outer  block,  with  their  types,  as  given  by  declarations  of t he  outer 
block:  integer  and  character,  respectively. 

• 

2.7.1 

Symbol  Table  Per  Scope 

T he  term  "scope  of  identifier 
really  refers  to  t he  scope  of  a  particular  dec 
laration  of  x.  T he  term  scope  by  itself  refers  to  a  portion  of  a  program  t h at  is 
t he  scope  of  one  or  more  declarations. 

Scopes  are  important,  because  the  same  identifier  can  be  declared  for  differ 
ent  purposes  in  different  p a r ts  of a  program.  Common  names  like  i  and  x  often 
have  multiple  uses.  As  another  example,  subclasses  can  redeclare  a  method 
name  to  override  a  method  in  a  superclass. 

If blocks  can  be  nested,  several  declarations  of the  same  identifier  can  appear 
within  a  single  block.  T he  following  syntax  results  in  nested  blocks  when  stmts 
can  generate  a  block: 

block 

-> 

'{'  decls  stmts  '}' 

(We  quote  curly  braces  in  t he  syntax  to  distinguish  t h em  from  curly  braces  for 
semantic  actions.)  W i th  t he  g r a m m ar  in  Fig.  2.38,  decls  generates  an  optional 
sequence  of declarations  and  stmts  generates  an  optional  sequence  of statements. 

2.7. 

SYMBOL  TABLES 

87 

Optimization  of  Symbol  Tables  for  Blocks 

Implementations  of  symbol  tables  for  blocks  can  take  advantage  of  the 
most-closely  nested  rule.  Nesting  ensures  t h at  t he  chain  of  applicable 
symbol  tables  forms  a  stack.  At  t he  t op  of  t he  stack  is  t he  table  for 
t he  current  block.  Below  it  in  the  stack  are  the  tables  for  the  enclosing 
blocks.  Thus,  symbol  tables  can  be  allocated  and  deallocated  in  a  stack 
like  fashion. 

Some  compilers  maintain  a  single  hash  table  of  accessible  entries;  t h at 
is,  of  entries  t h at  are  not  hidden  by  a  declaration  in  a  nested  block.  Such 
a  hash  table  supports  essentially  constant-time  lookups,  at  t he  expense  of 
inserting  and  deleting  entries  on  block  entry  and  exit.  Upon  exit  from  a 
block  B,  the  compiler  must  undo  any  changes  to  the  hash  table  due  to 
declarations  in  block  B.  It  can  do  so  by  using  an  auxiliary  stack  to  keep 
track  of  changes  to  the  hash  table  while  block  B  is  processed. 

Moreover,  a  statement  can  be  a  block,  so  our  language  allows  nested  blocks, 
where  an  identifier  can  be  redeclared. 

T he  most-closely  nested  rule  for  blocks  is  t h at  an  identifier  x  is  in  the  scope 
of  t he  most-closely  nested  declaration  of  x;  t h at  is,  t he  declaration  of  x  found 
by  examining  blocks  inside-out,  starting  with  the  block  in  which  x  appears. 

E x a m p le  2 . 1 5:  T he  following  pseudocode  uses  subscripts  to  distinguish  a¬ 
mong  distinct  declarations  of  the  same  identifier: 

1) 
2) 
3) 
4) 
5) 

{ 

int  x i; 

int  yx; 

int  w2;  b o ol  y2; 
•  •  •  w2  ••;•••  xi 

int  z2; 

y2 

z2 

•••; 

{ 

} 

• • •  w0  • • •; 

•••  Xi 

•••  yi  • • •; 

6)  } 

T he  subscript  is  not  part  of  an  identifier;  it  is  in  fact  t he  line  number  of  t he 
declaration  t h at  applies  to  the  identifier.  Thus,  all  occurrences  of  x  are  within 
the  scope  of  the  declaration  on  line  1.  The  occurrence  of  y  on  line  3  is  in  the 
scope  of the  declaration of y  on  line  2  since  y  is  redeclared  within  the  inner  block. 
T he  occurrence  of  y  on  line  5,  however,  is  within  the  scope  of  the  declaration 
of  y  on  line  1. 

T he  occurrence  of w  on  line  5  is  presumably  within  the  scope  of a  declaration 
of  w  outside  this  program  fragment;  its  subscript  0  denotes  a  declaration  t h at 
is  global  or  external  to  this  block. 

Finally,  z  is  declared  and  used  within  the  nested  block,  but  cannot  be  used 

on  line  5,  since  t he  nested  declaration  applies  only  to  t he  nested  block. 

• 

88 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

The  most-closely  nested  rule  for  blocks  can  be  implemented  by  chaining 
symbol  tables.  T h at  is,  t he  table  for  a  nested  block  points  to  t he  table  for  its 
enclosing  block. 

E x a m p le  2 . 1 6:  Figure  2.36  shows  symbol  tables  for  the  pseudocode  in  Exam 
ple  2.15.  B\  is  for  the  block  starting  on  line  1  and 
is  for  t he  block  starting  at 
line  2.  At  the  top  of  t he  figure  is  an  additional  symbol  table  Bo  for  any  global 
or  default  declarations  provided  by  the  language.  During  the  time  t h at  we  are 
analyzing  lines  2  through  4,  the  environment  is  represented  by  a  reference  to 
the  lowest  symbol  table  —  the  one  for  B%.  When  we  move  to  line  5,  the  symbol 
table  for  B^  becomes  inaccessible,  and  the  environment  refers  instead  to  the 
symbol  table  for  B\,  from  which  we  can  reach  t he  global  symbol  table,  b ut  not 
the  table  for  B2. 

• 

Bo 

w 

Bi 

X 

i nt 

i nt 

y 

B2 

w 

i nt 

y  DOOl 
i nt 
z 

Figure  2.36:  Chained  symbol  tables  for  Example  2.15 

T he  Java  implementation  of  chained  symbol  tables  in  Fig.  2.37  defines  a 

class  Env,  short  for  environment.9  Class  Env  supports  three  operations: 

•  Create  a  new  symbol  table.  The  constructor  Env(p)  on  lines  6  through 
8  of  Fig.  2.37  creates  an  Env  object  with  a  hash  table  named  t a b l e. 
T he  object  is  chained  to  the  environment-valued  parameter  p  by  setting 
field  n e xt  to  p.  Although  it  is  t he  Env  objects  t h at  form  a  chain,  it  is 
convenient  to  talk  of t he  tables  being  chained. 

•  Put  a  new  entry  in  the  current  table.  T he  hash  table  holds  key-value 

pairs,  where: 

— T he  key  is  a  string,  or  rather  a  reference  to  a  string.  We  could 
alternatively  use  references  to  token  objects  for  identifiers  as  keys. 

-  T he  value  is  an  entry  of  class  Symbol.  T he  code  on  lines  9  through 
11  does  not  need  to  know  the  structure  of  an  entry;  t h at  is,  t he  code 
is  independent  of  t he  fields  and  methods  in  class  Symbol. 

9 "Environment"  is  another  term  for  the  collection  of  symbol  tables  that  are  relevant  at  a 

point  in  the  program. 

2.7. 

SYMBOL  TABLES 

89 

i m p o rt 

1)  p a c k a ge  s y m b o l s; 
2) 
j a v a . u t i l . *; 
3)  p u b l ic  c l a ss  Env  { 
4) 
5) 

p r i v a te  H a s h t a b le 
p r o t e c t ed  Env  p r e v; 

t a b l e; 

//  File  Env.java 

6) 

7) 

8) 

9) 

10) 

11) 

12) 
13) 
14) 
15) 
16) 
17) 
18) 
19)  } 

p u b l ic  Env(Env  p)  { 

t a b le  =  new  H a s h t a b l e O;  p r ev  =  p; 

> 

p u b l ic  v o id  p u t ( S t r i ng  s,  Symbol  sym)  { 

t a b l e . p u t ( s,  sym); 

> 

p u b l ic  Symbol  g e t ( S t r i ng  s)  { 

f o r(  Env  e  =  t h i s;  e  !=  n u l l;  e  =  e . p r ev  )  { 
( S y m b o l ) ( e . t a b l e . g e t ( s ) ); 

Symbol  found  = 
i f(  found 

!=  n u ll  ) 

r e t u rn  f o u n d; 

} 
r e t u rn  n u l l; 

} 

Figure  2.37:  Class  Env  implements  chained  symbol  tables 

•  Get  an  entry  for  an  identifier  by  searching  the  chain  of  tables,  starting 
with  the  table  for  the  current  block.  T he  code  for  this  operation  on  lines 
12  through  18  returns  either  a  symbol-table  entry  or  n u l l. 

Chaining  of  symbol  tables  results  in  a  tree  structure,  since  more  t h an  one 
block  can  be  nested  inside  an  enclosing  block.  T he  dotted  lines  in  Fig.  2.36  are 
a  reminder  t h at  chained  symbol  tables  can  form  a  tree. 

2.7.2  The  Use  of  Symbol  Tables 

In  effect,  t he  role  of  a  symbol  table  is  to  pass  information  from  declarations  to 
uses.  A  semantic  action  "puts"  information  about  identifier  x  into  t he  symbol 
table,  when  the  declaration  of  x  is  analyzed.  Subsequently,  a  semantic  action 
associated  with  a  production  such  as  factor  ->•  id  "gets"  information  about 
t he  identifier  from  t he  symbol  table.  Since  the  translation  of  an  expression 
Ei  op  E2,  for  a  typical  operator  o p,  depends  only  on  t he  translations  of  E\  and 
E2,  and  does  not  directly  depend  on  the  symbol  table,  we  can  add  any  number 
of  operators  without  changing  the  basic  flow  of  information  from  declarations 
to  uses,  through  t he  symbol  table. 

E x a m p le  2 . 1 7:  T he  translation  scheme  in  Fig.  2.38  illustrates  how  class  Env 
can  be  used.  T he  translation  scheme  concentrates  on  scopes,  declarations,  and 

90 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

uses.  It  implements  the  translation  described  in  Example  2.14.  As  noted  earlier, 
on  input 

program 

->• 

{  top  =  null;  } 

block 

block 

-» 

{  saved  =  top; 

top  =  n ew  Env(top); 
p r i n t ( "{  " );  } 

decls  stmts  '}' 

{  top  =  saved; 

printO'}  "); } 

decls  —> 
I 

decls  decl 

e 

decl 

-»• 

t y pe  id  ; 

{  s  =  n ew  Symbol; 

s.type  =  t y p e, lexeme 
top.put (id. lexeme,  s);  } 

stmts 

-» 

stmts  stmt 

stmt 

->• 
| 

6/ocA; 
factor  ; 

{  p r i n t ( ";  " );  } 

factor 

-> 

id 

{ 

top.get(id.lexeme); 

s  — 
print  (id.  lexeme); 

p r i n t ( " : " );  } 
print  (s.type); 

Figure  2.38:  T he  use  of  symbol  tables  for  translating  a  language  with  blocks 

{ 

i nt  x;  c h ar  y;  {  b o ol  y;  x;  y;  }  x;  y;  } 

t he  translation  scheme  strips  t he  declarations  and  produces 

{  {  x : i n t;  y : b o o l;  }  x : i n t;  y : c h a r;  } 

Notice  t h at  the  bodies  of  t he  productions  have  been  aligned  in  Fig.  2.38 
so  t h at  all  t he  g r a m m ar  symbols  appear  in  one  column,  and  all  t he  actions  in 
a  second  column.  As  a  result,  components  of  t he  body  are  often  spread  over 
several  lines. 

Now,  consider  the  semantic  actions.  T he  translation  scheme  creates  and 
discards  symbol  tables  upon  block  entry  and  exit,  respectively.  Variable  top 
denotes  the  t op  table,  at  t he  head  of  a  chain  of  tables.  T he  first  production  of 

2.8. 

INTERMEDIATE  CODE  GENERATION 

91 

the  underlying  g r a m m ar  is  program  ->•  block.  T he  semantic  action  before  block 
initializes  top  to  null,  with  no  entries. 
T he  second  production,  block  -» 

'{'  decls stmts'}',  has  actions  upon  block 
entry  and  exit.  On  block  entry,  before  decls,  a  semantic  action  saves  a  reference 
to  t he  current  table  using  a  local  variable  saved.  Each  use  of  this  production 
has  its  own  local  variable  saved,  distinct  from  the  local  variable  for  any  other 
use  of  this  production. 
In  a  recursive-descent  parser,  saved  would  be  local  to 
the  procedure  for  block.  The  treatment  of  local  variables  of  a  recursive  function 
is  discussed  in  Section  7.2.  T he  code 

top  =  n ew  Env (top); 

sets  variable  top  to  a  newly  created  new  table  t h at  is  chained  to  t he  previous 
value  of  top  just  before  block  entry.  Variable  top  is  an  object  of  class  Env;  the 
code  for  the  constructor  Env  appears  in  Fig.  2.37. 

On  block  exit,  after  ' } ',  a  semantic  action  restores  top  to  its  value  saved  on 
block  entry.  In  effect,  the  tables  form  a  stack;  restoring  top  to  its  saved  value 
pops  t he  effect  of  the  declarations  in  the  b l o c k .10  Thus,  t he  declarations  in  t he 
block  are  not  visible  outside  the  block. 

A  declaration,  decls  ->•  t y pe  id  results  in  a  new  entry  for  the  declared  iden 
tifier.  We  assume  t h at  tokens  t y pe  and  id  each  have  an  associated  attribute, 
which  is  the  type  and  lexeme,  respectively,  of  the  declared  identifier.  We  shall 
not  go  into  all  the  fields  of  a  symbol  object  s,  but  we  assume  t h at  there  is  a 
field  type  t h at  gives  the  type  of  the  symbol.  We  create  a  new  symbol  object  s 
and  assign  its  type  properly  by  s.type  —  type.lexeme.  T he  complete  entry  is 
put  into  the  top  symbol  table  by  top.put(\d.lexeme,  s). 

T he  semantic  action  in  the  production  factor  ->  id  uses  t he  symbol  table 
to  get  the  entry  for  the  identifier.  T he  get  operation  searches  for  the  first  entry 
in  t he  chain  of  tables,  starting  with  top.  The  retrieved  entry  contains  any 
• 
information  needed  about  t he  identifier,  such  as  the  type  of  the  identifier. 

2.8 

Intermediate  Code  Generation 

The  front  end  of  a  compiler  constructs  an  intermediate  representation  of  the 
source  program  from  which  the  back  end  generates  the  target  program. 
In 
this  section,  we  consider  intermediate  representations  for  expressions  and  state 
ments,  and  give  tutorial  examples  of  how  to  produce  such  representations. 

2.8.1  Two  Kinds  of Intermediate  Representations 

As  was  suggested  in  Section  2.1  and  especially  Fig.  2.4,  t he  two  most  important 
intermediate  representations  are: 

1 0I n s t e ad  of  explicitly  saving  and  restoring  tables,  we  could  alternatively  add  static  opera 

tions  push  and  pop  to  class Env. 

92 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

•  Trees,  including  parse  trees  and  (abstract)  syntax  trees. 

•  Linear  representations,  especially  "three-address  code." 

Abstract-syntax  trees,  or  simply  syntax  trees,  were  introduced  in  Section 
2.5.1,  and  in  Section  5.3.1  they  will  be  reexamined  more  formally.  During 
parsing,  syntax-tree  nodes  are  created  to  represent  significant  programming 
constructs.  As  analysis  proceeds,  information  is  added  to  t he  nodes  in  the  form 
of  attributes  associated  with  t he  nodes.  T he  choice  of  attributes  depends  on 
the  translation  to  be  performed. 

Three-address  code,  on  the  other  hand,  is  a  sequence  of elementary  program 
steps,  such  as  the  addition  of two  values.  Unlike  the  tree,  there  is  no  hierarchical 
structure.  As  we  shall  see  in  Chapter  9,  we  need  this  representation  if  we  are 
to  do  any  significant  optimization  of  code. 
In  t h at  case,  we  break  the  long 
sequence  of  three-address  statements  t h at  form  a  program  into  "basic  blocks," 
which  are  sequences  of statements  t h at  are  always  executed  one-after-the-other, 
with  no  branching. 

In  addition  to  creating  an  intermediate  representation,  a  compiler  front  end 
checks  t h at  the  source  program  follows  the  syntactic  and  semantic  rules  of  t he 
in  general  "static" 
source  language.  This  checking  is  called  static  checking; 
means  "done  by  t he  compiler."11  Static  checking  assures  t h at  certain  kinds 
of  programming  errors,  including  type  mismatches,  are  detected  and  reported 
during  compilation. 

It  is  possible  t h at  a  compiler  will  construct  a  syntax  tree  at  the  same  time 
it  emits  steps  of  three-address  code.  However,  it  is  common  for  compilers  to 
emit  t he  three-address  code  while  t he  parser  "goes  through  the  motions"  of 
constructing  a  syntax  tree,  without  actually  constructing  the  complete  tree 
d a ta  structure.  Rather,  the  compiler  stores  nodes  and  their  attributes  needed 
for  semantic  checking  or  other  purposes,  along  with  the  d a ta  structure  used  for 
parsing.  By  so  doing,  those  parts  of t he  syntax tree  t h at  are  needed  to  construct 
the  three-address  code  are  available  when  needed,  but  disappear  when  no  longer 
needed.  We  take  up  the  details  of  this  process  in  Chapter  5. 

2.8.2  Construction  of  Syntax  Trees 

We  shall  first  give  a  translation  scheme  t h at  constructs  syntax  trees,  and  later, 
in  Section  2.8.4,  show  how  the  scheme  can  be  modified  to  emit  three-address 
code,  along  with,  or  instead  of,  the  syntax  tree. 

Recall  from  Section  2.5.1  t h at  the  syntax  tree 

11 Its  opposite,  "dynamic,"  means  "while  the  program  is  running."  Many  languages  also 
make  certain  dynamic  checks.  For  instance,  an  object-oriented  language  like  Java  sometimes 
must  check  types  during  program  execution,  since  the  method  applied  to  an  object  may 
depend  on  the  particular  subclass  of the  object. 

2.8. 

INTERMEDIATE  CODE  GENERATION 

93 

op 

/ 

E\ 

\ 
E2 

represents  an  expression  formed  by  applying  t he  operator  op  to  the  subexpres 
sions  represented  by  E\  and  E2.  Syntax  trees  can  be  created  for  any  construct, 
not  just  expressions.  Each  construct  is  represented  by  a  node,  with  children 
for  t he  semantically  meaningful  components  of  the  construct.  For  example,  t he 
semantically  meaningful  components  of  a  C  while-statement: 

w h i le  (  expr  )  stmt 

are  t he  expression  expr  and  the  statement  stmt.12  The  syntax-tree  node  for  such 
a  while-statement  has  an  operator,  which  we  call  w h i l e,  and  two  children—the 
syntax  trees  for  the  expr  and  the  stmt. 

T he  translation  scheme  in  Fig.  2.39  constructs  syntax  trees  for  a  repre 
sentative,  but  very  limited,  language  of  expressions  and  statements.  All  the 
nonterminals  in  t he  translation  scheme  have  an  a t t r i b u te  n,  which  is  a  node  of 
the  syntax  tree.  Nodes  are  implemented  as  objects  of  class  Node. 

Class  Node  has  two  immediate  subclasses:  Expr  for  all  kinds  of  expressions, 
and  Stmt for  all  kinds  of statements.  Each t y pe  of statement  has  a  corresponding 
subclass  of  Stmt;  for  example,  operator  w h i le  corresponds  to  subclass  While. 
A  syntax-tree  node  for  operator  w h i le  with  children  x  and  y  is  created  by  t he 
pseudocode 

n ew  While  (x,y) 

which  creates  an  object  of  class  While  by  calling  constructor  function  While, 
with  t he  same  name  as  t he  class.  Just  as  constructors  correspond  to  operators, 
constructor  parameters  correspond  to  operands  in  the  abstract  syntax. 

W h en  we  study  t he  detailed  code  in  Appendix  A,  we  shall  see  how  methods 
In  this  section,  we 

are  placed  where  they  belong  in  this  hierarchy  of  classes. 
shall  discuss  only  a  few  of  the  methods,  informally. 

We  shall  consider  each  of  t he  productions  and  rules  of  Fig.  2.39,  in  t u r n. 
First,  the  productions  defining  different  types  of  statements  are  explained,  fol 
lowed  by  t he  productions  t h at  define  our  limited  types  of  expressions. 

S y n t ax  T r e es  for  S t a t e m e n ts 

For  each  statement  construct,  we  define  an  operator  in  the  abstract  syntax.  For 
constructs  t h at  begin  with  a  keyword,  we  shall  use  t he  keyword  for  the  operator. 
Thus,  there  is  an  operator  w h i le  for  while-statements  and  an  operator  do  for 
do-while  statements.  Conditionals  can  be  handled  by  defining  two  operators 

1 2T he  right  parenthesis  serves  only  to  separate  the  expression  from  the  statement.  The  left 
parenthesis  actually  has  no  meaning;  it  is  there  only  to  please  the  eye,  since  without  it,  C 
would  allow  unbalanced  parentheses. 

94 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

program 

-»  block 

return  block.n;  } 

block  —»•  '{' 

stmts 

'}' 

block.n  =  stmts.n;  } 

stmts 

stmt 

-y 
I 

-» 
| 

stmtsi 
e 

stmt 

stmts.n  =  n ew  Seq(stmtsi.n,  stmt.n)] 
stmts.n  =  null;  } 

} 

expr  ; 

stmt.n  =  n ew  Eval(expr.n); 

} 

if  (  expr  )  stmti 

stmt.n  =  n ew 

If(expr.n,stmti.n); 

} 

w h i le  (  expr  ) 

stmti 

do  stmt\  w h i le 

block 

stmt.n  =  n ew  While  (expr.n,  stmti.n);  } 
(  expr  ); 
stmt.n  =  n ew  Do  (stmti.n,  expr.n);  } 
stmt.n  =  block.n;  } 

expr  —»•  rel  -  exprx 

I 

rel 

expr.n  =  n ew  Assign  ( ' = ',  re/.n,  errpr^.n);  } 
expr.n  =  rein;  } 

rel  ->  rel\  <  a 
rek  <= 

| 

rein  =  n ew  Rel('<',  reli.n,  add.n);  } 
rein  =  n ew  Rel('<',  reli.n,  add.n);  } 
re/.n  =  add.n;  } 

add  -»  ftrfrfi  +  ierw 

| 

term 

add.n  =  n ew  0 p ( ' + ',  addi.n,  term.n);  } 

.n  =  term.n;  } 

term 

-> 
| 

iermi  *  factor 

factor 

term.n  =  n ew 
term.n  =  factor.n;  } 

0p('*',termi.n,factor.n); 

} 

factor 

(  ezpr  ) 
n um 

factor.n  =  expr.n;  } 
factor.n  =  n ew  Num  (num.value);  } 

Figure  2.39:  Construction  of  syntax  trees  for  expressions  and  statements 

2.8. 

INTERMEDIATE  CODE  GENERATION 

95 

ifelse  and  if for  if-statements  with  and  without  an  else  part,  respectively.  In  our 
simple  example  language,  we  do  not  use  else,  and  so  have  only  an  if-statement. 
Adding  e l se  presents  some  parsing  issues,  which  we  discuss  in  Section  4.8.2. 

Each  statement  operator  has  a  corresponding  class  of  the  same  name,  with 
In  addition,  we  define 
a  capital  first  letter;  e.g.,  class  If  corresponds  to  if. 
the  subclass  Seq,  which  represents  a  sequence  of  statements.  This  subclass 
corresponds  to  the  nonterminal  stmts  of t he  grammar.  Each  of  these  classes  are 
subclasses  of  Stmt,  which  in  t u rn  is  a  subclass  of  Node. 

T he  translation  scheme  in  Fig.  2.39  illustrates  t he  construction  of  syntax-

tree  nodes.  A  typical  rule  is  t he  one  for  if-statements: 

stmt 

->• 

if  (  expr  )  stmti 

{  stmt.n  =  n ew  If (expr.n,  stmt\.n);  } 

T he  meaningful  components  of  the  if-statement  are  expr  and  stmt\.  The  se 
mantic  action  defines  the  node  stmt.n  as  a  new  object  of  subclass  If.  T he  code 
for  the  constructor  //  is  not  shown.  It  creates  a  new  node  labeled  if  with  t he 
nodes  expr.n  and  stmt\.n  as  children. 

Expression  statements  do  not  begin  with  a  keyword,  so  we  define  a  new  op 
erator  eval  and  class  Eval,  which  is  a  subclass  of  Stmt,  to  represent  expressions 
t h at  are  statements.  T he  relevant  rule  is: 

stmt 

-> 

expr  ; 

{  stmt.n  =  n ew  Eval (expr.n);  } 

R e p r e s e n t i ng  B l o c ks  in  S y n t ax  T r e es 

T he  remaining  statement  construct  in  Fig.  2.39  is  t he  block,  consisting  of  a 
sequence  of  statements.  Consider  the  rules: 

stmt  -»  block 
-» 
block 

'{'  stmts  '}' 

{  stmt.n  =  block.n;  } 
{  block.n  =  stmts.n;  } 

T he  first  says  t h at  when  a  statement  is  a  block,  it  has  the  same  syntax  tree  as 
t he  block.  The  second  rule  says  t h at  t he  syntax  tree  for  nonterminal  block  is 
simply  t he  syntax  tree  for  the  sequence  of  statements  in  the  block. 

For  simplicity,  t he  language  in  Fig.  2.39  does  not  include  declarations.  Even 
when  declarations  are  included  in  Appendix  A,  we  shall  see  t h at  t he  syntax 
tree  for  a  block  is  still  t he  syntax  tree  for  the  statements  in  the  block.  Since 
information  from  declarations  is  incorporated  into  the  symbol  table,  they  are 
not  needed  in  t he  syntax  tree.  Blocks,  with  or  without  declarations,  therefore 
appear  to  be  just  another  statement  construct  in  intermediate  code. 

A  sequence  of  statements  is  represented  by  using  a  leaf  null  for  an  empty 

statement  and  a  operator  s eq  for  a  sequence  of  statements,  as  in 

stmts 

-*• 

stmtsi  stmt 

{  stmts.n  =  n ew  Seq(stmts1.n,  stmt.n);  } 

96 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

E x a m p le  2 . 1 8:  In  Fig.  2.40  we  see  p a rt  of  a  syntax  tree  representing  a  block 
or  statement  list.  There  are  two  statements  in  the  list,  t he  first  an  if-statement 
and  the  second  a  while-statement.  We  do  not  show  t he  portion  of  t he  tree 
above  this  statement  list,  and  we  show  only  as  a  triangle  each  of  t he  necessary 
subtrees:  two  expression  trees  for  the  conditions  of the  if-  and  while-statements, 
and  two  statement  trees  for  their  substatements. 

• 

Figure  2.40:  P a rt  of  a  syntax  tree  for  a  statement  list  consisting  of  an  if-
statement  and  a  while-statement 

S y n t ax  T r e es  for  E x p r e s s i o ns 

Previously,  we  handled  the  higher  precedence  of  *  over  +  by  using  three  non 
terminals  expr,  term,  and  factor.  T he  number  of  nonterminals  is  precisely  one 
plus  t he  number  of  levels  of  precedence  in  expressions,  as  we  suggested  in  Sec 
tion  2.2.6.  In  Fig.  2.39,  we  have  two  comparison  operators,  <  and  <=  at  one 
precedence  level,  as  well  as  the  usual  +  and  *  operators,  so  we  have  added  one 
additional  nonterminal,  called  add. 

Abstract  syntax  allows  us  to  group  "similar"  operators  to  reduce  the  number 
of  cases  and  subclasses  of  nodes  in  an  implementation  of  expressions.  In  this 
chapter,  we  take  "similar"  to  mean  t h at  t he  type-checking  and  code-generation 
rules  for  the  operators  are  similar.  For  example,  typically  the  operators  +  and  * 
can  be  grouped,  since  they  can  be  handled  in  the  same  way —  their  requirements 
regarding  the  types  of  operands  are  t he  same,  and  they  each  result  in  a  single 
three-address  instruction  t h at  applies  one  operator  to  two  values.  In  general, 
the  grouping  of  operators  in  t he  abstract  syntax  is  based  on  t he  needs  of  t he 
later  phases  of t he  compiler.  T he  table  in  Fig.  2.41  specifies  the  correspondence 
between  t he  concrete  and  abstract  syntax  for  several  of t he  operators  of  Java. 
In  t he  concrete  syntax,  all  operators  are  left  associative,  except  t he  assign 
ment  operator  =,  which  is  right  associative.  The  operators  on  a  line  have  t he 

2.8. 

INTERMEDIATE  CODE  GENERATION 

97 

C O N C R E TE  S Y N T AX 

= 
11 
&& 
==  ! = 
<=  >=  > 

+  -
*  /  •/. 
j 

~  unary 
[] 

A B S T R A CT  S Y N T AX 
a s s i gn 
c o nd 
c o nd 
rel 
rel 
op 
op 
n ot 
m i n us 
a c c e ss 

Figure  2.41:  Concrete  and  abstract  syntax  for  several  Java  operators 

same  precedence;  t h at  is,  ==  and  !=  have  the  same  precedence.  T he  lines  are 
in  order  of increasing  precedence;  e.g.,  ==  has  higher  precedence  t h an  t he  oper 
ators  &&  and  =.  The  subscript  unary  in  -  unary  is  solely  to  distinguish  a  leading 
unary  minus  sign,  as  in  - 2,  from  a  binary  minus  sign,  as  in  2- a.  T he  operator 
[]  represents  array  access,  as  in  a[ i ]. 

T he  abstract-syntax  column  specifies  the  grouping  of operators.  The  assign 
ment  operator  =  is  in  a  group  by  itself.  The  group  c o nd  contains  the  conditional 
boolean  operators &&  and  I  I.  T he  group  rel  contains  the  relational  comparison 
operators  on  the  lines  for  ==  and  <.  T he  group  op  contains  t he  arithmetic 
operators  like  +  and  *.  Unary  minus,  boolean  negation,  and  array  access  are  in 
groups  by  themselves. 

The  mapping  between  concrete  and  abstract  syntax  in  Fig.  2.41  can  be 
implemented  by  writing  a  translation  scheme.  T he  productions  for  nonterminals 
expr,  rel,  add, 
term,  and  factor  in  Fig.  2.39  specify  the  concrete  syntax  for  a 
representative  subset  of  the  operators  in  Fig.  2.41.  The  semantic  actions  in 
these  productions  create  syntax-tree  nodes.  For  example,  t he  rule 

term  —b 

termi  *  factor 

{  term.n  =  n ew  O p ( V, t e r m \ . n , f a c t o r . n );  } 

creates  a  node  of  class  Op,  which  implements  the  operators  grouped  under  op 
in  Fig.  2.41.  The  constructor  Op  has  a  parameter  '*'  to  identify  the  actual 
operator,  in  addition  to  the  nodes  termy.n  and  factor.n  for  t he  subexpressions. 

2.8.3 

Static  Checking 

Static  checks  are  consistency  checks  t h at  are  done  during  compilation.  Not  only 
do  they  assure  t h at  a  program  can  be  compiled  successfully,  but  they  also  have 
the  potential  for  catching  programming  errors  early,  before  a  program  is  run. 
Static  checking  includes: 

•  Syntactic  Checking.  There  is  more  to  syntax  t h an  grammars.  For  ex 
ample,  constraints  such  as  an  identifier  being  declared  at  most  once  in  a 

98 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

scope,  or  t h at  a  break  statement  must  have  an  enclosing  loop  or  switch 
statement,  are  syntactic,  although  they  are  not  encoded  in,  or  enforced 
by,  a  grammar  used  for  parsing. 

•  Type  Checking.  T he  type  rules  of  a  language  assure  t h at  an  operator  or 
function  is  applied  to  t he  right  number  and  type  of operands.  If conversion 
between  types  is  necessary,  e.g.,  when  an  integer  is  added  to  a  float,  then 
the  type-checker  can  insert  an  operator  into  t he  syntax  tree  to  represent 
t h at  conversion.  We  discuss  type  conversion,  using  t he  common  t e rm 
"coercion,"  below. 

L-values  a nd  R - v a l u es 

We  now  consider  some  simple  static  checks  t h at  can  be  done  during  t he  con 
struction  of a  syntax  tree  for  a source  program.  In  general,  complex  static  checks 
may  need  to  be  done  by  first  constructing  an  intermediate  representation  and 
then  analyzing  it. 

There  is  a  distinction  between  t he  meaning  of  identifiers  on  t he  left  and 

right  sides  of  an  assignment.  In  each  of  t he  assignments 

i  =  5; 
i  =  i  +  1; 

the  right  side  specifies  an  integer  value,  while  t he  left  side  specifies  where  t he 
value  is  to  be  stored.  T he  terms  l-value  and  r-value  refer  to  values  t h at  are 
appropriate  on  t he  left  and  right  sides  of  an  assignment,  respectively.  T h at  is, 
r-values  are  what  we  usually  think  of  as  "values,"  while  /-values  are  locations. 
Static  checking  must  assure  t h at  the  left  side  of  an  assignment  denotes  an 
/-value.  An  identifier  like  i  has  an  /-value,  as  does  an  array  access  like  a [ 2 ]. 
But  a  constant  like  2  is  not  appropriate  on  the  left  side  of  an  assignment,  since 
it  has  an  r-value,  but  not  an  /-value. 

T y pe  C h e c k i ng 

Type  checking  assures  t h at  the  type  of  a  construct  matches  t h at  expected  by 
its  context.  For  example,  in  the  if-statement 

if  (  expr  )  stmt 

the  expression  expr  is  expected  to  have  type  b o o l e a n. 

Type  checking  rules  follow  t he  o p e r a t o r / o p e r a nd  structure  of  the  abstract 
syntax.  Assume  the  operator  rel  represents  relational  operators  such  as  <=. 
T he  type  rule  for  t he  operator  group  rel  is  t h at  its  two  operands  must  have  the 
same  type,  and  the  result  has  type  boolean.  Using  a t t r i b u te  type  for  t he  type 
of  an  expression,  let  E  consist  of  rel  applied  to  Ei  and  E2.  T he  t y pe  of  E  can 
be  checked  when  its  node  is  constructed,  by  executing  code  like  t he  following: 

2.8. 

INTERMEDIATE  CODE  GENERATION 

99 

if  (  Ei.type  ==  E2.type  )  E.type  =  boolean; 
e l se  error; 

T he  idea  of  matching  actual  with  expected  types  continues  to  apply,  even 

in  the  following  situations: 

•  Coercions.  A  coercion  occurs  if  the  type  of  an  operand  is  automatically 
converted  to  the  type  expected  by  the  operator. 
In  an  expression  like 
2  *  3 . 1 4,  the  usual  transformation  is  to  convert  the  integer  2  into  an 
equivalent  floating-point  number,  2 . 0,  and  then  perform  a  floating-point 
operation  on  the  resulting  pair  of  floating-point  operands.  T he  language 
definition  specifies  the  allowable  coercions.  For  example,  the  actual  rule 
for  rel  discussed  above  might  be  t h at  Ei.type  and  E2.type  are  convertible 
In  t h at  case,  it  would  be  legal  to  compare,  say,  an 
to  t he  same  type. 
integer  with  a  float. 

•  Overloading.  T he  operator  +  in  Java  represents  addition  when  applied 
to  integers;  it  means  concatenation  when  applied  to  strings.  A  symbol  is 
said  to  be  overloaded  if  it  has  different  meanings  depending  on  its  context. 
Thus,  +  is  overloaded  in  Java.  T he  meaning  of  an  overloaded  operator  is 
determined  by  considering  the  known  types  of  its  operands  and  results. 
For  example,  we  know  t h at  t he  +  in  z = x + y  is  concatenation  if  we  know 
t h at  any  of  x,  y,  or  z  is  of  type  string.  However,  if  we  also  know  t h at 
another  one  of  these  is  of  type  integer,  then  we  have  a  type  error  and 
there  is  no  meaning  to  this  use  of  +. 

2.8.4  Three-Address  Code 

Once  syntax  trees  are  constructed,  further  analysis  and  synthesis  can  be  done 
by  evaluating  attributes  and  executing  code  fragments  at  nodes  in  the  tree. 
We  illustrate  t he  possibilities  by  walking  syntax  trees  to  generate  three-address 
code.  Specifically,  we  show  how  to  write  functions  t h at  process  the  syntax  tree 
and,  as  a  side-effect,  emit  the  necessary  three-address  code. 

T h r e e - A d d r e ss  I n s t r u c t i o ns 

Three-address  code  is  a  sequence  of  instructions  of  the  form 

x  -  y  op  z 

where  x,  y,  and  z are  names,  constants,  or  compiler-generated  temporaries;  and 
op  stands  for  an  operator. 

Arrays  will  be  handled  by  using  t he  following  two  variants  of  instructions: 

x  [  y  ]  -  z 
x =  y  [  z 1 

100 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

T he  first  p u ts  the  value  of  z  in  t he  location  x[y],  and  the  second  p u ts  t he  value 
of  y[z]  in  t he  location  x. 

Three-address  instructions  are  executed  in  numerical  sequence  unless  forced 
to  do  otherwise  by  a  conditional  or  unconditional j u m p.  We  choose  the  following 
instructions  for  control  flow: 

if False  x goto L  if  £  is  false,  next  execute  t he  instruction  labeled L 
if  True  x goto L  if  rc  is  true,  next  execute  the  instruction  labeled L 
goto L 

next  execute  the  instruction  labeled L 

A  label  L  can  be  attached  to  any  instruction  by  prepending  a  prefix  L:.  An 
instruction  can  have  more  t h an  one  label. 

Finally,  we  need  instructions  t h at  copy  a  value.  T he  following  three-address 

instruction  copies  the  value  of  y  into  x: 

x=  y 

T r a n s l a t i on  of  S t a t e m e n ts 

Statements  are  translated  into  three-address  code  by  using  j u mp  instructions 
to  implement  t he flow of control  through  t he  statement.  T he  layout  in  Fig.  2.42 
illustrates  t he  translation  of  if  expr  t h en  stmti.  T he  j u mp  instruction  in  t he 
layout 

if False  x goto  after 

j u m ps  over  t he  translation  of  stmti  if  expr  evaluates  to  false.  Other  statement 
constructs  are  similarly  translated  using  appropriate j u m ps  around  t he  code  for 
their  components. 

code  to  compute 
expr  into  x 

if False  x goto  after 

code  for  stmti 

after—*-  ; 

Figure  2.42:  Code  layout  for  if-statements 

For  concreteness,  we  show  t he  pseudocode  for  class  If in  Fig.  2.43.  Class 
If is  a  subclass  of  Stmt,  as  are  t he  classes  for  t he  other  statement  constructs. 
Each  subclass  of  Stmt  has  a  constructor  —  // in  this  case  —  and  a  function  gen 
t h at  is  called  to  generate  three-address  code  for  this  kind  of  statement. 

2.8. 

INTERMEDIATE  CODE  GENERATION 

101 

c l a ss  //  e x t e n ds  Stmt  { 

Expr  E;  Stmt  S; 
p u b l ic  If (Expr  x,  Stmt  y)  {  E  =  x;  S  =  y;  after  =  newlabelQ;  } 
p u b l ic  v o id  gen()  { 

Expr  n  =  E.rvalueQ; 
emit(  "ifFalse "  +  n.toStringQ  +  " goto "  +  after); 
S.genQ; 
emit (after  + 

":"); 

} 

Figure  2.43:  Function  gen  in  class  / / g e n e r a t es  three-address  code 

T he  constructor  // in  Fig.  2.43  creates  syntax-tree  nodes  for  if-statements. 
It  is  called  with  two  parameters,  an  expression  node  x  and  a  statement  node 
y,  which  it  saves  as  attributes  E  and  5.  T he  constructor  also  assigns  a t t r i b u te 
after  a  unique  new  label,  by  calling  function  newlabelQ.  T he  label  will  be  used 
according  to  the  layout  in  Fig.  2.42. 

Once  t he  entire  syntax  tree  for  a  source  program  is  constructed,  t he  function 
gen  is  called  at  the  root  of  the  syntax  tree.  Since  a  program  is  a  block  in 
our  simple  language,  the  root  of  the  syntax  tree  represents  the  sequence  of 
statements  in  the  block.  All  statement  classes  contain  a  function  gen. 

T he  pseudocode  for  function  gen  of  class  / / in  Fig.  2.43  is  representative.  It 
calls  E.rvalueQ  to  translate  the  expression  E  (the  boolean-valued  expression 
t h at  is  p a rt  of  the  if-statements)  and  saves  the  result  node  returned  by  E. 
Translation  of  expressions  will  be  discussed  shortly.  Function  gen  then  emits  a 
conditional  j u mp  and  calls  S.genQ  to  translate  t he  substatement  S. 

T r a n s l a t i on  of  E x p r e s s i o ns 

We  now  illustrate  the  translation  of  expressions  by  considering  expressions  con 
taining  binary  operators  o p,  array  accesses,  and  assignments,  in  addition  to 
constants  and  identifiers.  For  simplicity,  in  an  array  access  y[z],  we  require  t h at 
y  be  an  identifier.13  For  a  detailed  discussion  of  intermediate  code  generation 
for  expressions,  see  Section  6.4. 

We  shall  take  t he  simple  approach  of  generating  one  three-address  instruc 
tion  for  each  operator  node  in  the  syntax  tree  for  an  expression.  No  code  is 
generated  for  identifiers  and  constants,  since  they  can  appear  as  addresses  in 
instructions.  If  a  node  x  of  class  Expr  has  operator  o p,  then  an  instruction  is 
emitted  to  compute  the  value  at  node  x  into  a  compiler  generated  "temporary" 
name,  say  t.  Thus,  i - j +k  translates  into  two  instructions 

1 3T h is  simple  language  supports a[a[n]],  but  not a[m] [n].  Note  that a[a[n]]  has  the 

form a [£?], where E is a [n]. 

102 

CHAPTER 

2. 

A 

SIMPLE 

SYNTAX-DIRECTED 

TRANSLATOR 

i  - 

j 
tl  = 
t2  =  tl  +  k 

W i th  array  accesses  and  assignments  comes  the  need  to  distinguish  between 
/-values  and  r-values.  For  example,  2* a[ i]  can  be  translated  by  computing  the 
r-value  of  a[ i]  into  a  temporary,  as  in 

[ 

tl  =  a 
t2  =  2  *  tl 

i  ] 

But,  we  cannot  simply  use  a  temporary  in  place  of  a[ i ],  if  a[ i]  appears  on 
t he  left  side  of  an  assignment. 

T he  simple  approach  uses  t he  two  functions  lvalue  and  rvalue,  which  appear 
in  Fig.  2.44  and  2.45,  respectively.  When  function  rvalue  is  applied  to  a  nonleaf 
node  x,  it  generates  instructions  to  compute  x  into  a  temporary,  and  returns 
a  new  node  representing  t he  temporary.  When  function  lvalue  is  applied  to  a 
nonleaf,  it  also  generates  instructions  to  compute  t he  subtrees  below  x,  and 
returns  a  node  representing  t he  "address"  for  x. 

We  describe  function  lvalue  first,  since  it  has  fewer  cases.  W h en  applied 
to  a  node  x,  function  lvalue  simply  returns  x  if  it  is  the  node  for  an  identifier 
(i.e.,  if  x  is  of  class  Id). 
In  our  simple  language,  t he  only  other  case  where 
an  expression  has  an  /-value  occurs  when  x  represents  an  array  access,  such  as 
In  this  case,  x  will  have  t he  form  Access(y,  z),  where  class  Access  is  a 
a[ i ]. 
subclass  of  Expr,  y  represents  t he  name  of  t he  accessed  array,  and  z  represents 
the  offset  (index)  of  the  chosen  element  in  t h at  array.  From  the  pseudo-code 
in  Fig.  2.44,  function  lvalue  calls  rvalue(z)  to  generate  instructions,  if  needed, 
to  compute  the  r-value  of  z.  It  then  constructs  and  returns  a  new  Access  node 
with  children  for  t he  array  name  y  and  t he  r-value  of  z. 

Expr  lvalue(x  :  Expr)  { 

if  (  x  is  an  Id  node  )  r e t u rn  x; 
e l se  if  (  x  is  an  Access (y,  z)  node  and  y  is  an  Id  node  )  { 

r e t u rn  n ew  Access(y,  rvalue(z)); 

} 
e l se  error; 

} 

Figure  2.44:  Pseudocode  for  function  lvalue 

E x a m p le  2 . 1 9:  When  node  x  represents  t he  array  access  a[ 2* k ],  the  call 
lvalue(x)  generates  an  instruction 

t  =  2  *  k 

and  returns  a  new  node  x'  representing  t he  /-value  a[ t ],  where  t  is  a  new 
temporary  name. 

In  detail,  t he  code  fragment 

2.8. 

INTERMEDIATE  CODE  GENERATION 

103 

r e t u rn  n ew  Access(y,  rvalue(z)); 

is  reached  with  y  being  t he  node  for  a  and  z  being  t he  node  for  expression  2*k. 
T he  cail  rvalue(z)  generates  code  for  the  expression  2*k  (i.e.,  t he  three-address 
statement  t  =  2  *  k)  and  returns  the  new  node  z'  representing  the  t e m p o r a ry 
name  t.  T h at  node  z'  becomes  the  value  of  the  second  field  in  the  new  Access 
node  x'  t h at  is  created. 

• 

Expr  rvalue(x  :  Expr)  { 

if  (  x  is  an  Id  or  a  Constant  node  )  r e t u rn  x; 
e l se  if  (  x  is  an  Op(op,y,z)  or  a  Rel(op,y,z)  node  )  { 

t  =  new  temporary; 
emit  string  for  t  =  rvalue(y)  op  rvalue(z); 
r e t u rn  a  new  node  for  t; 

} 
e l se  if  (  x  is  an  Access  (y,z)  node  )  { 

lvalue(x),  which  returns  Access(y,  z'); 

t  —  new  temporary; 
call 
emit  string  for  t  =  Access(y,  z')\ 
r e t u rn  a  new  node  for  t; 

} 
e l se  if  (  x  is  an  Assign (y,  z)  node  )  { 

z'  =  rvalue(z)] 
emit  string  for  lvalue(y)  =  z'; 
r e t u rn  z'; 

} 

} 

Figure  2.45:  Pseudocode  for  function  rvalue 

Function  rvalue  in  Fig.  2.45  generates  instructions  and  returns  a  possibly 
new  node.  When  x  represents  an  identifier  or  a  constant,  rvalue  returns  x  itself. 
In  all  other  cases,  it  returns  an  Id  node  for  a  new  temporary  t.  T he  cases  are 
as  follows: 

•  When  x  represents  y  op  z,  the  code  first  computes  y'  =  rvalue(y)  and 
z'  =  rvalue(z). 
It  creates  a  new  temporary  t  and  generates  an  instruc 
tion  t  =  y'  op  z'  (more  precisely,  an  instruction  formed  from  the  string 
representations  of  t,  y',  o p,  and  z').  It  returns  a  node  for  identifier  t. 

•  W h en  x  represents  an  array  access  ylz],  we  can  reuse  function 

lvalue. 

T he call lvalue(x)  returns an access y [ 2 ' ], where z'  represents an identifier 
holding  t he  offset  for  t he  array  access.  T he  code  creates  a  new  t e m p o r a ry 
t,  generates  an  instruction  based  on  t  =  y tz'l,  and  returns  a  node  for  t. 

104 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

•  When  x  represents  y  =  z,  then  the  code  first  computes  z'  =  rvalue(z).  It 
generates  an  instruction  based  on  lvalue(y)  =  z'  and  returns  t he  node  z'. 

E x a m p le  2 . 2 0:  When  applied  to  the  syntax  tree  for 

function  rvalue  generates 

a [ i]  =  2 * a[ j - k] 

t3  =  j  -  k 
t2  =  a  [  t3  ] 
tl  =  2  *  t2 
a  [  i  ]  =  tl 

T h at  is,  the  root  is  an  Assign  node  with  first  argument  a [ i]  and  second  ar 

gument  2 * a[ j - k]  .  Thus,  the  third  case  applies,  and  function  rvalue  recursively 
evaluates  2 * a[ j - k ].  T he  root  of this  subtree  is  the  Op  node  for  *,  which  causes 
a  new  temporary  tl  to  be  created,  before  t he  left  operand,  2  is  evaluated,  and 
then  the  right  operand.  T he  constant  2  generates  no  three-address  code,  and 
its  r-value  is  returned  as  a  Constant  node  with  value  2. 

T he  right  operand  a[ j - k]  is  an  Access  node,  which  causes  a  new  t e m p o r a ry 
t2  to  be  created,  before  function  lvalue  is  called  on  this  node.  Recursively, 
rvalue  is  called  on  t he  expression  j -k.  As  a  side-effect  of  this  call,  the  three-
address  statement  t3  =  j 
-  k  is  generated,  after  t he  new  temporary  t3  is 
created.  Then,  returning  to  the  call  of  lvalue  on  a[ j - k ],  the  t e m p o r a ry  t2  is 
assigned  the  r-value  of  the  entire  access-expression,  t h at  is,  t2  =  a 

[  t3  ]. 

Now,  we  return  to  t he  call  of  rvalue  on  the  Op  node  2 * a[ j - k ],  which  earlier 
created  temporary  t l.  A  three-address  statement  11  =  2  *  12  is  generated  as 
a  side-effect,  to  evaluate  this  multiplication-expression.  Last,  t he  call  to  rvalue 
on  the  whole  expression  completes  by  calling  lvalue  on  the  left  side  a [ i]  and 
then  generating  a  three-address  instruction  a [ i ] = t l,  in  which  t he  right 
side  of  the  assignment  is  assigned  to  the  left  side. 

• 

B e t t er  C o de  for  E x p r e s s i o ns 

We  can  improve  on  function  rvalue  in  Fig.  2.45  and  generate  fewer  three-address 
instructions,  in  several  ways: 

•  Reduce  t he  number  of  copy  instructions  in  a  subsequent  optimization 
phase.  For  example,  the  pair  of  instructions  t  =  i +1  and  i  =  t  can  be 
combined  into  i  =  i + 1,  if  there  are  no  subsequent  uses  of  t. 

•  Generate  fewer  instructions  in  t he  first  place  by  taking  context  into  ac 
count.  For  example,  if  the  left  side  of  a  three-address  assignment  is  an 
array  access  a [ t ],  then  t he  right  side  must  be  a  name,  a  constant,  or  a 
temporary,  all  of which  use just  one  address.  But  if the  left  side  is  a  name 
x,  then  t he  right  side  can  be  an  operation  y  op  z  t h at  uses  two  addresses. 

2.9. 

SUMMARY  OF  CHAPTER  2 

105 

We  can  avoid  some  copy  instructions  by  modifying  the  translation  functions 
to  generate  a  partial  instruction  t h at  computes,  say  j+k,  but  does  not  commit 
to  where  the  result  is  to  be  placed,  signified  by  a  null  address  for  the  result: 

null  =  j  +  k 

(2.8) 

T he  null  result  address  is  later  replaced  by  either  an  identifier  or  a  temporary, 
as  appropriate.  It  is  replaced  by  an  identifier  if  j +k  is  on  t he  right  side  of  an 
assignment,  as  in  i = j + k ;,  in  which  case  (2.8)  becomes 

i  =  j  +  k 

But,  if  j +k  is  a  subexpression,  as  in  j + k + 1,  then  the  null  result  address  in  (2.8) 
is  replaced  by  a  new  t e m p o r a ry  t,  and  a  new  partial  instruction  is  generated 

t  =  j  +  k 
null  =  t  +  1 

Many  compilers  make  every  effort  to  generate  code  t h at  is  as  good  as  or  bet 

ter  t h an  hand-written  assembly  code  produced  by  experts.  If  code-optimization 
techniques,  such  as  the  ones  in  Chapter  9  are  used,  then  an  effective  strategy 
may  well  be  to  use  a  simple  approach  for  intermediate  code  generation,  and 
rely  on  t he  code  optimizer  to  eliminate  unnecessary  instructions. 

2.8.5  Exercises  for  Section  2.8 

E x e r c i se  2 . 8 . 1:  For-statements  in  C  and  Java  have  the  form: 

for  (  exprx 

;  expr2 

;  expr3  )  stmt 

T he  first  expression  is  executed  before  the  loop;  it  is  typically  used  for  initializ 
ing  the  loop  index.  The  second  expression  is  a  test  made  before  each  iteration 
of t he  loop;  the  loop  is  exited  if the  expression  becomes  0.  The  loop  itself can  be 
thought  of  as  the  statement  {stmt  expr3;}.  The  third  expression  is  executed 
at  the  end  of  each  iteration;  it  is  typically  used  to  increment  the  loop  index. 
The  meaning  of  the  for-statement  is  similar  to 

expr±;  w h i le 

(  expr2 

) 

{stmt  expr3; 

} 

Define  a  class  For  for  for-statements,  similar  to  class  / / in  Fig.  2.43. 

E x e r c i se  2 . 8 . 2:  The  programming  language  C  does  not  have  a  boolean  type. 
Show  how  a  C  compiler  might  translate  an  if-statement  into  three-address  code. 

2.9  Summary  of Chapter  2 

The  syntax-directed  techniques  in  this  chapter  can  be  used  to  construct  compiler 
front  ends,  such  as  those  illustrated  in  Fig.  2.46. 

106 

CHAPTER 

2. 

A 

SIMPLE  SYNTAX-DIRECTED 

TRANSLATOR 

if(  peek ==  '\n'  )  line  =  line  +  1; 

X 
1 

Lexical  Analyzer 

(if) {(> (id, "peek") (eq> (const, »\n») ()) 

(id, "line") (assign) (id, "line") (+) ( n u m,  1)  (;) 

.__  X 

Syntax-Directed  Translator 

, 
~r 

or 

if 

assign 

+ 

peek 

( i n t) 

An' 

tl = (int) '\n' 

ifFalse  peek  ==  tl  goto  4 

line  =  line  +  1 

Figure  2.46:  Two  possible  translations  of  a  statement 

•  The  starting  point  for  a  syntax-directed  translator  is  a  g r a m m ar  for  the 
source  language.  A  grammar  describes  the  hierarchical  structure  of  pro 
grams.  It  is  defined  in  terms  of  elementary  symbols  called  terminals  and 
variable  symbols  called  nonterminals.  These  symbols  represent  language 
constructs.  The  rules  or  productions  of a  grammar  consist  of a  nonterminal 
called  t he  head  or  left  side  of  a  production  and  a  sequence  of  terminals 
and  nonterminals  called  the  body  or  right  side  of  the  production.  One 
nonterminal  is  designated  as  t he  start  symbol. 

• 

In  specifying  a  translator,  it  is  helpful  to  attach  attributes  to  programming 
construct,  where  an  attribute  is  any  quantity  associated  with  a  construct. 
Since  constructs  are  represented  by  g r a m m ar  symbols,  t he  concept  of 
attributes  extends  to  grammar  symbols.  Examples  of  attributes  include 
an  integer  value  associated  with  a  terminal  n um  representing  numbers, 
and  a  string  associated  with  a  terminal  id  representing  identifiers. 

•  A  lexical  analyzer  reads  t he  input  one  character  at  a  time  and  produces 
as  output  a  stream  Of  tokens,  where  a  token  consists  of  a  terminal  symbol 
In 
along  with  additional  information  in  the  form  of  a t t r i b u te  values. 
Fig.  2.46,  tokens  are  written  as  tuples  enclosed  between  (  ).  T he  token 
(id,  "peek")  consists  of the  terminal  id  and  a  pointer  to  the  symbol-table 
entry  containing  the  string  "peek".  T he  translator  uses  the  table  to  keep 

2.9. 

SUMMARY  OF  CHAPTER  2 

107 

track  of  reserved  words  and  identifiers  t h at  have  already  been  seen. 

4-  Parsing  is  the  problem  of  figuring  out  how  a  string  of  terminals  can  be 
derived  from  t he  start  symbol  of  the  grammar  by  repeatedly  replacing  a 
nonterminal  by  the  body  of one  of its  productions.  Conceptually,  a  parser 
builds  a  parse  tree  in  which  the  root  is  labeled  with  the  start  symbol, 
each  nonleaf  corresponds  to  a  production,  and  each  leaf  is  labeled  with 
a  terminal  or  the  empty  string  e.  T he  parse  tree  derives  the  string  of 
terminals  at  the  leaves,  read  from  left  to  right. 

4*  Efficient  parsers  can  be  built  by  hand,  using  a  top-down  (from  the  root  to 
the  leaves  of  a  parse  tree)  method  called  predictive  parsing.  A  predictive 
parser  has  a  procedure  for  each  nonterminal;  procedure  bodies  mimic  the 
productions  for  nonterminals;  and,  the  flow  of  control  through  the  pro 
cedure  bodies  can  be  determined  unambiguously  by  looking  one  symbol 
ahead  in  the  input  stream.  See  Chapter  4  for  other  approaches  to  parsing. 

•  Syntax-directed  translation  is  done  by  attaching  either  rules  or  program 
fragments  to  productions  in  a  grammar.  In  this  chapter,  we  have  consid 
ered  only  synthesized  attributes  —  the  value  of  a  synthesized  a t t r i b u te  at 
any  node  x  can  depend  only  on  attributes  at  the  children  of  re,  if  any.  A 
syntax-directed  definition  attaches  rules  to  productions;  the  rules  compute 
a t t r i b u te  vales.  A  translation  scheme  embeds  program  fragments  called 
semantic  actions  in  production  bodies.  The  actions  are  executed  in  the 
order  t h at  productions  are  used  during  syntax  analysis. 

•  T he  result  of  syntax  analysis  is  a  representation  of  the  source  program, 
called  intermediate  code.  Two  primary  forms  of  intermediate  code  are  il 
lustrated  in  Fig.  2.46.  An  abstract  syntax  tree  has  nodes  for  programming 
constructs;  the  children  of  a  node  give  the  meaningful  sub  constructs.  Al 
ternatively,  three-address  code  is  a  sequence  of  instructions  in  which  each 
instruction  carries  out  a  single  operation. 

•  Symbol  tables  are  d a ta  structures  t h at  hold  information  about  identifiers. 
Information  is  put  into  the  symbol  table  when  t he  declaration  of an  iden 
tifier  is  analyzed.  A  semantic  action  gets  information  from  t he  symbol 
table  when  t he  identifier  is  subsequently  used,  for  example,  as  a  factor  in 
an  expression. 

Chapter  3 

Lexical  Analysis 

In  this  chapter  we  show  how  to  construct  a  lexical  analyzer.  To  implement  a 
lexical  analyzer  by  hand,  it  helps  to  start  with  a  diagram  or  other  description  for 
t he  lexemes  of each  token.  We  can  then  write  code  to  identify  each  occurrence  of 
each  lexeme  on  the  input  and  to  return  information  about  the  token  identified. 
We  can  also  produce  a  lexical  analyzer  automatically  by  specifying  the  lex 
eme  p a t t e r ns  to  a  lexical-analyzer  generator  and  compiling  those  p a t t e r ns  into 
code  t h at  functions  as  a  lexical  analyzer.  This  approach  makes  it  easier  to  mod 
ify  a  lexical  analyzer,  since  we  have  only  to  rewrite  the  affected  patterns,  not 
the  entire  program.  It  also  speeds  up  the  process  of  implementing  the  lexical 
analyzer,  since  t he  programmer  specifies  the  software  at  the  very  high  level  of 
p a t t e r ns  and  relies  on  the  generator  to  produce  the  detailed  code.  We  shall 
introduce  in  Section  3.5  a  lexical-analyzer  generator  called  Lex  (or  Flex  in  a 
more  recent  embodiment). 

We  begin  the  study  of  lexical-analyzer  generators  by  introducing  regular 
expressions,  a  convenient  notation  for  specifying  lexeme  patterns.  We  show 
how  this  notation  can  be  transformed,  first  into  nondeterministic  a u t o m a ta 
and  then  into  deterministic  a u t o m a t a.  T he  latter  two  notations  can  be  used  as 
input  to  a  "driver,"  t h at  is,  code  which  simulates  these  a u t o m a ta  and  uses  t h em 
as  a  guide  to  determining  the  next  token.  This  driver  and  the  specification  of 
t he  a u t o m a t on  form  the  nucleus  of  the  lexical  analyzer. 

3.1  The  Role  of the  Lexical  Analyzer 

As  the  first  phase  of  a  compiler,  the  main  task  of  the  lexical  analyzer  is  to 
read  t he  input  characters  of t he  source  program,  group  t h em  into  lexemes,  and 
produce  as  output  a  sequence  of  tokens  for  each  lexeme  in  t he  source  program. 
T he  stream  of  tokens  is  sent  to  the  parser  for  syntax  analysis.  It  is  common 
for  the  lexical  analyzer  to  interact  with  the  symbol  table  as  well.  W h en  the 
lexical  analyzer  discovers  a  lexeme  constituting  an  identifier,  it  needs  to  enter 
In  some  cases,  information  regarding  the 
t h at  lexeme  into  the  symbol  table. 

1 09 

110 

CHAPTER  3. 

LEXICAL  ANALYSIS 

kind  of  identifier  may  be  read  from  the  symbol  table  by  the  lexical  analyzer  to 
assist  it  in  determining  the  proper  token  it  must  pass  to  the  parser. 

These  interactions  are  suggested  in  Fig.  3.1.  Commonly,  the  interaction  is 
implemented  by  having  t he  parser  call  t he  lexical  analyzer.  T he  call,  suggested 
by  the  getNextToken  command,  causes  t he  lexical  analyzer  to  read  characters 
from  its  input  until  it  can  identify  the  next  lexeme  and  produce  for  it  t he  next 
token,  which  it  returns  to  the  parser. 

source 
program 

to  semantic 
analysis 

Symbol 
Table 

Figure  3.1:  Interactions  between  the  lexical  analyzer  and  the  parser 

Since  t he  lexical  analyzer  is  the  part  of  the  compiler  t h at  reads  t he  source 
text,  it  may  perform  certain  other  tasks  besides  identification  of  lexemes.  One 
such  task  is  stripping  out  comments  and  whitespace  (blank,  newline,  t a b,  and 
perhaps  other  characters  t h at  are  used  to  separate tokens  in  t he  input).  Another 
task  is  correlating  error  messages  generated  by  t he  compiler  with  the  source 
program.  For  instance,  t he  lexical  analyzer  may  keep  track  of  t he  number 
of  newline  characters  seen,  so  it  can  associate  a  line  number  with  each  error 
In  some  compilers,  the  lexical  analyzer  makes  a  copy  of  t he  source 
message. 
program  with  the  error  messages  inserted  at  the  appropriate  positions.  If  the 
source  program  uses  a  macro-preprocessor,  the  expansion  of  macros  may  also 
be  performed  by  t he  lexical  analyzer. 

Sometimes,  lexical  analyzers  are  divided  into  a  cascade  of  two  processes: 

a)  Scanning  consists  of  the  simple  processes  t h at  do  not  require  tokenization 
of t he  input,  such  as  deletion  of  comments  and  compaction  of consecutive 
whitespace  characters  into  one. 

b)  Lexical  analysis  proper  is  t he  more  complex  portion,  where  t he  scanner 

produces  the  sequence  of  tokens  as  output. 

3.1.1  Lexical  Analysis  Versus  Parsing 

There  are  a number  of reasons  why  the  analysis  portion  of a  compiler  is  normally 
separated  into  lexical  analysis  and  parsing  (syntax  analysis)  phases. 

3.1. 

THE  ROLE  OF  THE  LEXICAL  ANALYZER 

111 

1.  Simplicity  of  design  is  the  most  important  consideration.  The  separation 
of  lexical  and  syntactic  analysis  often  allows  us  to  simplify  at  least  one 
of  these  tasks.  For  example,  a  parser  t h at  had  to  deal  with  comments 
and  whitespace  as  syntactic  units  would  be  considerably  more  complex 
t h an  one  t h at  can  assume  comments  and  whitespace  have  already  been 
removed  by  the  lexical  analyzer. 
If  we  are  designing  a  new  language, 
separating  lexical  and  syntactic  concerns  can  lead  to  a  cleaner  overall 
language  design. 

2.  Compiler  efficiency  is  improved.  A  separate  lexical  analyzer  allows  us  to 
apply  specialized  techniques  t h at  serve  only  t he  lexical  task,  not  the  job 
of  parsing.  In  addition,  specialized  buffering  techniques  for  reading  input 
characters  can  speed  up  t he  compiler  significantly. 

3.  Compiler  portability  is  enhanced. 

Input-device-specific  peculiarities  can 

be  restricted  to  t he  lexical  analyzer. 

3.1.2  Tokens,  Patterns,  and  Lexemes 

W h en  discussing  lexical  analysis,  we  use  three  related  but  distinct  terms: 

•  A  token  is  a  pair  consisting  of  a  token  name  and  an  optional  a t t r i b u te 
value.  The  token  name  is  an  abstract  symbol  representing  a  kind  of 
lexical  unit,  e.g.,  a  particular  keyword,  or  a  sequence  of  input  characters 
denoting  an  identifier.  The  token  names  are  the  input  symbols  t h at  the 
parser  processes.  In  what  follows,  we  shall  generally  write  the  name  of  a 
token  in  boldface.  We  will  often  refer  to  a  token  by  its  token  name. 

•  A  pattern is  a  description  of the  form  t h at  the  lexemes  of a  token  may  take. 
In  the  case  of  a  keyword  as  a  token,  the  p a t t e rn  is  just  the  sequence  of 
characters  t h at  form  the  keyword.  For  identifiers  and  some  other  tokens, 
the  p a t t e rn  is  a  more  complex  structure  t h at  is  matched  by  many  strings. 

•  A  lexeme  is  a  sequence  of  characters  in  the  source  program  t h at  matches 
the  p a t t e rn  for  a  token  and  is  identified  by  the  lexical  analyzer  as  an 
instance  of  t h at  token. 

E x a m p le  3 . 1:  Figure  3.2  gives  some  typical  tokens,  their  informally  described 
patterns,  and  some  sample  lexemes.  To  see  how  these  concepts  are  used  in 
practice,  in  the  C  statement 

p r i n t f ( " T o t al  =  %d\n",  s c o r e ); 

b o th  p r i n tf  and  s c o re  are  lexemes  matching  the  p a t t e rn  for  token  id,  and 
" T o t al  =  °/,d\n"  is  a  lexeme  matching  l i t e r a l. 

• 

In  many  programming  languages,  the  following  classes  cover  most  or  all  of 

the  tokens: 

112 

CHAPTER  3. 

LEXICAL  ANALYSIS 

T O K EN 

I N F O R M AL  D E S C R I P T I ON 

S A M P LE  L E X E M ES 

if 

e l se 

characters  i,  f 

characters  e,  1,  s,  e 

if 

e l se 

c o m p a r i s on 

<  or  >  or  <=  or  >=  or  ==  or  ! = 

<=, ! = 

id 

n u m b er 

literal 

letter  followed  by  letters  and  digits 

p i,  s c o r e,  D2 

any  numeric  constant 

3 . 1 4 1 5 9,  0,  6 . 0 2 e 23 

anything  but  ",  surrounded  by  "'s 

"core  dumped" 

Figure  3.2:  Examples  of  tokens 

1.  One  token  for  each  keyword.  T he  p a t t e rn  for  a  keyword  is  t he  same  as 

the  keyword  itself. 

2.  Tokens  for  the1  operators,  either  individually  or  in  classes  such  as  t he  token 

c o m p a r i s on  rfientioned  in  Fig.  3.2. 

3.  One  token  representing  all  identifiers. 

4.  One  or  more  tokens  representing  constants,  such  as  numbers  and  literal 

strings. 

5.  Tokens  for  each  punctuation  symbol,  such  as  left  and  right  parentheses, 

comma,  and  semicolon. 

3.1.3  Attributes  for  Tokens 

When  more  t h an  one  lexeme  can  match  a  p a t t e r n,  t he  lexical  analyzer  must 
provide  the  subsequent  compiler  phases  additional  information  about  the  par 
ticular  lexeme  t h at  matched.  For  example,  t he  p a t t e rn  for  token  n u m b er 
matches  both  0  and  1,  but  it  is  extremely  important  for  t he  code  generator  to 
know  which  lexeme  was  found  in  the  source  program.  Thus,  in  many  cases  the 
lexical  analyzer  returns  to  the  parser  not  only  a  token  name,  but  an  a t t r i b u te 
value  t h at  describes  the  lexeme  represented  by  t he  token;  t he  token  name  in 
fluences  parsing  decisions,  while  the  attribute  value  influences  translation  of 
tokens  after  the  parse. 

We  shall  assume  t h at  tokens  have  at  most  one  associated  attribute,  although 
this  attribute  may  have  a  structure  t h at  combines  several  pieces  of  information. 
T he  most  important  example  is  t he  token  id,  where  we  need  to  associate  with 
t he  token  a  great  deal  of  information.  Normally,  information  about  an  identi 
fier  —  e.g.,  its  lexeme,  its  type,  and  the  location  at  which  it  is  first  found  (in 
case  an  error  message  about  t h at  identifier  must  be  issued)  —  is  kept  in  the 
symbol  table.  Thus,  t he  appropriate  a t t r i b u te  value  for  an  identifier  is  a  pointer 
to  the  symbol-table  entry  for  t h at  identifier. 

3.1. 

THE  ROLE  OF  THE  LEXICAL  ANALYZER 

113 

Tricky  Problems  When  Recognizing  Tokens 

Usually,  given  t he  p a t t e rn  describing  t he  lexemes  of a token,  it  is  relatively 
simple  to  recognize  matching  lexemes  when  they  occur  on  the  input.  How 
ever,  in  some  languages  it  is  not  immediately  apparent  when  we  have  seen 
an  instance  of  a  lexeme  corresponding  to  a  token.  T he  following  example 
is  taken  from  Fortran,  in  the  fixed-format  still  allowed  in  Fortran  90.  In 
the  statement 

DO  5  I  =  1.25 

it  is  not  apparent  t h at  the  first  lexeme  is  D05I,  an  instance  of the  identifier 
token,  until we see the  dot  following the  1.  Note t h at  blanks  in  fixed-format 
Fortran  are  ignored  (an  archaic  convention).  Had  we  seen  a  comma instead 
of  t he  dot,  we  would  have  had  a  do-statement 

in  which  the  first  lexeme  is  t he  keyword  DO. 

DO  5  I  =  1,25 

E x a m p le  3 . 2:  The  token  names  and  associated  a t t r i b u te  values  for  the  For 
t r an  statement 

E  =  M  *  C  **  2 

are  written  below  as  a  sequence  of  pairs. 

< i d,  pointer  to  symbol-table  entry  for  E> 
< a s s i g n _ o p> 
< i d,  pointer  to  symbol-table  entry  for  M> 
< m u l t _ o p> 
< i d,  pointer  to  symbol-table  entry  for  C> 
< e x p _ o p> 
< n u m b e r,  integer  value  2> 

Note  t h at  in  certain  pairs,  especially  operators,  punctuation,  and  keywords, 
there  is  no  need  for  an  attribute  value.  In  this  example,  the  token  n u m b er  has 
been  given  an  integer-valued  attribute. 
In  practice,  a  typical  compiler  would 
instead  store  a  character  string  representing the  constant  and  use  as  an  a t t r i b u te 
value  for  n u m b er  a  pointer  to  t h at  string. 

• 

3.1.4  Lexical  Errors 

It  is  hard  for  a  lexical  analyzer  to  tell,  without  the  aid  of  other  components, 
t h at  there  is  a  source-code  error.  For  instance,  if  t he  string  f i  is  encountered 
for  the  first  time  in  a  C  program  in  the  context: 

114 

CHAPTER  3. 

LEXICAL  ANALYSIS 

fi 

(  a  ==  f ( x )) 

. .. 

a  lexical  analyzer  cannot  tell  whether  f i  is  a  misspelling  of  the  keyword  if  or 
an  undeclared  function  identifier.  Since  f i  is  a  valid  lexeme  for  t he  token  id, 
the  lexical  analyzer  must  return  the  token  id  to  t he  parser  and  let  some  other 
phase  of  the  compiler  —  probably  the  parser  in  this  case  —  handle  an  error 
due  to  transposition  of  the  letters. 

However,  suppose  a  situation  arises  in  which  the  lexical  analyzer  is  unable 
to  proceed  because  none  of  the  patterns  for  tokens  matches  any  prefix  of  t he 
remaining  input.  T he  simplest  recovery  strategy  is  "panic  mode"  recovery.  We 
delete  successive  characters  from  t he  remaining  input,  until  t he  lexical  analyzer 
can  find  a  well-formed  token  at  t he  beginning  of what  input  is  left.  This  recovery 
technique  may  confuse  the  parser,  but  in  an  interactive  computing  environment 
it  may  be  quite  adequate. 

Other  possible  error-recovery  actions  are: 

1.  Delete  one  character  from  the  remaining  input. 

2.  Insert  a  missing  character  into  the  remaining  input. 

3.  Replace  a  character  by  another  character. 

4.  Transpose  two  adjacent  characters. 

Transformations  like  these  may  be  tried  in  an  a t t e m pt  to  repair  the  input.  T he 
simplest  such  strategy  is  to  see  whether  a  prefix  of  the  remaining  input  can 
be  transformed  into  a  valid  lexeme  by  a  single  transformation.  This  strategy 
makes  sense,  since  in  practice  most  lexical  errors  involve  a  single  character.  A 
more  general  correction  strategy  is  to  find  the  smallest  number  of  transforma 
tions  needed  to  convert  t he  source  program  into  one  t h at  consists  only  of  valid 
lexemes,  but  this  approach  is  considered  too  expensive  in  practice  to  be  worth 
t he  effort. 

3.1.5  Exercises  for  Section  3.1 

E x e r c i se  3 . 1 . 1:  Divide  the  following  C ++  program: 

f l o at 

l i m i t e d S q u a r e ( x) 

f l o at  x  { 
/*  r e t u r ns  x - s q u a r e d,  b ut  n e v er  more  t h an  100  */ 
r e t u rn 

( x < = - 1 0 . 0 | | x > = 1 0 . 0 ) ? 1 0 0 : x * x; 

} 

into  appropriate lexemes,  using the  discussion  of Section  3.1.2  as  a guide.  Which 
lexemes  should  get  associated  lexical  values?  W h at  should  those  values  be? 

!  E x e r c i se  3 . 1 . 2:  Tagged  languages  like  H T ML  or  XML  are  different  from  con 
ventional  programming  languages  in  t h at  the  punctuation  (tags)  are  either  very 
numerous  (as  in  HTML)  or  a  user-definable  set  (as  in  XML).  Further,  tags  can 
often  have  parameters.  Suggest  how  to  divide  the  following  H T ML  document: 

3.2. 

INPUT  BUFFERING 

115 

Here  is  a photo  of  <B>my  house</B>: 

< P X I MG  SRC  =  "house.gif"><BR> 

See  <A  HREF  =  "morePix.html">More Pictures</A>  if  you 

liked  that  one.<P> 

into  appropriate  lexemes.  Which  lexemes  should  get  associated  lexical  values, 
and  what  should  those  values  be? 

3.2 

Input  Buffering 

Before  discussing the  problem  of recognizing lexemes  in  the  input,  let  us  examine 
some  ways  t h at  the  simple  but  important  task  of  reading  the  source  program 
can  be  speeded.  This  task  is  made  difficult  by  the  fact  t h at  we  often  have 
to  look  one  or  more  characters  beyond  the  next  lexeme  before  we  can  be  sure 
we  have  the  right  lexeme.  T he  box  on  "Tricky  Problems  When  Recognizing 
Tokens"  in  Section  3.1  gave  an  extreme  example,  but  there  are  many  situations 
where  we  need  to  look  at  least  one  additional  character  ahead.  For  instance, 
we  cannot  be  sure  we've  seen  the  end  of  an  identifier  until  we  see  a  character 
t h at  is  not  a  letter  or  digit,  and  therefore  is  not  part  of  the  lexeme  for  id.  In 
C,  single-character  operators  like  -,  =,  or  <  could  also  be  the  beginning  of  a 
two-character  operator  like  ->,  ==,  or  <=.  Thus,  we  shall  introduce  a  two-buffer 
scheme  t h at  handles  large  lookaheads  safely.  We  then  consider  an  improvement 
involving  "sentinels"  t h at  saves  time  checking  for  the  ends  of  buffers. 

3.2.1  Buffer  Pairs 

Because  of t he  amount  of time  taken  to  process  characters  and  the  large  number 
of  characters  t h at  must  be  processed  during  the  compilation  of  a  large  source 
program,  specialized  buffering  techniques  have  been  developed  to  reduce  the 
amount  of  overhead  required  to  process  a  single  input  character.  An  impor 
t a nt  scheme  involves  two  buffers  t h at  are  alternately  reloaded,  as  suggested  in 
Fig.  3.3. 

E 

= 

M  *  C  *  *  2  eof 

t 
forward 

lexemeBegin 

Figure  3.3:  Using  a  pair  of  input  buffers 

Each  buffer  is  of  the  same  size  N,  and  N  is  usually  the  size  of  a  disk  block, 
e.g.,  4096  bytes.  Using  one  system  read  command  we  can  read  N  characters 
into  a  buffer,  rather  t h an  using  one  system  call  per  character.  If  fewer  t h an  N 
characters  remain  in  t he  input  file,  t h en  a  special  character,  represented  by  eof, 

116 

CHAPTER  3. 

LEXICAL  ANALYSIS 

marks  the  end  of  the  source  file  and  is  different  from  any  possible  character  of 
the  source  program. 

Two  pointers  to  the  input  are  maintained: 

1.  Pointer  lexemeBegin,  marks  the  beginning  of  the  current  lexeme,  whose 

extent  we  are  attempting  to  determine. 

2.  Pointer  forward  scans  ahead  until  a  p a t t e rn  match  is  found;  the  exact 
strategy  whereby  this  determination  is  made  will  be  covered  in  t he  balance 
of  this  chapter. 

Once  t he  next  lexeme  is  determined,  forward  is  set  to  the  character  at  its  right 
end.  Then,  after  the  lexeme  is  recorded  as  an  a t t r i b u te  value  of a token  returned 
to  the  parser,  lexemeBegin  is  set  to  the  character  immediately  after  t he  lexeme 
just  found.  In  Fig.  3.3,  we  see  forward  has  passed  the  end  of  the  next  lexeme, 
**  (the  Fortran  exponentiation  operator),  and  must  be  retracted  one  position 
to  its  left. 

Advancing  forward  requires  t h at  we  first  test  whether  we  have  reached  t he 
end  of  one  of  the  buffers,  and  if  so,  we  must  reload  the  other  buffer  from  the 
input,  and  move  forward  to  t he  beginning  of  t he  newly  loaded  buffer.  As  long 
as  we  never  need  to  look  so  far  ahead  of t he  actual  lexeme  t h at  the  sum  of  the 
lexeme's  length  plus  the  distance  we  look  ahead  is  greater  t h an  N,  we  shall 
never  overwrite  the  lexeme  in  its  buffer  before  determining  it. 

3.2.2  Sentinels 

If we  use  the  scheme  of Section  3.2.1  as  described,  we  must  check,  each  time  we 
advance  forward,  t h at  we  have  not  moved  off  one  of t he  buffers;  if  we  do,  then 
we  must  also  reload  t he  other  buffer.  Thus,  for  each  character  read,  we  make 
two  tests:  one  for  the  end  of  t he  buffer,  and  one  to  determine  what  character 
is  read  (the  latter  may  be  a  multiway  branch).  We  can  combine  t he  buffer-end 
test  with  the  test  for  t he  current  character  if  we  extend  each  buffer  to  hold  a 
sentinel  character  at  the  end.  T he  sentinel  is  a  special  character  t h at  cannot 
be  part  of  the  source  program,  and  a  natural  choice  is  the  character  eof. 

Figure  3.4  shows  the  same  arrangement  as  Fig.  3.3,  but  with  t he  sentinels 
added.  Note  t h at  e of retains  its  use  as  a  marker  for  the  end  of the  entire  input. 
Any  e of  t h at  appears  other  t h an  at  the  end  of  a  buffer  means  t h at  t he  input 
is  at  an  end.  Figure  3.5  summarizes  the  algorithm  for  advancing  forward. 
Notice  how  the  first  test,  which  can  be  part  of  a  multiway  branch  based  on  t he 
character  pointed  to  by  forward,  is  t he  only  test  we  make,  except  in  t he  case 
where  we  actually  are  at  the  end  of  a  buffer  or  the  end  of  t he  input. 

3.3  Specification  of  Tokens 

Regular  expressions  are  an  important  notation  for  specifying  lexeme  p a t t e r n s. 
While  they  cannot  express  all  possible  patterns,  they  are  very  effective  in  spec-

3.3. 

SPECIFICATION  OF  TOKENS 

117 

Can  We  Run  Out  of  Buffer  Space? 

In  most  modern  languages,  lexemes  are  short,  and  one  or  two  characters 
of lookahead  is  sufficient.  Thus  a  buffer  size  N  in  t he  thousands  is  ample, 
and  t he  double-buffer  scheme  of  Section 3.2.1  works  without  problem. 
However,  there  are  some  risks.  For  example,  if  character  strings  can  be 
very  long,  extending  over  many  lines,  then  we  could  face  the  possibility 
t h at  a  lexeme  is  longer  t h an  N.  To  avoid  problems  with  long  character 
strings,  we  can  treat  t h em  as  a  concatenation  of  components,  one  from 
each  line  over  which  the  string  is  written.  For  instance,  in  Java  it  is 
conventional  to  represent  long  strings  by  writing  a  piece  on  each  line  and 
concatenating  pieces  with  a  +  operator  at  the  end  of  each  piece. 

A  more  difficult  problem  occurs  when  arbitrarily  long  lookahead  may 

be  needed.  For  example,  some  languages  like  P L /I  do  not  treat  key 
words  as  reserved;  t h at  is,  you  can  use  identifiers  with  the  same  name  as 
a  keyword  like DECLARE.  If the  lexical  analyzer  is  presented  with  text  of a 
P L /I program t h at  begins DECLARE ( ARG1,  ARG2,...  it  cannot  be  sure 
whether DECLARE is  a keyword,  and ARG1  and  so on  are variables being  de 
clared,  or  whether DECLARE  is  a  procedure  name  with  its  arguments.  For 
this  reason,  modern  languages  tend  to  reserve  their  keywords.  However,  if 
not,  one  can  treat  a  keyword  like DECLARE  as  an  ambiguous  identifier,  and 
let  t he  parser  resolve  t he  issue,  perhaps  in  conjunction  with  symbol-table 
lookup. 

ifying  those  types  of  p a t t e r ns  t h at  we  actually  need  for  tokens.  In  this  section 
we  shall  study  the  formal  notation  for  regular  expressions,  and  in  Section  3.5 
we  shall  see  how  these  expressions  are  used  in  a  lexical-analyzer  generator. 
Then,  Section  3.7  shows  how  to  build  the  lexical  analyzer  by  converting  regular 
expressions  to  a u t o m a ta  t h at  perform  the  recognition  of  the  specified  tokens. 

3.3.1 

Strings  and  Languages 

An  alphabet  is  any  finite  set  of  symbols.  Typical  examples  of  symbols  are  let 
ters,  digits,  and  punctuation.  The  set  {0,1}  is  the  binary  alphabet.  ASCII  is  an 
important  example  of  an  alphabet;  it  is  used  in  many  software  systems.  Uni-

E 

= 

M  *  eof  C  *  *  2  eof 

eof 

| 
lexemeBegin 

forward 

Figure 3.4: Sentinels  at  the  end  of  each  buffer 

118 

CHAPTER  3. 

LEXICAL  ANALYSIS 

s w i t ch  (  *forward++  )  { 

c a se  eof: 

if  (forward  is  at  end  of  first  buffer  )  { 

reload  second  buffer; 
forward  =  beginning  of  second  buffer; 

} 
e l se  if  (forward  is  at  end  of  second  buffer  )  { 

reload  first  buffer; 
forward  =  beginning  of  first  buffer; 

} 
e l se  /*  e of within  a  buffer  marks  the  end  of  input  */ 

terminate  lexical  analysis; 

break; 

Cases  for  t he  other  characters 

} 

Figure  3.5:  Lookahead  code  with  sentinels 

Implementing  Multiway  Branches 

We  might  imagine  t h at  t he  switch  in  Fig.  3.5  requires  many  steps  to  exe 
cute,  and  t h at  placing  t he  case  e of  first  is  not  a  wise  choice.  Actually,  it 
doesn't  m a t t er  in  what  order  we  list  the  cases  for  each  character.  In  prac 
tice,  a  multiway  branch  depending  on  t he  input  character  is  be  made  in 
one  step  by  jumping  to  an  address  found  in  an  array  of  addresses,  indexed 
by  characters. 

code,  which  includes  approximately  100,000  characters  from  alphabets  around 
the  world,  is  another  important  example  of  an  alphabet. 

A  string  over  an  alphabet  is  a  finite  sequence  of  symbols  drawn  from  t h at 
alphabet.  In  language  theory,  the  terms  "sentence"  and  "word"  are  often  used 
as  synonyms  for  "string."  T he  length  of  a  string  s,  usually  written  |s|,  is  the 
number  of  occurrences  of  symbols  in  s.  For  example,  b a n a na  is  a  string  of 
length  six.  The  empty  string,  denoted  e,  is  the  string  of  length  zero. 

A  language  is  any  countable  set  of  strings  over  some  fixed  alphabet.  This 
definition  is  very  broad.  Abstract  languages  like  0,  t he  empty  set,  or  {e},  t he 
set  containing  only  the  empty  string,  are  languages  under  this  definition.  So 
too  are  the  set  of  all  syntactically  well-formed  C  programs  and  the  set  of  all 
grammatically  correct  English  sentences,  although  the  latter  two  languages  are 
difficult  to  specify  exactly.  Note  t h at  the  definition  of  "language"  does  not 
require  t h at  any  meaning  be  ascribed  to  the  strings  in  the  language.  Methods 
for  defining  the  "meaning"  of  strings  are  discussed  in  Chapter  5. 

3.3. 

SPECIFICATION  OF  TOKENS 

119 

Terms  for  Parts  of  Strings 

T he  following  string-related  terms  are  commonly  used: 

1.  A  prefix  of  string  s  is  any  string  obtained  by  removing  zero  or  more 
symbols  from  the  end  of  s.  For  example,  ban,  banana,  and  e  are 
prefixes  of  banana. 

2.  A  suffix  of  string  s  is  any  string  obtained  by  removing  zero  or  more 
symbols  from  the  beginning  of  s.  For  example,  nana,  b a n a n a,  and  e 
are  suffixes  of  banana. 

3.  A  substring  of  s  is  obtained  by  deleting  any  prefix  and  any  suffix 
from  s.  For  instance,  banana,  nan,  and  e  are  substrings  of b a n a n a. 

4.  T he  proper  prefixes,  suffixes,  and  substrings  of  a  string  s  are  those, 
prefixes,  suffixes,  and  substrings,  respectively,  of  s  t h at  are  not  e  or 
not  equal  to  s  itself. 

5.  A  subsequence  of  s  is  any  string  formed  by  deleting  zero  or  more 
not  necessarily  consecutive  positions  of  s.  For  example,  b a an  is  a 
subsequence  of  banana. 

If  x  and  y  are  strings,  then  the  concatenation  of  x  and  y,  denoted  xy,  is  the 
string  formed  by  appending  y  to  x.  For  example,  if  x  =  dog  and  y  =  h o u s e, 
then  xy  —  doghouse.  T he  empty  string  is  the  identity  under  concatenation; 
t h at  is,  for  any  string  s,  es  =  se  —  s. 

If we  think of concatenation  as  a  product,  we  can  define  t he  "exponentiation" 
of  strings  as  follows.  Define  s°  to  be  e,  and  for  all  i  >  0,  define  sl  to  be  st~1s. 
Since  es  =  s,  it  follows  t h at  s1  =  s.  Then  s2  =  ss,  s3  =  sss,  and  so  on. 

3.3.2  Operations  on  Languages 

In  lexical  analysis,  the  most  important  operations  on  languages  are  union,  con 
catenation,  and  closure,  which  are  defined  formally  in  Fig.  3.6.  Union  is  t he 
familiar  operation  on  sets.  The  concatenation  of languages  is  all  strings  formed 
by  taking  a  string  from  the  first  language  and  a  string  from  the  second  lan 
guage,  in  all  possible  ways,  and  concatenating  them.  T he  (Kleene)  closure  of  a 
language  L,  denoted  L*,  is  the  set  of  strings  you  get  by  concatenating  L  zero 
or  more  times.  Note  t h at  L°,  the  "concatenation  of  L  zero  times,"  is  defined  to 
be  {e},  and  inductively,  U  is  Ll~1L.  Finally,  the  positive  closure,  denoted  L+, 
is  t he  same  as  t he  Kleene  closure,  b ut  without  t he  t e rm  L °.  T h at  is,  e  will  not 
be  in  L+  unless  it  is  in  L  itself. 

120 

CHAPTER  3. 

LEXICAL  ANALYSIS 

O P E R A T I ON 

, 

D E F I N I T I ON  A ND  N O T A T I ON 

Union  of  L  and  M 

L  U  M  =  {s  |  s  is  in  L  or  s  is  in  M} 

Concatenation  of  L  and  M 

LM  =  {si  |  s  is  in  L  and  t  is  in  M} 

Kleene  closure  of  L 

Positive  closure  of  L 

L*  = U £0 

Figure  3.6:  Definitions  of  operations  on  languages 

E x a m p le  3.3 i  Let  L  be  the  set  of  letters  {A, B , . ..  , Z, a, b , . . ., z}  and  let  D 
be  the  set  of  digits  { 0 , 1 , . ..  9 }.  We  may  think  of  L  and  D  in  two,  essentially 
equivalent,  ways.  One  way  is  t h at  L  and  D  are,  respectively,  the  alphabets  of 
uppercase  and  lowercase  letters  and  of  digits.  T he  second  way  is  t h at  L  and  D 
are  languages,  all  of  whose  strings  happen  to  be  of  length  one.  Here  are  some 
other  languages  t h at  can  be  constructed  from  languages  L  and  D,  using  t he 
operators  of  Fig.  3.6: 

1.  L  U  D  is  the  set  of  letters  and  digits  —  strictly  speaking  t he  language 
with  62  strings  of  length  one,  each  of  which  strings  is  either  one  letter  or 
one  digit. 

2.  LD  is  t he  set  c-f  520  strings  of  length  two,  each  consisting  of  one  letter 

followed  by  one  digit. 

3.  L4  is  the  set  of  all  4-letter  strings. 

4.  L*  is  t he  set  of  all  strings  of letters,  including  e,  t he  empty  string. 

5.  L(L  U  D)*  is  the  set  of  all  strings  of  letters  and  digits  beginning  with  a 

letter. 

6.  D+  is  the  set  of  all  strings  of  one  or  more  digits. 

• 

3.3.3  Regular  Expressions 

Suppose  we  wanted  to  describe  the  set  of  valid  C  identifiers.  It  is  almost  ex 
actly  t he  language  described  in  item  (5)  above;  t he  only  difference  is  t h at  t he 
underscore  is  included  among  t he  letters. 

In  Example  3.3,  we  were  able  to  describe  identifiers  by  giving  names  to  sets 
of  letters  and  digits  and  using  the  language  operators  union,  concatenation, 
and  closure.  This  process  is  so  useful  t h at  a  notation  called  regular  expressions 
has  come  into  common  use  for  describing  all  the  languages  t h at  can  be  built 
from  these  operators  applied  to  the  symbols  of  some  alphabet.  In  this  notation, 
if  letter-  is  established  to  stand  for  any  letter  or  the  underscore,  and  digit-  is 

3.3. 

SPECIFICATION  OF  TOKENS 

121 

established  to  stand  for  any  digit,  then  we  could  describe  the  language  of  C 
identifiers  by: 

letter-  (  letter-  \  digit  )* 

T he  vertical  bar  above  means  union,  the  parentheses  are  used  to  group  subex 
pressions,  the  star  means  "zero  or  more  occurrences  of,"  and  the  juxtaposition 
of  letter,  with  the  remainder  of  the  expression  signifies  concatenation. 

The  regular  expressions  are  built  recursively  out  of  smaller  regular  expres 
sions,  using  the  rules  described  below.  Each  regular  expression  r  denotes  a 
language  L(r),  which  is  also  defined  recursively  from  the  languages  denoted  by 
r 's  subexpressions.  Here  are  the  rules  t h at  define  t he  regular  expressions  over 
some  alphabet  £  and  t he  languages  t h at  those  expressions  denote. 

B A S I S:  There  are  two  rules  t h at  form  t he  basis: 

1.  e  is  a  regular  expression,  and  L(e)  is  {e},  t h at  is,  the  language  whose  sole 

member  is  the  empty  string. 

2.  If a  is  a  symbol  in  E,  then  a  is  a  regular  expression,  and  L(a)  =  {a},  t h at 
is,  the  language  with  one  string,  of length  one,  with  a  in  its  one  position. 
Note  t h at  by  convention,  we  use  italics  for  symbols,  and  boldface  for  their 
corresponding  regular  expression.1 

I N D U C T I O N:  There  are  four  parts  to  t he  induction  whereby  larger  regular 
expressions  are  built  from  smaller  ones.  Suppose  r  and  s  are  regular  expressions 
denoting  languages  L(r)  and  L(s),  respectively. 

1.  (r)|(s)  is  a  regular  expression  denoting  the  language  L(r)  U  L(s). 

2.  (r)(s)  is  a  regular  expression  denoting  the  language  L(r)L(s). 

3.  (r)*  is  a  regular  expression  denoting  (L(r))*. 

4.  (r)  is  a  regular  expression  denoting  L(r).  This  last  rule  says  t h at  we  can 
add  additional  pairs  of  parentheses  around  expressions  without  changing 
the  language  they  denote. 

As  defined,  regular  expressions  often  contain  unnecessary  pairs  of  paren 
theses.  We  may  drop  certain  pairs  of  parentheses  if  we  adopt  the  conventions 
t h a t: 

a)  T he  unary  operator  *  has  highest  precedence  and  is  left  associative. 

b)  Concatenation  has  second  highest  precedence  and  is  left  associative. 

h o w e v e r,  when  talking  about  specific  characters  from  the  ASCII  character  set,  we  shall 

generally  use  teletype  font  for  both  the  character  and  its  regular  expression. 

122 

CHAPTER  3. 

LEXICAL  ANALYSIS 

c) 

|  has  lowest  precedence  and  is  left  associative. 

Under  these  conventions,  for  example,  we  may  replace  t he  regular  expression 
(a)|((b)*(c))  by  a|b*c.  Both  expressions  denote  t he  set  of strings  t h at  are  either 
a  single  a  or  are  zero  or  more  6's  followed  by  one  c. 

E x a m p le  3 . 4:  Let  £  =  {a,  6}. 

1.  The  regular  expression  a|b  denotes  the  language  {a,  b}. 

2.  (a|b)(a|b)  denotes  {aa,  ah,  ba,  bb},  the  language  of all  strings  of length  two 
over  t he  alphabet  E.  Another  regular  expression  for  t he  same  language  is 
a a | a b | b a | b b. 

3.  a*  denotes  the  language  consisting  of  all  strings  of  zero  or  more  a's,  t h at 

is,  { e ,a , a a , a a a , . . . }. 

4.  (a|b)*  denotes  the  set  of  all  strings  consisting  of  zero  or  more  instances 
of  a  or  b,  t h at  is,  all  strings  of  a's  and  6's:  {e,a,  b,aa,  ab,  ba,  bb,aaa,...}. 
Another  regular  expression  for  the  same  language  is  (a*b*)*. 

5.  a|a*b  denotes  the  language  {a,  b,  ab,  aab,  aaab,...},  t h at  is,  the  string  a 

and  all  strings  consisting  of  zero  or  more  a's  and  ending  in  b. 

• 

A  language  t h at  can  be  defined  by  a  regular  expression  is  called  a  regular 
set.  If two  regular  expressions  r  and  s  denote  the  same  regular  set,  we  say  they 
are  equivalent  and  write  r  =  s.  For  instance,  (a|b)  =  (b|a).  There  are  a  number 
of  algebraic  laws  for  regular  expressions;  each  law  asserts  t h at  expressions  of 
two  different  forms  are  equivalent.  Figure  3.7  shows  some  of  the  algebraic  laws 
t h at  hold  for  arbitrary  regular  expressions  r,  s,  and  t. 

L AW 

r\s  =  s\r 

D E S C R I P T I ON 

|  is  commutative 

r\(s\t)  = 

(r\s)\t 

|  is  associative 

r(st)  = 

(rs)t 

Concatenation  is  associative 

r(s\t)  =  rs\rt; 

(s\t)r  =  sr\tr  Concatenation  distributes  over  | 

er  =  re  =  r 

r*  =  (r|e)* 

e  is  the  identity  for  concatenation 

e  is  guaranteed  in  a  closure 

*  is  idempotent 

Figure  3.7:  Algebraic  laws  for  regular  expressions 

3.3. 

SPECIFICATION  OF  TOKENS 

123 

3.3.4  Regular  Definitions 

For  notational  convenience,  we  may  wish  to  give  names  to  certain  regular  ex 
pressions  and  use  those  names  in  subsequent  expressions,  as  if  t he  names  were 
themselves  symbols.  If  £  is  an  alphabet  of  basic  symbols,  then  a  regular  defi 
nition  is  a  sequence  of  definitions  of  the  form: 

di 
d2 

dn 

-> 
-» 

n 
r2 

^ 

rn 

where: 

1.  Each  di  is  a  new  symbol,  not  in  E  and  not  the  same  as  any  other  of  the 

cTs,  and 

2.  Each  T{  is  a  regular  expression  over  the  alphabet  E  U  {d\,d2,..  .  , 

to  E  and  the  previously  defined  G T S,  we  avoid  recursive  defini 
By  restricting 
tions,  and  we  can  construct  a  regular  expression  over  E  alone,  for  each  r$.  We 
do  so  by  first  replacing  uses  of  d\  in  r2  (which  cannot  use  any  of the  d's  except 
for  d\),  then  replacing  uses  of  d\  and  d2  in  r-$  by  r\  and  (the  substituted)  r2, 
and  so  on.  Finally,  in  rn  we  replace  each  di,  for  i  —  1 , 2 , . ..  ,n  —  1,  by  t he 
substituted  version  of  r$,  each  of  which  has  only  symbols  of  E. 

E x a m p le  3 . 5:  C  identifiers  are  strings  of letters,  digits,  and  underscores.  Here 
is  a  regular  definition  for  the  language  of  C  identifiers.  We  shall  conventionally 
use  italics  for  the  symbols  defined  in  regular  definitions. 

letter- 
digit 

A | B | - - - | Z | a | b | - - - | z |_ 

-+ 
->  0  j  1  j • • • j  9 

id  —)• 

letter-  (  letter-  \  digit  )* 

E x a m p le  3 . 6:  Unsigned  numbers  (integer  or  floating  point)  are  strings  such 
as  5280,  0 . 0 1 2 3 4,  6.336E4,  or  1.89E-4.  T he  regular  definition 

digit 
digits 

optionalFraction 
optionalExponent 

-+ 

- )• 

number 

-> 

9 

0  |  1 
digit  digit* 
.  digits  |  e 
(  E  (  +  |  -  |  e  )  digits  )  |  e 
digits 

optionalFraction 

optionalExponent 

is  a  precise  specification  for  this  set  of  strings.  T h at  is,  an  optionalFraction  is 
either  a  decimal  point  (dot)  followed  by  one  or  more  digits,  or  it  is  missing  (the 
empty  string).  An  optionalExponent,  if  not  missing,  is  the  letter  E  followed  by 
an  optional  +  or  -  sign,  followed  by  one  or  more  digits.  Note  t h at  at  least  one 
digit  must  follow  the  dot,  so  number  does  not  match  1.,  but  does  match  1.0. 
• 

124 

CHAPTER  3. 

LEXICAL  ANALYSIS 

3.3.5  Extensions  of Regular  Expressions 

Since  Kleene  introduced  regular  expressions  with  t he  basic  operators  for  union, 
concatenation,  and  Kleene  closure  in  the  1950s,  many  extensions  have  been 
added  to  regular  expressions  to  enhance  their  ability  to  specify  string  p a t t e r n s. 
Here  we  mention  a  few  notational  extensions  t h at  were  first  incorporated  into 
Unix  utilities  such  as  Lex  t h at  are  particularly  useful  in  t he  specification  lexical 
analyzers.  The  references  to  this  chapter  contain  a  discussion  of  some  regular-
expression  variants  in  use  today. 

1.  One  or  more 

instances.  T he  unary,  postfix  operator 

+  represents  t he 
positive  closure  of  a  regular  expression  and  its  language.  T h at  is,  if  r  is  a 
regular  expression,  then  ( r )+  denotes  the  language  (L(r))  + .  T he  operator 
+  has  the  same  precedence  and  associativity  as  the  operator  *.  Two  useful 
algebraic  laws,  r*  =  r+\e  and  r+  =  rr*  =  r*r  relate  t he  Kleene  closure 
and  positive  closure. 

2.  Zero  or  one  instance.  The  unary  postfix  operator  ?  means  "zero  or  one 
occurrence."  T h at  is,  r?  is  equivalent  to  r|e,  or  p ut  another  way,  L(r?)  = 
L(r)  U  {e}.  The  ?  operator  has  the  same  precedence  and  associativity  as 
*  and  +. 

3.  Character  classes. 

A  regular  expression  aifal  •  •  •  \an,  where 

the  a^s 

are  each  symbols  of  the  alphabet,  can  be  replaced  by  t he  shorthand 
[aia,2  •  •  - an].  More  importantly,  when  0 1 , 0 2 , . ..  , an  f °rm  a  logical  se 
quence,  e.g.,  consecutive  uppercase  letters,  lowercase  letters,  or  digits,  we 
can  replace  t h em  by  o i - an,  t h at  is,  just  the  first  and  last  separated  by 
a  hyphen.  Thus,  [abc]  is  shorthand  for  a|b|c,  and  [a-z]  is  shorthand  for 
a | b | . - - | z. 

E x a m p le  3 . 7:  Using  these  shorthands,  we  can  rewrite  t he  regular  definition 
of  Example  3.5  as: 

letter. 
digit 
id 

-> 
-> 
-> 

[A-Za-z_] 
[0-9] 
letter-  (  letter  \  digit  )* 

The  regular  definition  of  Example  3.6  can  also  be  simplified: 

->  [0-9] 
digit 
digits  —>•  digit+ 
-»• 

number 

digits (.  digits)?  ( E [+-]?  digits  )? 

• 

3.3. 

SPECIFICATION  OF  TOKENS 

125 

3.3.6  Exercises  for  Section  3.3 

E x e r c i se  3 . 3 . 1:  Consult  the  language  reference  manuals  to  determine  (i)  the 
sets  of  characters  t h at  form  t he  input  alphabet  (excluding  those  t h at  may  only 
appear  in  character  strings  or  comments),  (ii)  the  lexical  form  of  numerical 
constants,  and  (Hi)  t he  lexical  form  of  identifiers,  for  each  of  the  following 
languages:  (a)  C  (b)  C ++  (c)  C#  (d)  Fortran  (e)  Java  (f)  Lisp  (g)  SQL. 

!  E x e r c i se  3 . 3 . 2:  Describe  the  languages  denoted  by  the  following  regular  ex 

pressions: 

a)  a(a|b)*a. 

b)  ((e|a)b*)*. 

c)  (a|b)*a(a|b)(a|b). 

d)  a*ba*ba*ba*. 

!!  e)  (aa|bb)*((ab|ba)(aa|bb)*(ab|ba)(aa|bb)*)*. 

E x e r c i se  3 . 3 . 3:  In  a  string  of  length  n,  how  many  of  t he  following  are  there? 

a)  Prefixes. 

b)  Suffixes. 

c)  Proper  prefixes. 

!  d)  Substrings. 

!  e)  Subsequences. 

E x e r c i se  3 . 3 . 4:  Most  languages  are  case  sensitive,  so  keywords  can  be  written 
only  one  way,  and  the  regular  expressions  describing  their  lexeme  is  very  simple. 
However,  some  languages,  like  SQL,  are  case  insensitive,  so  a  keyword  can  be 
written  either  in  lowercase  or  in  uppercase,  or  in  any  mixture  of  cases.  Thus, 
the  SQL  keyword  SELECT  can  also  be  written  s e l e c t,  S e l e c t,  or  sElEcT,  for 
instance.  Show  how  to  write  a  regular  expression  for  a  keyword  in  a  case-
insensitive  language.  Illustrate  t he  idea  by  writing  t he  expression  for  "select" 
in  SQL. 

!  E x e r c i se  3 . 3 . 5:  Write  regular  definitions  for  the  following  languages: 

a)  All  strings  of  lowercase  letters  t h at  contain  the  five  vowels  in  order. 

b)  All  strings  of  lowercase  letters  in  which  the  letters  are  in  ascending  lexi 

cographic  order. 

c)  Comments,  consisting  of  a  string  surrounded  by  /*  and  * /,  without  an 

intervening  * /,  unless  it  is  inside  double-quotes  ("). 

126 

CHAPTER  3. 

LEXICAL  ANALYSIS 

!!  d)  All  strings  of  digits  with  no  repeated  digits.  Hint:  Try  this  problem  first 

with  a  few  digits,  such  as  { 0 , 1 , 2 }. 

!!  e)  All  strings  of  digits  with  at  most  one  repeated  digit. 

!!  f)  All  strings  of  a's  and  6's  with  an  even  number  of  a's  and  an  odd  number 

of 6's. 

g)  The  set  of Chess  moves,  in  the  informal  notation,  such  as  p - k4  or  k b p x q n. 

!!  h)  All  strings  of a's  and  6's  t h at  do  not  contain  the  substring  a66. 

i)  All  strings  of  a's  and  6's  t h at  do  not  contain  the  subsequence  a66. 

E x e r c i se  3 . 3 . 6:  Write  character  classes  for  the  following  sets  of  characters: 

a)  The  first  ten  letters  (up  to  "j")  in  either  upper  or  lower  case. 

b)  The  lowercase  consonants. 

c)  T he  "digits"  in  a  hexadecimal  number  (choose  either  upper  or  lower  case 

for  the  "digits"  above  9 ). 

d)  The  characters  t h at  can  appear  at  the  end  of a legitimate  English  sentence 

(e.g.,  exclamation  point). 

The  following  exercises,  up  to  and  including  Exercise  3.3.10,  discuss  the 
extended  regular-expression  notation  from  Lex  (the  lexical-analyzer  generator 
t h at  we  shall  discuss  extensively  in  Section  3.5).  T he  extended  notation  is  listed 
in  Fig.  3.8. 

E x e r c i se  3 . 3 . 7:  Note  t h at  these  regular  expressions  give  all  of  t he  following 
symbols  (operator  characters)  a  special  meaning: 

\  » 

.  ~  $ [

]*  +  ? {} 

I 

/ 

Their  special  meaning  must  be  turned  off  if  they  are  needed  to  represent  them 
selves  in  a  character  string.  We  can  do  so  by  quoting  the  character  within  a 
string of length  one  or  more;  e.g.,  t he  regular  expression  "**"  matches  the  string 
**.  We  can  also  get  the  literal  meaning  of  an  operator  character  by  preceding 
it  by  a  backslash.  Thus,  t he  regular  expression  \ * \*  also  matches  t he  string 
**.  Write  a  regular  expression  t h at  matches  t he  string  " \. 

In  Lex,  a  complemented  character  class  represents  any  char 
E x e r c i se  3 . 3 . 8: 
acter  except  the  ones  listed  in  the  character  class.  We  denote  a  complemented 
class  by  using  "  as  the  first  character;  this  symbol  (caret)  is  not  itself  part  of 
the  class  being  complemented,  unless  it  is  listed  within  the  class  itself.  Thus, 
[~A-Za-z]  matches  any  character  t h at  is  not  an  uppercase  or  lowercase  letter, 
and  [~\~]  represents  any  character  b ut  the  caret  (or  newline,  since  newline 
cannot  be  in  any  character  class).  Show  t h at  for  every  regular  expression  with 
complemented  character  classes,  there  is  an  equivalent  regular  expression  with 
out  complemented  character  classes. 

3.3. 

SPECIFICATION  OF  TOKENS 

127 

E X P R E S S I ON 

M A T C H ES 

E X A M P LE 

c 

V 
l l g ll 

$ 

[*] 

r* 

r+ 

r? 

t he  one  non-operator  character  c 

character  c  literally 

string  s  literally 

any  character  but  newline 

beginning  of  a  line 

end  of  a  line 

a 
\* 
"**" 

a.  *b 

~abc 

abc$ 

any  one  of  t he  characters  in  string  s 

[ a b c] 

any  one  character  not  in  string  s 

[~abc] 

zero  or  more  strings  matching  r 

one  or  more  strings  matching  r 

zero  or  one  r 

a* 

a+ 

a? 

r{m,  n} 

between  m  and  n  occurrences  of  r 

a[ l, 5] 

rir2 
r\  |  r2 
(r) 

ri/r2 

an  ?*i  followed  by  an  r2 

an  ri  or  an  r2 

same  as  r 

7*1  when  followed  by  r2 

ab 

a|b 

( a l b) 

a b c/ 1 23 

Figure  3.8:  Lex  regular  expressions 

!  E x e r c i se  3 . 3 . 9:  The  regular  expression  r{m,  n]  matches  from  m  to  n  occur 
rences  of the  p a t t e rn  r.  For  example,  a [ 1 , 5]  matches  a  string  of one  to  five  a's. 
Show  t h at  for  every  regular  expression  containing  repetition  operators  of  this 
form,  there  is  an  equivalent  regular  expression  without  repetition  operators. 

!  E x e r c i se  3 . 3 . 1 0:  T he  operator  "  matches  the  left  end  of a  line,  and  $  matches 
the  right  end  of  a  line.  The  operator  "  is  also  used  to  introduce  complemented 
character  classes,  but  the  context  always  makes  it  clear  which  meaning  is  in 
tended.  For  example,  ~ [ ~ a e i o u ] *$  matches  any  complete  line  t h at  does  not 
contain  a  lowercase  vowel. 

a)  How  do  you  tell  which  meaning  of  A  is  intended? 

b)  Can  you  always  replace  a  regular  expression  using  t he  "  and  $  operators 

by  an  equivalent  expression  t h at  does  not  use  either  of  these  operators? 

!  E x e r c i se  3 . 3 . 1 1:  T he  UNIX  shell  command  sh  uses  the  operators  in  Fig.  3.9 
in  filename  expressions  to  describe  sets  of file names.  For  example,  the  filename 
expression  * .o  matches  all  file  names  ending  in 
.o;  s o r t l .?  matches  all  file 
names  of  the  form  s o r t. c,  where  c  is  any  character.  Show  how  sh  filename 

128 

CHAPTER  3. 

LEXICAL  ANALYSIS 

E X P R E S S I ON 

M A T C H ES 

E X A M P LE 

V 

V 
* 
? 

[s] 

string  s  literally 

'V 
character  c  literally  V 
any  string 

*. o 

any  character 

s o r t l .? 

any  character  in  s 

s o r t l . [ c s o] 

Figure  3.9:  Filename  expressions  used  by  the  shell  command  sh 

expressions  can  be  replaced  by  equivalent  regular  expressions  using  only  t he 
basic  union,  concatenation,  and  closure  operators. 

!  E x e r c i se  3 . 3 . 1 2:  SQL  allows  a  rudimentary  form  of  p a t t e r ns  in  which  two 
characters  have  special  meaning:  underscore  (_)  stands  for  any  one  character 
and  percent-sign  (%)  stands  for  any  string  of  0  or  more  characters.  In  addition, 
t he  programmer  may  define  any  character,  say  e,  to  be  the  escape  character,  so 
e  preceding  an  e  preceding  _,  %  or  another  e  gives  t he  character  t h at  follows  its 
literal  meaning.  Show  how  to  express  any  SQL  p a t t e rn  as  a  regular  expression, 
given  t h at  we  know  which  character  is  the  escape  character. 

3.4  Recognition  of Tokens 

In  t he  previous  section  we  learned  how  to  express  p a t t e r ns  using  regular  expres 
sions.  Now,  we  must  study  how  to  take  t he  p a t t e r ns  for  all  the  needed  tokens 
and  build  a  piece  of  code  t h at  examines  the  input  string  and  finds  a  prefix  t h at 
is  a  lexeme  matching  one  of  the  patterns.  Our  discussion  will  make  use  of  the 
following  running  example. 

stmt  —>• 

| 
I 
expr  —»• 

if  expr  t h en  stmt 
if  expr  t h en  stmt  e l se  stmt 

e 
term  r e l op 

term 

term 

| 
-> 
| 

term 
id 
n u m b er 

Figure  3.10:  A  grammar  for  branching  statements 

E x a m p le  3 . 8:  T he  grammar  fragment  of  Fig.  3.10  describes  a  simple  form 
of  branching  statements  and  conditional  expressions.  This  syntax  is  similar  to 
t h at  of  the  language  Pascal,  in  t h at  t h en  appears  explicitly  after  conditions. 

3.4. 

RECOGNITION  OF  TOKENS 

129 

For  r e l o p,  we  use  t he  comparison  operators  of  languages  like  Pascal  or  SQL, 
where  =  is  "equals"  and  <>  is  "not  equals,"  because  it  presents  an  interesting 
structure  of  lexemes. 

T he  terminals  of  the  grammar,  which  are  if,  t h e n,  else,  r e l o p,  id,  and 
n u m b e r,  are the  names  of tokens  as  far  as  the  lexical  analyzer is  concerned.  The 
p a t t e r ns  for  these  tokens  are  described  using  regular  definitions,  as  in  Fig.  3.11. 
T he  p a t t e r ns  for  id  and  number  are  similar  to  what  we  saw  in  Example  3.7. 

-> 

-> 

digit 
digits 
number 
letter 
id 

if 
then 
else 
relop 

[0-9] 
digit+ 
digits  (.  digits)?  (  E  [+-]?  digits  )? 
[A-Za-z] 
letter  (  letter  \  digit  )* 
if 
t h en 
e l se 
< 1 > 1 <= 1 >= 1 = 1 <> 

Figure  3.11:  P a t t e r ns  for  tokens  of  Example  3.8 

For  this  language,  the  lexical  analyzer  will  recognize  the  keywords  if,  then, 
and  e l s e,  as  well  as  lexemes  t h at  match  the  patterns  for  relop,  id,  and  number. 
To  simplify  matters,  we  make  the  common  assumption  t h at  keywords  are  also 
t h at  is,  they  are  not  identifiers,  even  though  their  lexemes 
reserved  words: 
match  the  p a t t e rn  for  identifiers. 

In  addition,  we  assign  t he  lexical  analyzer  t he  job  of  stripping  out  white-

space,  by  recognizing  the  "token"  ws  defined  by: 

ws  -»  (  blank  |  t ab  j  n e w l i ne  )+ 

Here,  blank,  t a b,  and  n e w l i ne  are  abstract  symbols  t h at  we  use  to  express 
the  ASCII  characters  of  the  same  names.  Token  ws  is  different  from  the  other 
tokens  in  t h a t,  when  we  recognize it,  we  do  not  return  it  to  the  parser,  but  rather 
restart  t he  lexical  analysis  from  the  character  t h at  follows  the  whitespace.  It  is 
the  following  token  t h at  gets  returned  to  t he  parser. 

Our  goal  for  t he  lexical  analyzer  is  summarized  in  Fig.  3.12.  T h at  table 
shows,  for  each  lexeme  or  family  of  lexemes,  which  token  name  is  returned  to 
t he  parser  and  what  a t t r i b u te  value,  as  discussed  in  Section  3.1.3,  is  returned. 
Note  t h at  for  the  six  relational  operators,  symbolic  constants  LT,  LE,  and  so 
on  are  used  as  t he  a t t r i b u te  value,  in  order  to  indicate  which  instance  of  t he 
token  r e l op  we  have  found.  T he  particular  operator  found  will  influence  t he 
code  t h at  is  o u t p ut  from  the  compiler. 

• 

130 

CHAPTER  3. 

LEXICAL  ANALYSIS 

L E X E M ES 

T O K EN  N A ME 

A T T R I B U TE  V A L UE 

Any  ws 
if 
t h en 
e l se 
Any  id 
Any  number 
< 
<= 

= 
<> 
> 
>= 

-
if 
t h en 
e l se 
id 
n u m b er 
r e l op 
r e l op 
r e l op 
r e l op 
r e l op 
r e l op 

-
-
-
-
Pointer  to  table  entry 
Pointer  to  table  entry 
LT 

LE 

EQ 

NE 

GT 

Figure  3.12:  Tokens,  their  patterns,  and  a t t r i b u te  values 

3.4.1  Transition  Diagrams 

As  an  intermediate  step  in  t he  construction  of a lexical  analyzer,  we  first  convert 
p a t t e r ns  into  stylized  flowcharts,  called  "transition  diagrams."  In  this  section, 
we  perform  the  conversion  from  regular-expression  p a t t e r ns  to  transition  dia 
grams  by  hand,  but  in  Section  3.6,  we  shall  see  t h at  there  is  a  mechanical  way 
to  construct  these  diagrams  from  collections  of  regular  expressions. 

Transition  diagrams  have  a  collection  of  nodes  or  circles,  called  states.  Each 
state  represents  a  condition  t h at  could  occur  during  the  process  of  scanning 
the  input  looking  for  a  lexeme  t h at  matches  one  of  several  patterns.  We  may 
think  of  a  state  as  summarizing  all  we  need  to  know  about  what  characters  we 
have  seen  between  the  lexemeBegin  pointer  and  the  forward  pointer  (as  in  t he 
situation  of  Fig.  3.3). 

Edges  are  directed  from  one  state  of  t he  transition  diagram  to  another. 
Each  edge  is  labeled  by  a  symbol  or  set  of  symbols. 
If  we  are  in  some  state 
5,  and  t he  next  input  symbol  is  a,  we  look  for  an  edge  out  of  s t a te  s  labeled 
by  a  (and  perhaps  by  other  symbols,  as  well). 
If  we  find  such  an  edge,  we 
advance  the  forward  pointer  arid  enter  t he  state  of  t he  transition  diagram  to 
which  t h at  edge  leads.  We  shall  assume  t h at  all  our  transition  diagrams  are 
deterministic,  meaning  t h at  there  is  never  more  t h an  one  edge  out  of  a  given 
state  with  a  given  symbol  among  its  labels.  Starting  in  Section  3.5,  we  shall 
relax  t he  condition  of  determinism,  making  life  much  easier  for  t he  designer 
of  a  lexical  analyzer,  although  trickier  for  t he  implementer.  Some  important 
conventions  about  transition  diagrams  are: 

1.  Certain  states  are  said  to  be  accepting,  or final.  These  states  indicate  t h at 
a  lexeme  has  been  found,  although  the  actual  lexeme  may  not  consist  of 
all  positions  between  the  lexemeBegin  and  forward  pointers.  We  always 

3.4.  RECOGNITION 

OF 

TOKENS 

131 

indicate  an  accepting  state  by  a  double  circle,  and  if  there  is  an  action 
to  be  taken  —  typically  returning  a  token  and  an  a t t r i b u te  value  to  the 
parser  —  we  shall  attach  t h at  action  to  the  accepting  state. 

2.  In  addition,  if  it  is  necessary  to  retract  the  forward  pointer  one  position 
(i.e.,  the  lexeme  does  not  include  the  symbol  t h at  got  us  to  the  accepting 
state),  then  we  shall  additionally  place  a  *  near  t h at  accepting  state.  In 
our  example,  it  is  never  necessary  to  retract  forward  by  more  t h an  one 
position,  but  if it  were,  we  could  attach  any  number  of *'s  to  t he  accepting 
state. 

3.  One  state  is  designated  the  start  state,  or  initial  state;  it  is  indicated  by 
an  edge,  labeled  "start,"  entering  from  nowhere.  T he  transition  diagram 
always  begins  in  the  start  state  before  any  input  symbols  have  been  read. 

E x a m p le  3 . 9:  Figure  3.13  is  a  transition  diagram  t h at  recognizes  t he  lexemes 
matching the token r e l o p.  We  begin in state  0,  t he  start  state.  If we  see  <  as t he 
first  input  symbol,  then  among  the  lexemes  t h at  match  the  p a t t e rn  for  r e l op 
we  can  only  be  looking  at  <,  <>,  or  <=.  We  therefore  go  to  state  1,  and  look  at 
t he  next  character.  If  it  is  =,  then  we  recognize  lexeme  <=,  enter  state  2,  and 
return  the  token  r e l op  with  a t t r i b u te  LE,  the  symbolic  constant  representing 
this  particular  comparison  operator.  If  in  state  1  the  next  character  is  >,  then 
instead  we  have  lexeme  <>,  and  enter  state  3  to  return  an  indication  t h at  t he 
not-equals  operator  has  been  found.  On  any  other  character,  t he  lexeme  is  <, 
and  we  enter  state  4  to  return  t h at  information.  Note,  however,  t h at  state  4 
has  a  *  to  indicate  t h at  we  must  retract  the  input  one  position. 

Figure  3.13:  Transition  diagram  for  r e l op 

On  t he  other  hand,  if in  state  0  the  first  character  we  see  is  =,  then  this  one 
character  must  be  the  lexeme.  We  immediately  return  t h at  fact  from  state  5. 

132 

CHAPTER  3. 

LEXICAL  ANALYSIS 

T he  remaining  possibility  is  t h at  the  first  character  is  >.  Then,  we  must  enter 
state  6  and  decide,  on  the  basis  of t he  next  character,  whether  t he  lexeme  is  >= 
(if  we  next  see  the  =  sign),  or  just  >  (on  any  other  character).  Note  t h at  if,  in 
s t a te  0,  we  see  any  character  besides  <,  =,  or  >,  we  can  not  possibly  be  seeing 
a  r e l op  lexeme,  so  this  transition  diagram  will  not  be  used. 

• 

3.4.2  Recognition  of Reserved  Words  and  Identifiers 

Recognizing  keywords  and  identifiers  presents  a  problem.  Usually,  keywords  like 
if  or  t h en  are  reserved  (as  they  are  in  our  running  example),  so  they  are  not 
identifiers  even  though  they  look  like  identifiers.  Thus,  although  we  typically 
use  a  transition  diagram  like  t h at  of  Fig.  3.14  to  search  for  identifier  lexemes, 
this  diagram  will  also  recognize  the  keywords  if,  then,  and  e l se  of our  running 
example. 

letter or  digit 

start 

letter  C^)  other 

/^zx  * 

*\9J 

*\10) 

K®) 

return(getToken(), 

installlD  ()) 

Figure  3.14:  A  transition  diagram  for  id's  and  keywords 

There  are  two  ways  t h at  we  can  handle  reserved  words  t h at  look  like  iden 

tifiers: 

1.  Install  the  reserved  words  in  the  symbol  table  initially.  A  field  of  the 
symbol-table  entry  indicates  t h at  these  strings  are  never  ordinary  identi 
fiers,  and  tells  which  token  they  represent.  We  have  supposed  t h at  this 
method  is  in  use  in  Fig.  3.14.  W h en  we  find  an  identifier,  a  call  to  installlD 
places  it  in  the  symbol  table  if it  is  not  already  there  and  returns  a  pointer 
to  the  symbol-table  entry  for  t he  lexeme  found.  Of  course,  any  identifier 
not  in  the  symbol  table  during  lexical  analysis  cannot  be  a  reserved  word, 
so  its  token  is  id.  The  function  getToken  examines  t he  symbol  table  entry 
for  t he  lexeme  found,  and  returns  whatever  token  n a me  the  symbol  table 
says  this  lexeme  represents  —  either  id  or  one  of t he  keyword  tokens  t h at 
was  initially  installed  in  the  table. 

2.  Create  separate  transition  diagrams  for  each  keyword;  an  example  for 
t he  keyword  t h en  is  shown  in  Fig.  3.15.  Note  t h at  such  a  transition 
diagram  consists  of  states  representing  the  situation  after  each  successive 
letter  of  t he  keyword  is  seen,  followed  by  a  test  for  a  "nonletter-or-digit," 
i.e.,  any  character  t h at  cannot  be  t he  continuation  of  an  identifier.  It  is 
necessary  to  check  t h at  t he  identifier  has  ended,  or  else  we  would  r e t u rn 
token  t h en  in  situations  where  t he  correct  token  was  id,  with  a  lexeme 
like  t h e n e x t v a l ue  t h at  has  t h en  as  a  proper  prefix. 
If  we  adopt  this 
approach,  then  we  must  prioritize  the  tokens  so  t h at  the  reserved-word 

3.4. 

RECOGNITION  OF  TOKENS 

133 

tokens  are  recognized  in  preference  to  id,  when  the  lexeme  matches  both 
p a t t e r n s.  We  do  not  use  this  approach  in  our  example,  which  is  why  t he 
states  in  Fig.  3.15  are  unnumbered. 

Figure  3.15:  Hypothetical  transition  diagram  for  the  keyword  t h en 

3.4.3  Completion  of  the  Running  Example 

T he  transition  diagram  for  i d 's  t h at  we  saw  in  Fig.  3.14  has  a  simple  structure. 
Starting  in  state  9,  it  checks  t h at  the  lexeme  begins  with  a  letter  and  goes  to 
state  10  if so.  We  stay in  state  10  as  long  as  the  input  contains  letters  and  digits. 
When  we  first  encounter  anything  but  a  letter  or  digit,  we  go  to  state  11  and 
accept  the  lexeme  found.  Since  the  last  character  is  not  part  of  the  identifier, 
we  must  retract  the  input  one  position,  and  as  discussed  in  Section  3.4.2,  we 
enter  what  we  have  found  in  the  symbol  table  and  determine  whether  we  have 
a  keyword  or  a  true  identifier. 

The  transition  diagram  for  token  n u m b er  is  shown  in  Fig.  3.16,  and  is  so 
far  the  most  complex  diagram  we  have  seen.  Beginning  in  state  12,  if  we  see  a 
digit,  we  go  to  state  13.  In  t h at  state,  we  can  read  any  number  of  additional 
digits.  However,  if we  see  anything  but  a  digit  or  a  dot,  we  have  seen  a  number 
in  the  form  of  an  integer;  123  is  an  example.  T h at  case  is  handled  by  entering 
state  20,  where  we  return  token  n u m b er  and  a  pointer  to  a  table  of  constants 
where  the  found  lexeme  is  entered.  These  mechanics  are  not  shown  on  the 
diagram  but  are  analogous  to  the  way  we  handled  identifiers. 

digit 

digit 

digit 

start 

Figure  3.16:  A  transition  diagram  for  unsigned  numbers 

If  we  instead  see  a  dot  in  state  13,  then  we  have  an  "optional  fraction." 
State  14  is  entered,  and  we  look  for  one  or  more  additional  digits;  state  15  is 
used  for  t h at  purpose.  If  we  see  an E,  then  we  have  an  "optional  exponent," 
whose  recognition  is  the  job  of  states  16  through  19.  Should  we,  in  state  15, 
instead  see  anything  b ut E  or  a  digit,  then  we  have  come  to  t he  end  of  t he 
fraction,  there  is  no  exponent,  and  we  return  the  lexeme  found,  via  state  21. 

134 

CHAPTER  3. 

LEXICAL  ANALYSIS 

The  final  transition  diagram,  shown  in  Fig.  3.17,  is  for  whitespace.  In  t h at 
diagram,  we  look for one  or more  "whitespace"  characters,  represented  by  d e l im 
in  t h at  diagram  —  typically  these  characters  would  be  blank,  t a b,  newline,  and 
perhaps  other  characters  t h at  are  not  considered  by  t he  language  design  to  be 
part  of  any  token. 

delim 

Figure  3.17:  A  transition  diagram  for  whitespace 

Note  t h at  in  state  24,  we  have  found  a  block  of  consecutive  whitespace 
characters,  followed  by  a  nonwhitespace  character.  We  retract  t he  input  to 
begin  at  the  nonwhitespace,  but  we  do  not  return  to  the  parser.  Rather,  we 
must  restart  the  process  of  lexical  analysis  after  the  whitespace. 

3.4.4  Architecture  of a  Transition-Diagram-Based  Lexical 

Analyzer 

There  are  several  ways  t h at  a  collection  of  transition  diagrams  can  be  used 
to  build  a  lexical  analyzer.  Regardless  of  the  overall  strategy,  each  state  is 
represented  by  a  piece  of  code.  We  may  imagine  a  variable  s t a te  holding  the 
number  of  the  current  s t a te  for  a  transition  diagram.  A  switch  based  on  t he 
value  of  s t a te  takes  us  to  code  for  each  of  t he  possible  states,  where  we  find 
the  action  of  t h at  state.  Often,  the  code  for  a  state  is  itself  a  switch  statement 
or  multiway  branch  t h at  determines  t he  next  state  by  reading  and  examining 
the  next  input  character. 

E x a m p le  3 . 1 0:  In  Fig.  3.18  we  see  a  sketch  of  g e t R e l o p O,  a  C ++  function 
whose job  is  to  simulate  the  transition  diagram  of Fig.  3.13  and  return  an  object 
of type  TOKEN,  t h at  is,  a pair  consisting  of the  token  name  (which  must  be  r e l op 
in  this  case)  and  an  a t t r i b u te  value  (the  code  for  one  of  t he  six  comparison 
operators  in  this  case).  g e t R e l o pO  first  creates  a  new  object  r et  Token  and 
initializes  its  first  component  to  RELOP,  the  symbolic  code  for  token  r e l o p. 

We  see  t he  typical  behavior  of  a  state  in  case  0,  the  case  where  t he  current 
state  is  0.  A  function  n e x t C h a r ()  obtains  t he  next  character  from  t he  input 
and  assigns  it  to  local  variable  c.  We  then  check  c  for  the  three  characters  we 
expect  to  find,  making  t he  state  transition  dictated  by  t he  transition  diagram 
of  Fig.  3.13  in  each  case.  For  example,  if  t he  next  input  character  is  =,  we  go 
to  state  5. 

If the  next  input  character  is  not  one  t h at  can  begin  a  comparison  operator, 

then  a function  f a il ()  is  called.  W h at  f a il ()  does  depends  on  t he  global  error-
recovery  strategy  of  t he  lexical  analyzer.  It  should  reset  t he  f o r w a rd  pointer 
to  lexemeBegin,  in  order  to  allow  another  transition  diagram  to  be  applied  to 

3.4. 

RECOGNITION  OF  TOKENS 

135 

TOKEN  g e t R e l o pO 

{ 

TOKEN retToken =  new(RELOP); 
while(1)  {  /*  repeat  character processing until  a return 

or  failure  occurs  */ 

switch(state)  { 

case  0:  c  = n e x t C h a r Q; 

if  (  c ==  '<»  )  state =  1; 
else  if  (  c ==  '='  )  state =  5; 
else  if  (  c  ==  '>'  )  state  -  6; 
else fail();  /*  lexeme  is  not  a relop  */ 
break; 

case  1:  ... 

case 8:  retract(); 

retToken.attribute  =  GT; 

return(retToken); 

Figure 3.18:  Sketch  of implementation  of relop  transition  diagram 

the  true  beginning  of  the  unprocessed  input. 
It  might  then  change  t he  value 
of state  to  be  t he  start  state  for  another  transition  diagram,  which  will  search 
for  another  token.  Alternatively,  if  there  is  no  other  transition  diagram  t h at 
remains  unused, fail()  could  initiate  an  error-correction  phase  t h at  will  try 
to  repair  the  input  and  find  a  lexeme,  as  discussed  in  Section 3.1.4. 

We  also  show  the  action  for  state 8  in  Fig. 3.18.  Because  state 8  bears  a  *, 
we  must  retract  t he  input  pointer  one  position  (i.e.,  put  c  back  on  t he  input 
stream).  T h at  task  is  accomplished  by  the  function retract ( ).  Since  state 8 
represents  t he  recognition  of  lexeme  >=,  we  set  the  second  component  of  the 
returned object,  which we suppose is  named attribute,  to  GT,  the  code for this 
operator. 

• 

To  place  t he  simulation  of  one  transition  diagram  in  perspective,  let  us 
consider  the  ways  code  like  Fig. 3.18  could  fit  into  t he  entire  lexical  analyzer. 

1.  We  could  arrange for  the  transition  diagrams  for  each token  to  be  tried  se 

quentially.  Then,  t he  function f ail()  of  Example 3.10  resets  the  pointer 
forward  and  starts  the  next  transition  diagram,  each  time  it  is  called. 
This  method  allows  us  to  use  transition  diagrams  for  the  individual  key 
words,  like  the  one  suggested  in  Fig. 3.15.  We  have  oniy  to  use  these 
before  we  use  t he  diagram  for  id,  in  order  for  the  keywords  to  be  reserved 
words. 

136 

CHAPTER  3. 

LEXICAL  ANALYSIS 

2.  We  could  run  the  various  transition  diagrams  "in  parallel,"  feeding  t he 
next  input  character  to  all  of  them  and  allowing  each  one  to  make  what 
ever  transitions  it  required. 
If  we  use  this  strategy,  we  must  be  careful 
to  resolve  the  case  where  one  diagram  finds  a  lexeme  t h at  matches  its 
p a t t e r n,  while  one  or  more  other  diagrams  are  still  able  to  process  input. 
T he  normal  strategy  is  to  take  the  longest  prefix  of t he  input  t h at  matches 
any  pattern.  T h at  rule  allows  us  to  prefer  identifier  t h e n e xt  to  keyword 
t h e n,  or  t he  operator  ->  to  -,  for  example. 

3.  The  preferred  approach,  and  t he  one  we  shall  take  up  in  t he  following 
sections,  is  to  combine  all  the  transition  diagrams  into  one.  We  allow  t he 
transition  diagram  to  read  input  until  there  is  no  possible  next  state,  and 
then  take  the  longest  lexeme  t h at  matched  any  p a t t e r n,  as  we  discussed 
in  item  (2)  above. 
In  our  running  example,  this  combination  is  easy, 
because  no  two  tokens  can  start  with  t he  same  character;  i.e.,  t he  first 
character  immediately  tells  us  which  token  we  are  looking  for.  Thus,  we 
could  simply  combine  states  0,  9,  12,  and  22  into  one  start  state,  leaving 
other  transitions  intact.  However,  in  general,  the  problem  of  combining 
transition  diagrams  for  several  tokens  is  more  complex,  as  we  shall  see 
shortly. 

3.4.5  Exercises  for  Section  3.4 

E x e r c i se  3 . 4 . 1:  Provide  transition  diagrams  to  recognize  the  same  languages 
as  each  of  t he  regular  expressions  in  Exercise  3.3.2. 

E x e r c i se  3 . 4 . 2:  Provide  transition  diagrams  to  recognize  the  same  languages 
as  each  of  t he  regular  expressions  in  Exercise  3.3.5. 

T he  following  exercises,  up  to  Exercise  3.4.12,  introduce  the  Aho-Corasick 
algorithm  for  recognizing  a  collection  of  keywords  in  a  text  string  in  time  pro 
portional  to  t he  length  of  the  text  and  the  sum  of  the  length  of  the  keywords. 
This  algorithm  uses  a  special  form  of  transition  diagram  called  a  trie.  A  trie  is 
a  tree-structured  transition  diagram  with  distinct  labels  on  t he  edges  leading 
from  a  node  to  its  children.  Leaves  of  the  trie  represent  recognized  keywords. 

Knuth,  Morris,  and  P r a tt  presented  an  algorithm  for  recognizing  a  single 
keyword  &i&2  •  •  • K  in  a  text  string.  Here  the  trie  is  a  transition  diagram  with 
n  states,  0  through  n.  State  0  is  the  initial  state,  and  state  n  represents  ac 
ceptance,  t h at  is,  discovery  of  the  keyword.  From  each  state  s  from  0  through 
n  -  1,  there  is  a  transition  to  state  s  +  1,  labeled  by  symbol  ba+i.  For  example, 
the  trie  for  the  keyword  a b a b aa  is: 
a 

^ 

^ 

a 

_ 

b 

a 

b 

a 

® — K D — - ® — K i > — ® — - d >-

In  order  to  process  text  strings  rapidly  and  search  those  strings  for  a  key 

word,  it  is useful to define,  for keyword &i&2  •  •  • &n  and position  s  in t h at  keyword 
f(s),  computed  as  in 
(corresponding  to  state  s  of  its  trie),  a  failure  function, 

3.4. 

RECOGNITION  OF  TOKENS 

137 

Fig. 3.19.  T he  objective  is  t h at  &i&2-"  •&/(*) 
ls  the  longest  proper  prefix  of 
&1&2  •  •  • bs  t h at  is  also  a  suffix  of b\b2  •  •  • bs.  The  reason  f(s)  is  important  is  t h at 
if we  are  trying  to  match  a  text  string  for  61&2  •  •  • bn,  and  we  have  matched  the 
first  s  positions,  but  we  then  fail  (i.e.,  the  next  position  of  the  text  string  does 
not  hold  bs+i),  then  f(s)  is  the  longest  prefix  of  &1&2  •  *  •  bn  t h at  could  possibly 
m a t ch  t he  text  string  up  to  the  point  we  are  at.  Of course,  the  next  character  of 
the  text  string  must  be  &/(s)+i,  or  else  we  still  have  problems  and  must  consider 
a  yet  shorter  prefix,  which  will  be  &/(/(s)). 

t  = 0; 
/ ( 1 ) = 0; 

1) 
2) 
3)  for  (s  = 1;  s  <  n;  s  +  +)  { 
4) 
5) 
6) 
7) 

t  =  t  +  l; 
f(s + 1)  = t; 

while  (t > 0  kk  bs+1  ! =  bt+i)  t  =  fit); 
if (6s +i  ==  bt+i)  { 

} 

8) 

else  f(s  + 1)  = 0; 

} 

Figure 3.19:  Algorithm  to  compute  the  failure  function  for  keyword 6162 • • • bn 

As  an  example,  the  failure  function  for  the  trie  constructed  above for ababaa 

is: 

s 

f{s) 

3  4  5 

1  2 
0  0  1  2 

6 
3  1 

For instance,  states 3 and 1  represent prefixes aba and a, respectively. /(3) = 1 
because a  is  the  longest  proper  prefix  of aba  t h at  is  also  a  suffix  of aba.  Also, 
/ ( 2) = 0,  because  the  longest  proper  prefix  of ab  t h at  is  also  a  suffix  is  the 
empty  string. 

Exercise 3.4.3:  Construct  the  failure  function  for  the  strings: 

a)  abababaab. 

b)  aaaaaa. 

c)  abbaabb. 

! Exercise 3.4.4:  Prove,  by  induction  on  s,  t h at  t he  algorithm  of  Fig. 3.19 

correctly  computes  the  failure  function. 

!! Exercise 3.4.5:  Show  t h at  the  assignment  t  =  f{t)  in  line (4)  of  Fig. 3.19  is 
executed  at  most  n  times.  Show  t h at  therefore,  the  entire  algorithm  takes  only 
0(n)  time  on  a  keyword  of  length  n. 

138 

CHAPTER  3. 

LEXICAL  ANALYSIS 

in  time  0(m) 

Having  computed  the  failure  function  for  a  keyword  bib2  •  •  •  bn,  we  can  scan 
a  string  a\a2---am 
to  tell  whether  t he  keyword  occurs  in  t he 
string.  T he  algorithm,  shown  in  Fig.  3.20,  slides  the  keyword  along  t he  string, 
trying  to  make  progress  by  matching  t he  next  character  of t he  keyword  with  the 
next  character  of t he  string.  If it  cannot  do  so  after  matching  s  characters,  then 
it  "slides"  the  keyword  right  s  —  f(s)  positions,  so  only  the  first  / ( s)  characters 
of  t he  keyword  are  considered  matched  with  t he  string. 

1) 
2) 
3) 
4) 
5) 

6) 

s  =  0; 
for  (i  =  1;  i  <  m;  i++)  { 
w h i le  (s  >  0 
if,(a*  ==  b8+i)  s  =  s  +  1; 
if  (s  ==  n)  r e t u rn  "yes"; 

a{  !  =  bs+1)  s  =  f(s); 

} 
r e t u rn  "no"; 

Figure  3.20:  T he  K MP  algorithm  tests  whether  string  a\a2  -  ••am  contains  a 
single  keyword  b\b2  •  •  •  bn  as  a  substring  in  0(m  +  n)  time 

E x e r c i se  3 . 4 . 6:  Apply  Algorithm  K MP  to  test  whether  keyword  ababaa  is  a 
substring  of: 

a)  abababaab. 

b)  abababbaa. 

!!  E x e r c i se  3 . 4 . 7:  Show  t h at  the  algorithm  of  Fig.  3.20  correctly  tells  whether 
the  keyword  is  a  substring  of  t he  given  string.  Hint:  proceed  by  induction  on 
i.  Show  t h at  for  all  i,  t he  value  of  s  after  line  (4)  is  t he  length  of  t he  longest 
prefix  of  the  keyword  t h at  is  a  suffix  of  a\a2  •  •  •  a^. 

!!  E x e r c i se  3 . 4 . 8:  Show  t h at  t he  algorithm  of  Fig.  3.20  runs  in  time  0(m  +  n ), 
assuming  t h at  function  /  is  already  computed  and  its  values  stored  in  an  array 
indexed  by  s. 

E x e r c i se  3 . 4 . 9:  T he  Fibonacci  strings  are  defined  as  follows: 

1.  si  =  b. 

2.  s2  =  a. 

3.  Sk  =  Sk-iSk-2 

for 

k  > 

2. 

For  example,  s3  =  ab, S4  =  aba,  and S5  =  abaab. 

a)  W h at  is  the  length  of  sn? 

3.4. 

RECOGNITION  OF  TOKENS 

139 

b)  Construct  t he  failure  function  for  SQ. 

c)  Construct  t he  failure  function  for  sj. 

!!  d)  Show  t h at  the  failure  function  for  any  sn  can  be  expressed  by  / ( l)  = 

/ ( 2)  =  0,  and  for  2  <  j  < 
integer  such  t h at 

<  j  +  1. 

\sn\,  f(j)  is  j  -  \sk-i\,  where  k  is  the  largest 

!!  e)  In  the  K MP  algorithm,  what  is  the  largest  number  of consecutive  applica 

tions  of  the  failure  function,  when  we  try  to  determine  whether  keyword 
Sk  appears  in  text  string  s^+i? 

Aho  and  Corasick  generalized  the  K MP  algorithm  to  recognize  any  of  a 
set  of  keywords  in  a  text  string. 
In  this  case,  the  trie  is  a  true  tree,  with 
branching  from  the  root.  There  is  one  state  for  every  string  t h at  is  a  prefix 
(not  necessarily  proper)  of  any  keyword.  The  parent  of  a  state  corresponding 
to  string  b\b2  • • • bk  is  the  state  t h at  corresponds  to  &1&2 • • •  frfc-i-  A  state  is 
accepting  if  it  corresponds  to  a  complete  keyword.  For  example,  Fig.  3.21 
shows  t he  trie  for  t he  keywords  h e,  s h e,  h i s,  and  h e r s. 

Figure  3.21:  Trie  for  keywords  he,  s h e,  h i s,  h e rs 

The  failure  function  for  the  general  trie  is  defined  as  follows.  Suppose  s 
is  the  state  t h at  corresponds  to  string  &i&2  •  •  •  bn.  Then  f(s)  is  the  state  t h at 
corresponds  to  t he  longest  proper  suffix  of  &i62  •  •  -bn  t h at  is  also  a  prefix  of 
some  keyword.  For  example,  the  failure  function  for  t he  trie  of  Fig.  3.21  is: 

s 

f(s) 

1 
0 

2 
0 

3 
0 

4 
1 

5 
2 

6 
0 

7 
3 

8 
0 

9 
3 

!  E x e r c i se  3 . 4 . 1 0:  Modify  the  algorithm  of  Fig.  3.19  to  compute  the  failure 
function  for  general  tries.  Hint:  T he  major  difference  is  t h at  we  cannot  simply 
test  for  equality  or  inequality  of  bs+1  and  bt+i  in  lines  (4)  and  (5)  of  Fig.  3.19. 
Rather,  from  any  state  there  may  be  several  transitions  out  on  several  charac 
ters,  as  there  are  transitions  on  b o th  e  and  i  from  state  1  in  Fig.  3.21.  Any  of 

140 

CHAPTER  3. 

LEXICAL  ANALYSIS 

those  transitions  could  lead  to  a  state  t h at  represents  the  longest  suffix  t h at  is 
also  a  prefix. 

E x e r c i se  3 . 4 . 1 1:  Construct  t he  tries  and  compute  t he  failure  function  for  t he 
following  sets  of  keywords: 

a)  a a a,  a b a a a,  and  a b a b a a a. 

b)  a l l,  f a l l,  f a t a l,  l l a m a,  and  lame. 

c)  p i p e,  p e t,  i t e m,  t e m p e r,  and  p e r p e t u a l. 

!  E x e r c i se  3 . 4 . 1 2:  Show  t h at  your  algorithm  from  Exercise  3.4.10  still  runs  in 

time  t h at  is  linear  in  t he  sum  of the  lengths  of t he  keywords. 

3.5  The  Lexical-Analyzer  Generator  Lex 

In  this  section,  we  introduce  a  tool  called  Lex,  or  in  a  more  recent  implemen 
tation  F l e x,  t h at  allows  one  to  specify  a  lexical  analyzer  by  specifying  regular 
expressions  to  describe  patterns  for  tokens.  T he  input  notation  for  the  Lex  tool 
is  referred  to  as  t he  Lex  language  and  the  tool  itself  is  t he  Lex  compiler.  Behind 
the  scenes,  the  Lex  compiler  transforms  t he  input  p a t t e r ns  into  a  transition 
diagram  and  generates  code,  in  a file called  l e x . y y. c,  t h at  simulates  this  t r a n 
sition  diagram.  T he  mechanics  of  how  this  translation  from  regular  expressions 
to  transition  diagrams  occurs  is  t he  subject  of  the  next  sections;  here  we  only 
learn  the  Lex  language. 

3.5.1  Use  of Lex 

Figure  3.22  suggests  how  Lex  is  used.  An  input  file,  which  we  call  l e x . l,  is 
written  in  the  Lex  language  and  describes  t he  lexical  analyzer  to  be  generated. 
T he  Lex  compiler  transforms  l e x. 1  to  a  C  program,  in  a  file  t h at  is  always 
named  l e x . y y. c.  T he  latter file is  compiled  by  the  C  compiler  into  a file called 
a . o u t,  as  always.  T he  C-compiler  output  is  a  working  lexical  analyzer  t h at  can 
take  a  stream  of  input  characters  and  produce  a  stream  of  tokens. 

T he  normal  use  of the  compiled  C  program,  referred  to  as  a. o ut  in  Fig.  3.22, 
is  as  a  subroutine  of t he  parser.  It  is  a  C  function  t h at  returns  an  integer,  which 
is  a  code  for  one  of  the  possible  token  names.  T he  a t t r i b u te  value,  whether  it 
be  another  numeric  code,  a  pointer  to  t he  symbol  table,  or  nothing,  is  placed 
in  a  global  variable  y y l v a l ,2  which  is  shared  between  t he  lexical  analyzer  and 
parser,  thereby  making  it  simple  to  return  b o th  t he  name  and  an  a t t r i b u te  value 
of  a  token. 

incidentally,  the yy  that  appears  in yylval  and lex.yy.c  refers  to  the Yacc  parser-
generator,  which  we  shall  describe  in  Section  4.9,  and  which  is  commonly  used  in  conjunction 
with Lex. 

3.5. 

THE  LEXICAL-ANALYZER  GENERATOR  LEX 

141 

Lex  source  program 
l e x .l 

l e x . y y .c 

Lex 
compiler 

c 
compiler 

l e x . y y .c 

a. out 

Input  stream 

a. out 
a. out 

Sequence  of tokens 

Figure 3.22:  Creating  a  lexical  analyzer  with Lex 

3.5.2 

Structure  of  Lex  Programs 

A Lex  program  has  the  following  form: 

declarations 
°/.7. 
translation  rules 
°/.0/. 
auxiliary  functions 

The  declarations  section  includes  declarations  of  variables,  manifest  constants 
(identifiers  declared  to  stand  for  a  constant,  e.g.,  the  name  of  a  token),  and 
regular  definitions,  in  the  style  of  Section 3.3.4. 
T he  translation  rules  each  have  the  form 

P a t t e rn 

{  Action  } 

Each  p a t t e rn  is  a  regular  expression,  which  may  use  the  regular  definitions  of 
t he  declaration  section.  T he  actions  are  fragments  of  code,  typically  written  in 
C,  although  many  variants  of Lex  using  other  languages  have  been  created. 

T he  third  section  holds  whatever  additional  functions  are  used  in  t he  actions. 
Alternatively,  these  functions  can  be  compiled  separately  and  loaded  with  the 
lexical  analyzer. 

T he  lexical  analyzer  created  by Lex  behaves  in  concert  with  the  parser  as 
follows.  W h en  called  by  the  parser,  the  lexical  analyzer  begins  reading  its 
remaining  input,  one  character  at  a  time,  until  it  finds  the  longest  prefix  of  the 
input  t h at  matches  one  of the  p a t t e r ns  Pi.  It  then  executes  the  associated  action 
Ai.  Typically,  Ai  will  return  to  the  parser,  but  if  it  does  not  (e.g.,  because  Pi 
describes  whitespace  or  comments),  then  the  lexical  analyzer  proceeds  to  find 
additional  lexemes,  until  one  of  the  corresponding  actions  causes  a  return  to 
t he  parser.  T he  lexical  analyzer  returns  a  single  value,  t he  token  name,  to 
the  parser,  but  uses  t he  shared,  integer  variable  y y l v al  to  pass  additional 
information  about  t he  lexeme  found,  if  needed. 

142 

CHAPTER  3. 

LEXICAL  ANALYSIS 

E x a m p le  3 . 1 1:  Figure  3.23  is  a  Lex  program  t h at  recognizes  t he  tokens  of 
Fig.  3.12  and  returns  the  token  found.  A  few  observations  about  this  code  will 
introduce  us  to  many  of  the  important  features  of  Lex. 

In  the  declarations  section  we  see  a  pair  of  special  brackets,  °/.{  and  % }. 
Anything  within  these  brackets  is  copied  directly  to  the  file  l e x . y y . c,  and  is 
not  treated  as  a  regular  definition.  It  is  common  to  place  there  t he  definitions  of 
the  manifest  constants,  using  C  #def i ne  statements  to  associate  unique  integer 
codes  with  each  of  t he  manifest  constants.  In  our  example,  we  have  listed  in  a 
comment  t he  names  of  the  manifest  constants,  LT, IF,  and  so  on,  but  have  not 
shown  them  defined  to  be  particular  integers.3 

Also  in  t he  declarations  section  is  a  sequence  of  regular  definitions.  These 
use  the  extended  notation  for  regular  expressions  described  in  Section  3.3.5. 
Regular  definitions  t h at  are  used  in  later  definitions  or  in  t he  p a t t e r ns  of  t he 
translation  rules  are  surrounded  by  curly  braces.  Thus,  for  instance,  delim  is 
defined  to  be  a  shorthand  for  the  character  class  consisting  of  t he  blank,  the 
t a b,  and  the  newline;  the  latter  two  are  represented,  as  in  all  UNIX  commands, 
by  backslash  followed  by  t  or  n,  respectively.  Then,  ws  is  defined  to  be  one  or 
more  delimiters,  by  the  regular  expression  {delim}+. 

Notice  t h at  in  the  definition  of  id  and  number,  parentheses  are  used  as 
grouping  metasymbols  and  do  not  stand  for  themselves.  In  contrast,  E  in  t he 
If  we  wish  to  use  one  of  the  Lex  meta 
definition  of  number  stands  for  itself. 
symbols,  such  as  any  of the  parentheses,  +,  *,  or  ?,  to  stand  for  themselves,  we 
may  precede  t h em  with  a  backslash.  For  instance,  we  see  \. 
in  t he  definition  of 
number,  to  represent  t he  dot,  since  t h at  character  is  a  metasymbol  representing 
"any  character,"  as  usual  in  UNIX  regular  expressions. 

In  t he  auxiliary-function  section,  we  see  two  such  functions,  i n s t a l l l D () 
and  i n s t a l l N u m O.  Like  t he  portion  of  the  declaration  section  t h at  appears 
between  °/0{.  .  . % },  everything  in  the  auxiliary  section  is  copied  directly  to  file 
l e x . y y . c,  but  may  be  used  in  the  actions. 

Finally,  let  us  examine  some  of t he  p a t t e r ns  and  rules  in  t he  middle  section  of 
Fig.  3.23.  First,  ws,  an  identifier  declared  in  the  first  section,  has  an  associated 
empty  action.  If  we  find  whitespace,  we  do  not  return  to  t he  parser,  but  look 
for  another  lexeme.  T he  second  token  has  t he  simple  regular  expression  p a t t e rn 
if.  Should  we  see  t he  two  letters  if  on  the  input,  and  they  are  not  followed 
by  another  letter  or  digit  (which  would  cause  the  lexical  analyzer  to  find  a 
longer  prefix  of the  input  matching  the  p a t t e rn  for  i d ),  then  the  lexical  analyzer 
consumes  these  two  letters  from  the  input  and  returns  t he  token  name IF,  t h at 
is,  t he  integer  for  which  the  manifest  constant IF  stands.  Keywords  t h en  and 
e l se  are  treated  similarly. 

T he  fifth  token  has  the  p a t t e rn  defined  by  id.  Note  t h a t,  although  keywords 
like  if  match  this  p a t t e rn  as  well  as  an  earlier  p a t t e r n,  Lex  chooses  whichever 

3If Lex  is  used  along  with Yacc,  then  it  would  be  normal  to  define  the  manifest  constants 
in  the Yacc  program  and  use  them  without  definition  in  the Lex  program.  Since lex.yy.c  is 
compiled  with  the Yacc  output,  the  constants  thus  will  be  available  to  the  actions  in  the Lex 
program. 

THE 

LEXICAL-ANALYZER 

GENERATOR  LEX 

143 

U 

'/.} 

/*  definitions  of  manifest  constants 

LT,  LE, EQ,  NE,  GT,  GE, 

IF,  THEN,  ELSE,  ID,  NUMBER,  RELOP */ 

/*  regular  definitions  */ 
delim 
ws 

[  \t\n] 
{delim}+ 

letter 
digit 

[A-Za-z] 
[0-9] 

id 

{letter}({letter}|{digit})* 

number 

{digit}+(\.{digit}+)?(E[+-]?{digit}+)? 

°/.y. 

{ws} 

if 

then 

else 

{id} 

{/*  no  action  and  no  return  */} 

{return(IF);} 

{return(THEN);} 

{return(ELSE);} 

{yylval =  (int)  installID();  return(ID);} 

{number}  {yylval =  (int)  installNumO ;  return(NUMBER);} 
1 I <M 

"<=" 

II  _  II 

"<>" 

{yylval  =  LT;  return(RELOP) ;} 
{yylval  =  LE;  return(RELOP) ;} 
{yylval  =  EQ;  return(RELOP) ;} 
{yylval  =  NE;  return(RELOP) ;} 
{yylval  =  GT;  return(RELOP) ;} 
{yylval  =  GE;  return(RELOP) •} 

int  installlDQ  {/*  function to  install  the  lexeme,  whose 

first  character  is  pointed to  by  yytext, 
arid whose  length  is  yyleng,  into  the 
symbol  table  and  return  a  pointer 
thereto  */ 

int  installNumO  {/*  similar  to  installlD,  but  puts  numer 

ical  constants  into  a  separate  table  */ 

} 

Figure 3.23: Lex  program  for  the  tokens  of Fig. 3.12 

144 

CHAPTER  3. 

LEXICAL  ANALYSIS 

p a t t e rn  is  listed  first  in  situations  where  the  longest  matching  prefix  matches 
two  or  more  patterns.  The  action  taken  when  id  is  matched  is  threefold: 

1.  Function  i n s t a l l l D ()  is  called  to  place  the  lexeme  found  in  t he  symbol 

table. 

2.  This  function  returns  a  pointer  to  t he  symbol  table,  which  is  placed  in 
global  variable  y y l v a l,  where  it  can  be  used  by  t he  parser  or  a  later 
component  of  the  compiler.  Note  t h at  i n s t a l l l D ()  has  available  to  it 
two  variables  t h at  are  set  automatically  by  the  lexical  analyzer  t h at  Lex 
generates: 

(a)  y y t e xt  is  a  pointer  to  the  beginning  of  t he  lexeme,  analogous  to 

lexemeBegin  in  Fig.  3.3. 

(b)  y y l e ng  is  the  length  of  the  lexeme  found. 

3.  T he  token  name  ID  is  returned  to  the  parser. 

T he  action  taken  when  a  lexeme  matching  the  p a t t e rn  number  is  similar,  using 
the  auxiliary  function  i n s t a l l N u m O. 

• 

3.5.3  Conflict  Resolution  in  Lex 

We  have  alluded  to  t he  two  rules  t h at  Lex  uses  to  decide  on  t he  proper  lexeme 
to  select,  when  several  prefixes  of  the  input  match  one  or  more  patterns: 

1.  Always  prefer  a  longer  prefix  to  a  shorter  prefix. 

2.  If  the  longest  possible  prefix  matches  two  or  more  patterns,  prefer  the 

p a t t e rn  listed  first  in  the  Lex  program. 

E x a m p le  3 . 1 2:  T he  first  rule  tells  us  to  continue  reading  letters  and  digits  to 
find  t he  longest  prefix  of these  characters  to  group  as  an  identifier.  It  also  tells 
us  to  treat  <=  as  a  single  lexeme,  rather  t h an  selecting  <  as  one  lexeme  and  = 
as  the  next  lexeme.  T he  second  rule  makes  keywords  reserved,  if  we  list  t he 
keywords  before  id  in  t he  program.  For  instance,  if  t h en  is  determined  to  be 
the  longest  prefix  of  t he  input  t h at  matches  any  p a t t e r n,  and  the  p a t t e rn  t h en 
precedes  { i d },  as  it  does  in  Fig.  3.23,  then  the  token  THEN  is  returned,  rather 
t h an  ID. 

• 

3.5.4  The  Lookahead  Operator 

Lex  automatically  reads  one  character  ahead  of  t he  last  character  t h at  forms 
t he  selected  lexeme,  and  then  retracts  t he  input  so  only  the  lexeme  itself  is 
consumed  from  the  input.  However,  sometimes,  we  want  a  certain  p a t t e rn  to 
be  matched  to  the  input  only  when  it  is  followed  by  a  certain  other  characters. 
If  so,  we  may  use  t he  slash  in  a  p a t t e rn  to  indicate  the  end  of  t he  part  of  t he 

3.5. 

THE  LEXICAL-ANALYZER  GENERATOR  LEX 

145 

p a t t e rn  t h at  matches  t he  lexeme.  W h at  follows  /  is  additional  p a t t e rn  t h at 
must  be  matched  before  we  can  decide  t h at  the  token  in  question  was  seen,  but 
what  matches  this  second  p a t t e rn  is  not  part  of  the  lexeme. 

E x a m p le  3 . 1 3:  In  Fortran  and  some  other  languages,  keywords  are  not  re 
served.  T h at  situation  creates  problems,  such  as  a  statement 

IF(I,J)  =  3 

where IF  is  the  name  of an  array,  not  a  keyword.  This  statement  contrasts  with 
statements  of  t he  form 

IF(  condition )  THEN  ... 

where IF  is  a  keyword.  Fortunately,  we  can  be  sure  t h at  t he  keyword IF  is 
always  followed  by  a  left  parenthesis,  some  text  —  the  condition  —-  t h at  may 
contain  parentheses,  a  right  parenthesis  and  a  letter.  Thus,  we  could  write  a 
Lex  rule  for  the  keyword IF  like: 

IF /  \(  .*  \)  {letter} 

This  rule  says  t h at  the  p a t t e rn  the  lexeme  matches  is  just  t he  two  letters IF. 
T he  slash  says  t h at  additional  p a t t e rn  follows  but  does  not  match  the  lexeme. 
In  this  p a t t e r n,  the  first  character  is  the  left  parentheses.  Since  t h at  character  is 
a Lex  metasymbol,  it  must  be  preceded  by  a  backslash  to  indicate  t h at  it  has  its 
literal  meaning.  T he  dot  and  star  match  "any  string  without  a  newline."  Note 
t h at  t he  dot  is  a Lex  metasymbol  meaning  "any  character  except  newline."  It 
is  followed  by  a  right  parenthesis,  again  with  a  backslash  to  give  t h at  character 
its  literal  meaning.  T he  additional  p a t t e rn  is  followed  by  the  symbol  letter, 
which  is  a  regular  definition  representing  the  character  class  of  all  letters. 

Note  t h at  in  order  for  this  p a t t e rn  to  be  foolproof,  we  must  preprocess 
the  input  to  delete  whitespace.  We  have  in  the  p a t t e rn  neither  provision  for 
whitespace,  nor  can  we  deal  with  the  possibility  t h at  the  condition  extends  over 
lines,  since  the  dot  will  not  match  a  newline  character. 

For  instance,  suppose  this  p a t t e rn  is  asked  to  match  a  prefix  of  input: 

IF(A<(B+C)*D)THEN... 

the  first  two  characters  match IF,  the  next  character  matches  \ (,  the  next  nine 
characters  match  .*,  and  the  next  two  match  \)  and  letter.  Note  the  fact  t h at 
t he  first  right  parenthesis  (after  C)  is  not  followed  by  a  letter  is  irrelevant;  we 
only  need  to  find  some  way  of  matching  the  input  to  the  p a t t e r n.  We  conclude 
t h at  t he  letters IF  constitute  t he  lexeme,  and  they  are  an  instance  of  token if. 
• 

146 

CHAPTERS. 

LEXICAL 

ANALYSIS 

3.5.5  Exercises  for  Section  3.5 

E x e r c i se  3 . 5 . 1:  Describe  how  to  make  t he  following  modifications  to  t he  Lex 
program  of  Fig.  3.23: 

a)  Add  the  keyword  w h i l e. 

b)  Change  t he  comparison  operators  to  be  t he  C  operators  of  t h at  kind. 

c)  Allow  the  underscore  (_)  as  an  additional  letter. 

!  d)  Add  a  new  p a t t e rn  with  token  STRING.  The  p a t t e rn  consists  of  a  double-
quote  ("),  any  string  of  characters  and  a  final  double-quote.  However, 
if  a  double-quote  appears  in  the  string,  it  must  be  escaped  by  preceding 
it  with  a  backslash  ( \ ),  and  therefore  a  backslash  in  t he  string  must  be 
represented  by  two  backslashes.  T he  lexical  value,  which  is  t he  string 
without  the  surrounding  double-quotes,  and  with  backslashes  used  to  es 
cape  a  character  removed.  Strings  are  to  be  installed  in  a  table  of strings. 

E x e r c i se  3 . 5 . 2:  Write  a  Lex  program  t h at  copies  a  file,  replacing  each  non 
empty  sequence  of  white  space  by  a  single  blank. 

E x e r c i se  3 . 5 . 3:  Write  a  Lex  program  t h at  copies  a  C  program,  replacing  each 
instance  of  t he  keyword  f l o at  by  double. 

!  E x e r c i se  3 . 5 . 4:  Write  a  Lex  program  t h at  converts  a  file  to  "Pig  latin." 
Specifically,  assume  the  file  is  a  sequence  of  words  (groups  of  letters)  separated 
by  whitespace.  Every  time  you  encounter  a  word: 

1.  If  the  first  letter  is  a  consonant,  move  it  to  t he  end  of  t he  word  and  then 

add  ay. 

2.  If  t he  first  letter  is  a  vowel,  just  add  ay  to  the  end  of  the  word. 

All  nonletters  are  copied  intact  to  the  output. 

!  E x e r c i se  3 . 5 . 5:  In  SQL,  keywords  and  identifiers  are  case-insensitive.  Write 
a  Lex  program  t h at  recognizes  t he  keywords  SELECT,  FROM,  and  WHERE  (in  any 
combination  of  capital  and  lower-case  letters),  and  token  ID,  which  for  the 
purposes  of  this  exercise  you  may  take  to  be  any  sequence  of  letters  and  digits, 
beginning  with  a  letter.  You  need  not  install  identifiers  in  a  symbol  table,  but 
tell  how  the  "install"  function  would  differ  from  t h at  described  for  case-sensitive 
identifiers  as  in  Fig.  3.23. 

3.6. 

FINITE  AUTOMATA 

147 

3.6  Finite  Automata 

We  shall  now  discover  how  Lex  turns  its  input  program  into  a  lexical  analyzer. 
At  t he  heart  of  the  transition  is  the  formalism  known  as  finite  automata.  These 
are  essentially  graphs,  like  transition  diagrams,  with  a  few  differences: 

1.  Finite  a u t o m a ta  are  recognizers;  they  simply  say  "yes"  or  "no"  about  each 

possible  input  string. 

2.  Finite  a u t o m a ta  come  in  two  flavors: 

(a)  Nondeterministic 

finite  automata  (NFA)  have  no  restrictions  on  the 
labels  of  their  edges.  A  symbol  can  label  several  edges  out  of  t he 
same  state,  and  e,  the  empty  string,  is  a  possible  label. 

(b)  Deterministic 

finite  automata  (DFA)  have,  for  each  state,  and  for 
each  symbol  of  its  input  alphabet  exactly  one  edge  with  t h at  symbol 
leaving  t h at  state. 

Both  deterministic  and  nondeterministic  finite  a u t o m a ta  are  capable  of  rec 
ognizing  t he  same  languages. 
In  fact  these  languages  are  exactly  the  same 
languages,  called  the  regular  languages,  t h at  regular  expressions  can  describe.4 

3.6.1  Nondeterministic  Finite  Automata 

A  nondeterministic 

finite  automaton  (NFA)  consists  of: 

1.  A  finite  set  of  states  5. 

2.  A  set  of  input  symbols  E,  the  input  alphabet.  We  assume  t h at  e,  which 

stands  for  t he  empty  string,  is  never  a  member  of  E. 

3.  A  transition  function  t h at  gives,  for  each  state,  and  for  each  symbol  in 

E  U  {e}  a  set  of  next  states. 

4.  A  state  so  from  S  t h at  is  distinguished  as  the  start  state  (or  initial  state). 

5.  A  set  of  states  F,  a  subset  of  S,  t h at  is  distinguished  as  the  accepting 

states  (or 

final  states). 

We  can  represent  either  an  NFA  or  DFA  by  a  transition  graph,  where  t he 
nodes  are  states  and  the  labeled  edges  represent  the  transition  function.  There 
is  an  edge  labeled  a  from  state  s  to  state  t  if  and  only  if  t  is  one  of  t he  next 
states  for  state  s  and  input  a.  This  graph  is  very  much  like  a transition  diagram, 
except: 

4T h e re  is  a  small  lacuna:  as  we  defined  them,  regular  expressions  cannot  describe  the 
empty  language,  since  we  would  never  want  to  use  this  pattern  in  practice.  However,  finite 
automata  can  define  the  empty  language.  In  the  theory,  0  is  treated  as  an  additional  regular 
expression  for  the  sole  purpose  of  defining  the  empty  language. 

148 

CHAPTER  3. 

LEXICAL  ANALYSIS 

a)  The  same  symbol  can  label  edges  from  one  state  to  several  different  states, 

and 

b)  An  edge  may  be  labeled  by  e,  t he  empty  string,  instead  of,  or  in  addition 

to,  symbols  from  the  input  alphabet. 

E x a m p le  3 . 1 4:  T he  transition  graph  for  an  NFA  recognizing  the  language 
of  regular  expression  ( a | b ) * a bb  is  shown  in  Fig.  3.24.  This  abstract  example, 
describing  all  strings  of  a's  and  &'s  ending  in  t he  particular  string  abb,  will  be 
used  throughout  this  section.  It  is  similar  to  regular  expressions  t h at  describe 
languages  of  real  interest,  however.  For  instance,  an  expression  describing  all 
files  whose  name  ends  in 
.o  is  a n y * . o,  where  a ny  stands  for  any  printable 
character. 

a 

b 

Figure  3.24:  A  nondeterministic  finite  a u t o m a t on 

Following  our  convention  for  transition  diagrams,  t he  double  circle  around 
state  3  indicates  t h at  this  state  is  accepting.  Notice  t h at  t he  only  ways  to  get 
from  the  start  state  0  to  the  accepting  state  is  to  follow  some  p a th  t h at  stays 
in  state  0  for  a  while,  then  goes  to  states  1,  2,  and  3  by  reading  abb  from  t he 
input.  Thus,  the  only  strings  getting  to  the  accepting  state  are  those  t h at  end 
in  abb. 

• 

3.6.2  Transition  Tables 

We  can  also  represent  an  NFA  by  a  transition  table,  whose  rows  correspond  to 
states,  and  whose  columns  correspond to  the  input  symbols  and  e.  T he  entry  for 
a  given  state  and  input  is  the  value  of  the  transition  function  applied  to  those 
arguments.  If t he  transition  function  has  no  information  about  t h at  state-input 
pair,  we  put  0  in  the  table  for  the  pair. 

E x a m p le  3 . 1 5:  The  transition  table  for  the  NFA  of  Fig.  3.24  is  shown  in 
Fig.  3.25. 

• 

T he  transition  table  has  the  advantage  t h at  we  can  easily  find  the  transitions 
on  a  given  state  and  input.  Its  disadvantage  is  t h at  it  takes  a  lot  of space,  when 
the  input  alphabet  is  large,  yet  most  states  do  not  have  any  moves  on  most  of 
the  input  symbols. 

3.6. 

FINITE  AUTOMATA 

1 49 

S T A TE 

a 

0 

1 

2 

3 

{ 0 , 1} 
0 
0 
0 

b 

e 
{ 0}  0 
{ 2}  0 
{ 3}  0 
0 
0 

Figure  3 . 2 5:  Transition  table  for  the  NFA  of Fig.  3 . 24 

3.6.3  Acceptance  of Input  Strings  by  Automata 

An  NFA  accepts  input  string  x  if  and  only  if there  is  some  p a th  in  t he  transition 
graph  from  t he  start  state  to  one  of  the  accepting  states,  such  t h at  the  symbols 
along  the  p a th  spell  out  x.  Note  t h at  e  labels  along  the  p a th  are  effectively 
ignored,  since  t he  empty  string  does  not  contribute  to  t he  string  constructed 
along  the  p a t h. 

E x a m p le  3 . 1 6:  T he  string  aabb  is  accepted  by  t he  NFA  of  Fig.  3 . 2 4.  T he 
p a th  labeled  by  aabb  from  state  0  to  state  3  demonstrating  this  fact  is: 

0 

•  1 
Note  t h at  several  p a t hs  labeled  by  the  same  string  may  lead  to  different  states. 
For  instance,  p a th 

*~  2 

•  3 

•  0 

a

a

a

a

bb 

bb 

0 

•  0 

•  0 
is  another  p a th  from  state  0  labeled  by  the  string  aabb.  This  p a th  leads  to 
state  0,  which  is  not  accepting.  However,  remember  t h at  an  NFA  accepts  a 
string  as  long  as  some  p a th  labeled  by  t h at  string  leads  from  t he  start  state 
to  an  accepting  state.  T he  existence  of  other  p a t hs  leading  to  a  nonaccepting 
state  is  irrelevant. 

*~  0 

•  0 

• 

T he  language  defined  (or  accepted)  by  an  NFA  is  the  set  of  strings  labeling 

some  p a th  from  the  start  to  an  accepting  state.  As  was  mentioned,  the  NFA  of 
Fig.  3 . 24  defines  the  same  language  as  does  t he  regular  expression  (a|b)*abb, 
t h at  is,  all  strings  from  t he  alphabet  {a,  b}  t h at  end  in  abb.  We  may  use  L(A) 
to  stand  for  t he  language  accepted  by  a u t o m a t on  A. 

E x a m p le  3 . 1 7:  Figure  3 . 26  is  an  NFA  accepting  L( a a * | b b * ).  String  aaa  is 
accepted  because  of  the  p a th 

0 

e 

•  l 

a 

»•  2 

a 

*-  2 

a 

•  2 

Note  t h at  e's  "disappear"  in  a  concatenation,  so  the  label  of  the  p a th  is  aaa. 
• 

3.6.4  Deterministic  Finite  Automata 

A  deterministic 

finite  automaton  (DFA)  is  a  special  case  of  an  NFA  where: 

150 

CHAPTER  3. 

LEXICAL  ANALYSIS 

start 

a 

b 

a 

b 

Figure  3.26:  NFA  accepting  aa*|bb* 

1.  There  are  no  moves  on  input  e,  and 

2.  For  each  state  s  and  input  symbol  a,  there  is  exactly  one  edge  out  of  s 

labeled  a. 

If we  are  using  a  transition  table  to  represent  a  DFA,  then  each  entry  is  a  single 
state,  we  may  therefore  represent  this  state  without  t he  curly  braces  t h at  we 
use  to  form  sets. 

While  the  NFA  is  an  abstract  representation  of  an  algorithm  to  recognize 
the  strings  of  a  certain  language,  t he  DFA  is  a  simple,  concrete  algorithm  for 
recognizing  strings. 
It  is  fortunate  indeed  t h at  every  regular  expression  and 
every  NFA  can  be  converted  to  a  DFA  accepting  the  same  language,  because  it 
is  the  DFA  t h at  we  really  implement  or  simulate  when  building lexical  analyzers. 
T he  following  algorithm  shows  how  to  apply  a  DFA  to  a  string. 

A l g o r i t hm  3 . 1 8:  Simulating  a  DFA. 

I N P U T:  An  input  string  x  terminated  by  an  end-of-file  character  eof.  A  DFA 
D  with  start  state  so,  accepting  states  F,  and  transition  function  move. 

O U T P U T:  Answer  "yes"  if D  accepts  x;  "no"  otherwise. 

M E T H O D:  Apply  the  algorithm  in  Fig.  3.27 to  t he  input  string  x.  T he  function 
move(s,c)  gives  the  state  to  which  there  is  an  edge  from  state  s  on  input  c. 
T he  function  next  Char  returns  the  next  character  of  t he  input  string  x.  • 

E x a m p le  3 . 1 9:  In  Fig.  3.28  we  see  the  transition  graph  of  a  DFA  accepting 
the  language  (a|b)*abb,  the  same  as  t h at  accepted  by  the  NFA  of  Fig.  3.24. 
Given  the  input  string  ababb,  this  DFA  enters  the  sequence  of states  0 , 1 , 2 , 1 , 2 ,3 
and  returns  "yes." 

• 

3.6. 

FINITE  AUTOMATA 

151 

8  =  S0] 
c  =  nextCharQ; 
w h i le  (  c  !=  e o f)  { 

s  =  move(s,c); 
c  =  nextCharQ; 

} 
if  (  s  is  in  F  )  r e t u rn  "yes"; 
e l se  r e t u rn  " n o "; 

3.6.5  Exercises  for  Section  3.6 

!  E x e r c i se  3 . 6 . 1:  Figure  3.19  in  the  exercises  of Section  3.4  computes  the  failure 
function  for  t he  K MP  algorithm.  Show  how,  given  t h at  failure  function,  we 
can  construct,  from  a  keyword  bib2  •  •  -  bn  an.  n  +  1-state  DFA  t h at  recognizes 
*bib2  •  •  •  bn,  where  the  dot  stands  for  "any  character."  Moreover,  this  DFA  can 
be  constructed  in  0(n)  time. 

E x e r c i se  3 . 6 . 2:  Design  finite  a u t o m a ta  (deterministic  or  nondeterministic) 
for  each  of  the  languages  of  Exercise  3.3.5. 

E x e r c i se  3 . 6 . 3:  For  the  NFA  of  Fig.  3.29,  indicate  all  the  paths  labeled  aabb. 
Does  t he  NFA  accept  aabb? 

start 

a.  b 

a.  b 

a.  b 

Figure  3.29:  NFA  for  Exercise  3.6.3 

152 

CHAPTER  3. 

LEXICAL  ANALYSIS 

start 

e 

a 

Figure  3.30:  NFA  for  Exercise  3.6.4 

E x e r c i se  3 . 6 . 4:  Repeat  Exercise  3.6.3  for  the  NFA  of  Fig.  3.30. 

E x e r c i se  3 . 6 . 5:  Give  the  transition  tables  for  the  NFA  of: 

a)  Exercise  3.6.3. 

b)  Exercise  3.6.4. 

c)  Figure  3.26. 

3.7  Prom  Regular  Expressions  to  Automata 

T he  regular  expression  is  t he  notation  of  choice  for  describing  lexical  analyzers 
and  other  pattern-processing  software,  as  was  reflected  in  Section  3.5.  How 
ever,  implementation  of  t h at  software  requires  the  simulation  of  a  DFA,  as  in 
Algorithm  3.18,  or  perhaps  simulation  of  an  NFA.  Because  an  NFA  often  has  a 
choice  of  move  on  an  input  symbol  (as  Fig.  3.24  does  oh  input  a  from  state  0) 
or  on  e  (as  Fig.  3.26  does  from  state  0),  or  even  a  choice  of making  a  transition 
on  e  or  on  a  real  input  symbol,  its  simulation  is  less  straightforward  t h an  for  a 
DFA.  Thus  often  it  is  important  to  convert  an  NFA  to  a  DFA  t h at  accepts  t he 
same  language. 

In  this  section  we  shall  first  show  how  to  convert  NFA's  to  DFA's.  Then,  we 
use  this  technique,  known  as  "the  subset  construction,"  to  give  a  useful  algo 
rithm  for  simulating  NFA's  directly,  in  situations  (other  t h an  lexical  analysis) 
where  the  NFA-to-DFA  conversion  takes  more  time  t h an  the  direct  simulation. 
Next,  we  show  how  to  convert  regular  expressions  to  NFA's,  from  which  a  DFA 
can  be  constructed  if  desired.  We  conclude  with  a  discussion  of  the  time-space 
tradeoffs  inherent  in  the  various  methods  for  implementing  regular  expressions, 
and  see  how  to  choose  the  appropriate  method  for  your  application. 

3.7.1  Conversion  of  an  NFA  to  a  DFA 

The  general  idea  behind  the  subset  construction  is  t h at  each  state  of  the 
constructed  DFA  corresponds  to  a  set  of  NFA  states.  After  reading  input 

3.7. 

FROM  REGULAR  EXPRESSIONS 

TO  AUTOMATA 

1 53 

flifl2  • • • Q>n,  t he  DFA  is  in  t h at  state  which  corresponds  to  the  set  of states  t h at 
t he  NFA  can  reach,  from  its  start  state,  following  paths  labeled  a\a2  •  •  •  an. 

It  is  possible  t h at  t he  number  of  DFA  states  is  exponential  in  the  number 
of  NFA  states,  which  could  lead  to  difficulties  when  we  t ry  to  implement  this 
DFA.  However,  part  of  t he  power  of  the  automaton-based  approach  to  lexical 
analysis  is  t h at  for  real  languages,  the  NFA  and  DFA  have  approximately  the 
same  number  of  states,  and  the  exponential  behavior  is  not  seen. 

A l g o r i t hm  3 . 2 0:  T he  subset  construction  of  a  DFA  from  an  NFA. 

I N P U T:  An  NFA  JV. 

O U T P U T:  A  DFA  D  accepting  the  same  language  as  N. 

M E T H O D:  Our  algorithm  constructs  a  transition  table  Dtran  for  D.  Each 
state  of  D  is  a  set  of  NFA  states,  and  we  construct  Dtran  so  D  will  simulate 
"in  parallel"  all  possible  moves  N  can  make  on  a  given  input  string.  Our  first 
problem  is  to  deal  with  e-transitions  of  N  properly. 
In  Fig.  3 . 31  we  see  t he 
definitions  of  several  functions  t h at  describe  basic  computations  on  t he  states 
of  N  t h at  are  needed  in  the  algorithm.  Note  t h at  s  is  a  single  state  of  N,  while 
T  is  a  set  of  states  of  N. 

O P E R A T I ON 

D E S C R I P T I ON 

e-closure(s) 

Set  of  NFA  states  reachable  from  NFA  state  s 

on  e-transitions  alone. 

e-closure(T) 

Set  of  NFA  states  reachable  from  some  NFA  state  s 

in  set  T  on  e-transitions  alone;  =  Us  in  T  e-closure(s). 

move(T,  a) 

Set  of  NFA  states  to  which  there  is  a  transition  on 

input  symbol  a  from  some  state  s  in  T. 

Figure  3 . 3 1:  Operations  on  NFA  states 

We  must  explore  those  sets  of states  t h at  N  can  be  in  after  seeing  some  input 
string.  As  a  basis,  before  reading  t he  first  input  symbol,  N  can  be  in  any  of t he 
states  of  e-closure(so),  where  SQ  is  its  start  state.  For  the  induction,  suppose 
t h at  N  can  be  in  set  of  states  T  after  reading  input  string  x.  If  it  next  reads 
input  a,  then  N  can  immediately  go  to  any  of t he  states  in  move(T,  a).  However, 
after  reading  a,  it  may  also  make  several  e-transitions;  thus  N  could  be  in  any 
state  of  e-closure(move(T,  a))  after  reading  input  xa.  Following  these  ideas,  the 
construction  of  t he  set  of  Z?'s  states,  Dstates,  and  its  transition  function  Dtran, 
is  shown in  Fig.  3 . 3 2. 

The  start  state  of  D  is  e-closure(so),  and  t he  accepting  states  of  D  are  all 
those  sets  of  AT's  states  t h at  include  at  least  one  accepting  s t a te  of  N.  To 
complete  our  description  of the  subset  construction,  we  need  only  to  show  how 

154 

CHAPTER 

3.' 

LEXICAL  ANALYSIS 

initially,  e-closure(s0)  is  the  only  state  in  Dstates,  and  it  is  unmarked; 
w h i le  (  there  is  an  unmarked  state  T  in  Dstates  )  { 

mark  T; 
for  (  each  input  symbol  a  )  { 

U  = 
if  (  U  is  not  in  Dstates  ) 

e-closure(move(T,a)); 

add  U  as  an  unmarked  state  to  Dstates; 

Dtran[T, a]  =  U; 

} 

} 

Figure  3.32:  The  subset  construction 

e-closure(T)  is  computed  for  any  set  of  NFA  states  T.  This  process,  shown  in 
Fig.  3.33,  is  a  straightforward  search  in  a  graph  from  a  set  of  states.  In  this 
case,  imagine  t h at  only  the  e-labeled  edges  are  available  in  the  graph. 

• 

push  all  states  of  T  onto  stack; 
initialize  e~closure(T)  to  T; 
w h i le  (  stack  is  not  empty  )  { 

pop  t,  t he  top  element,  off  stack; 
for  (  each  state  u  with  an  edge  from  t  to  u  labeled  e  ) 

if  (  u  is  not  in  e-closure(T)  )  { 

add  u  to  e-closure(T); 
push  u  onto  stack; 

} 

} 

Figure  3.33:  Computing  e-closure(T) 

E x a m p le  3 . 2 1:  Figure  3.34  shows  another  NFA  accepting  (a|b)*abb;  it  hap 
pens  to  be  the  one  we  shall  construct  directly  from  this  regular  expression  in 
Section  3.7.  Let  us  apply  Algorithm  3.20  to  Fig.  3.29. 

T he  start  state  A  of t he  equivalent  DFA  is  e-closure(0),  or  A  =  { 0 , 1 , 2 , 4 , 7 }, 
since  these  are  exactly  t he  states  reachable  from  state  0  via  a  p a th  all  of whose 
edges  have  label  e.  Note  t h at  a p a th  can  have  zero  edges,  so  state  0  is  reachable 
from  itself  by  an  e-labeled  p a t h. 

T he  input  alphabet  is  {a,  b}.  Thus,  our  first  step  is  to  mark  A  and  compute 

e-closure(move(A,a)) 

Dtran[A,a]  = 
Among  the  states  0,  1,  2,  4,  and  7,  only  2  and  7  have  transitions  on  a,  to 
3  and  8,  respectively.  Thus,  move(A,a)  =  { 3 , 8 }.  Also,  e-closure({3,8}  = 
{ 1 , 2 , 3 , 4 , 6 , 7 , 8 },  so  we  conclude 

and  Dtran[A,b]  = 

e-closure(move(A,b)). 

3.7. 

FROM  REGULAR  EXPRESSIONS 

TO  AUTOMATA 

1 55 

start 

e 

8 

Figure  3 . 3 4:  NFA  N  for  (a|b)*abb 

Dtran[A,a]  =  e-closure(move(A,a))  —  e-closure({3,8})  =  { 1 , 2 , 3 , 4 , 6 , 7 , 8} 

Let  us  call  this  set  B,  so  Dtran[A,  a]  =  B. 

Now,  we  must  compute  Dtran[A,b].  Among  t he  states  in  A,  only  4  has  a 

transition  on  6,  and  it  goes  to  5.  Thus, 

Dtran[A,b]  =  e-closure({5})  =  { 1 , 2 , 4 , 6 , 7} 

Let  us  call  t he  above  set  C,  so  Dtran[A,  b]  —  C. 

NFA 

S T A TE 

DFA 

S T A TE 

{ 0 , 1 , 2 , 4 , 7} 

{ 1 , 2 , 3 , 4 , 6 , 7 , 8} 

{ 1 , 2 , 4 , 5 , 6 , 7} 

{ 1 , 2 , 4 , 5 , 6 , 7 , 9} 

{ 1 , 2 , 3 , 5 , 6 , 7 , 1 0} 

A 
B 
C 
D 
E 

a 

b 

B 
C 
B  D 
B 
C 
E 
B 
B 
C 

Figure  3 . 3 5:  Transition  table  Dtran  for  DFA  D 

If  we  continue  this  process  with  the  unmarked  sets  B  and  C,  we  eventually 
reach  a  point  where  all  the  states  of  the  DFA  are  marked.  This  conclusion  is 
guaranteed,  since  there  are  "only"  211  different  subsets  of  a  set  of  eleven  NFA 
states.  T he  five  different  DFA  states  we  actually  construct,  their  correspond 
ing  sets  of  NFA  states,  and  the  transition  table  for  t he  DFA  D  are  shown  in 
Fig.  3 . 3 5,  and  the  transition  graph  for  D  is  in  Fig.  3 . 3 6.  State  A  is  the  start 
state,  a nd  s t a te  E,  which  contains  s t a te  10  of  t he  NFA,  is  t he  only  accepting 
state. 

Note  t h at  D  has  one  more  state  t h an  the  DFA  of Fig.  3 . 28  for  the  same  lan 

guage.  States  A  and  C  have  the  same  move  function,  and  so  can  be  merged.  We 
discuss  t he  m a t t er  of minimizing  the  number  of states  of a  DFA  in  Section  3 . 9 . 6. 
• 

156 

CHAPTER  3. 

LEXICAL  ANALYSIS 

b 

start 

Figure  3.36:  Result  of  applying  the  subset  construction  to  Fig.  3.34 

a 

3.7.2 

Simulation  of  an  NFA 

A  strategy  t h at  has  been  used  in  a  number  of  text-editing  programs  is  to  con 
struct  an  NFA  from  a  regular  expression  and  then  simulate  t he  NFA  using 
something  like  an  on-the-fly  subset  construction.  The  simulation  is  outlined 
below. 

A l g o r i t hm  3 . 2 2:  Simulating  an  NFA. 

I N P U T:  An  input  string  x  terminated  by  an  end-of-file  character  eof.  An  NFA 
N  with  start  state  SQ,  accepting  states  F,  and  transition  function  move. 

O U T P U T:  Answer  "yes"  if  M  accepts  x;  "no"  otherwise. 

M E T H O D:  The  algorithm keeps  a set  of current  states  S,  those  t h at  are  reached 
from  so  following  a  p a th  labeled  by  the  inputs  read  so  far.  If c  is  t he  next  input 
then  we  first  compute  move(S,c) 
character,  read  by  the  function  nextCharQ, 
and  then  close  t h at  set  using  e-closureQ.  T he  algorithm  is  sketched  in  Fig.  3.37. 
• 

1) 
2) 
3) 
4) 
5) 
6) 
7) 
8) 

S  =  e-closure(so); 
c  =  nextCharQ; 
w h i le  (  c  !=  e o f)  { 
S  = 
c  =  nextCharQ; 

e-closure(move(S,c)); 

} 
if  ( 5 n  F != 0  )  r e t u rn  "yes"; 
e l se  r e t u rn  "no"; 

Figure  3.37:  Simulating  an  NFA 

3.7. 

FROM  REGULAR  EXPRESSIONS 

TO  AUTOMATA 

157 

3.7.3  Efficiency  of  NFA  Simulation 

If  carefully  implemented,  Algorithm  3.22  can  be  quite  efficient.  As  t he  ideas 
involved  are  useful  in  a  number  of similar  algorithms  involving  search  of graphs, 
we  shall  look  at  this  implementation  in  additional  detail.  T he  d a ta  structures 
we  need  are: 

1.  Two  stacks,  each  of which  holds  a  set  of  NFA  states.  One  of these  stacks, 
oldStates,  holds  the  "current"  set  of  states,  i.e.,  the  value  of  S  on  the  right 
side  of  line  (4)  in  Fig.  3.37.  T he  second,  newStates,  holds  t he  "next"  set 
of  states  —  5  on  the  left  side  of  line  (4).  Unseen  is  a  step  where,  as  we 
go  around  the  loop  of  lines  (3)  through  (6),  newStates  is  transferred  to 
oldStates. 

2.  A  boolean  array  alreadyOn,  indexed  by  the  NFA  states,  to  indicate  which 
states  are  in  newStates.  While  t he  array  and  stack  hold  t he  same  infor 
mation,  it  is  much  faster  to  interrogate  alreadyOn[s]  t h an  to  search  for 
state  s  on  t he  stack  newStates.  It  is  for  this  efficiency  t h at  we  maintain 
both  representations. 

3.  A  two-dimensional  array  move[s,a]  holding  the  transition  table  of  the 
NFA.  T he  entries  in  this  table,  which  are  sets  of  states,  are  represented 
by  linked  lists. 

To  implement  line  (1)  of  Fig.  3.37,  we  need  to  set  each  entry  in  array  al 
readyOn  to FALSE,  then  for  each  state  s  in  e-closure(so),  push  s  onto  oldStates 
and  set  alreadyOn[s]  to TRUE.  This  operation  on  state  s,  and  the  implementation 
of  line  (4)  as  well,  are  facilitated  by  a  function  we  shall  call  addState(s).  This 
function  pushes  state  s  onto  newStates,  sets  alreadyOn[s]  to TRUE,  and  calls 
itself  recursively  on  t he  states  in  move[s,e]  in  order  to  further  the  computation 
of  e-closure(s).  However,  to  avoid  duplicating  work,  we  must  be  careful  never 
to  call  addState  on  a  state  t h at  is  already  on  the  stack  newStates.  Figure  3.38 
sketches  this  function. 

addState(s) 

{ 

push  s  onto  newStates; 
alreadyOn[s]  =  TRUE; 
for  (  t  on  move[s, e]  ) 

9) 
10) 

11) 
12) 
13) 
14) 
15) 

Figure  3.38:  Adding  a  new  state  s,  which  is  known  not  to  be  on  newStates 

We  implement  line  (4)  of  Fig.  3.37  by  looking  at  each  state  s  on  oldStates. 
We  first  find  t he  set  of states  move[s, c],  where  c  is  the  next  input,  and  for  each 

158 

CHAPTER  3. 

LEXICAL  ANALYSIS 

of  those  states  t h at  is  not  already  on  newStates,  we  apply  addState  to  it.  Note 
t h at  addState  has  the  effect  of  computing  the  e- closure  and  adding  all  those 
states  to  newStates  as  well,  if  they  were  not  already  on.  This  sequence  of  steps 
is  summarized  in  Fig.  3.39. 

16) 
17) 
18) 
19) 
20) 
21) 

22) 
23) 
24) 
25) 
26) 

for  ( s on  oldStates  )  { 

for  (  t  on  move[s, c]  ) 

if  (  \alreadyOn[t]  ) 
addState(t); 

pop  s  from  oldStates; 

} 

for  (  s  on  newStates  )  { 

pop  s  from  newStates; 
push  s  onto  oldStates; 
a/readyOn[s]  =  FALSE; 

} 

Figure  3.39:  Implementation  of  step  (4)  of  Fig.  3.37 

Now,  suppose  t h at  t he  NFA  N  has  n  states  and  m  transitions;  i.e.,  m  is  the 
sum  over  all  states  of  the  number  of  symbols  (or  e)  on  which  the  state  has  a 
transition  out.  Not  counting  the  call  to  addState  at  line  (19)  of  Fig.  3.39,  t he 
time  spent  in  t he  loop  of  lines  (16)  through  (21)  is  0(n).  T h at  is,  we  can  go 
around  t he  loop  at  most  n  times,  and  each  step  of  the  loop  requires  constant 
work,  except  for  the  time  spent  in  addState.  T he  same  is  true  of  the  loop  of 
lines  (22)  through  (26). 

During  one  execution  of  Fig.  3.39,  i.e.,  of  step  (4)  of  Fig.  3.37,  it  is  only 
possible  to  call  addState  on  a  given  state  once.  The  reason  is  t h at  whenever 
we  call  addState(s),  we  set  alreadyOn[s]  to  TRUE  at  line  (11)  of  Fig.  3.39.  Once 
alreadyOn[s]  is  TRUE,  the  tests  at  line  (13)  of Fig.  3.38  and  line  (18)  of Fig.  3.39 
prevent  another  call. 

T he  time  spent  in  one  call  to  addState,  exclusive  of  t he  time  spent  in  recur 
sive  calls  at  line  (14),  is  0 ( 1)  for  lines  (10)  and  (11).  For  lines  (12)  and  (13), 
the  time  depends  on  how  many  e-transitions  there  are  out  of  state  s.  We  do 
not  know  this  number  for  a  given  state,  but  we  know  t h at  there  are  at  most  m 
transitions  in  total,  out  of  all  states.  As  a  result,  the  aggregate  time  spent  in 
lines  (11)  over  all  calls  to  addState  during  one  execution  of t he  code  of  Fig.  3.39 
is  0(m).  T he  aggregate  for  the  rest  of  t he  steps  of  addState  is  0(n),  since  it  is 
a  constant  per  call,  and  there  are  at  most  n  calls. 

We  conclude  t h a t,  implemented  properly,  the  time  to  execute  line  (4)  of 
Fig.  3.37  is  0(n  +  m ).  The  rest  of  t he  while-loop  of  lines  (3)  through  (6)  takes 
0 ( 1)  time  per  iteration. 
If  t he  input  x  is  of  length  k,  then  t he  total  work  in 
t h at  loop  is  0((k(n  +  m ) ).  Line  (1)  of  Fig.  3.37  can  be  executed  in  0 (n  +  m) 
time,  since  it  is  essentially  t he  steps  of  Fig.  3.39  with  oldStates  containing  only 

3.7. 

FROM  REGULAR  EXPRESSIONS 

TO  AUTOMATA 

159 

Big-Oh  Notation 

An  expression  like  0(n)  is  a  shorthand  for  "at  most  some  constant  times 
n."  Technically,  we  say  a  function  / ( n ),  perhaps  t he  running  time  of  some 
step  of  an  algorithm,  is  0(g(n))  if  there  are  constants  c  and  no,  such  t h at 
whenever  n  >  n0,  it  is  true  t h at  / ( n)  <  cg(n).  A  useful  idiom  is  " 0 ( 1 ) ," 
which  means  "some  constant."  The  use  of  this  big-oh  notation  enables 
us  to  avoid  getting  too  far  into  the  details  of  what  we  count  as  a  unit  of 
execution  time,  yet  lets  us  express  t he  rate  at  which  t he  running  time  of 
an  algorithm  grows. 

the  state  so-  Lines  (2),  (7),  and  (8)  each  take  0 ( 1)  time.  Thus,  the  running 
time  of  Algorithm  3.22,  properly  implemented,  is  0((k(n  +  m ) ).  T h at  is,  t he 
time  taken  is  proportional  to  the  length  of  the  input  times  t he  size  (nodes  plus 
edges)  of  t he  transition  graph. 

3.7.4  Construction  of an  NFA  from  a  Regular  Expression 

We  now  give  an  algorithm  for  converting  any  regular  expression  to  an  NFA 
t h at  defines  t he  same  language.  T he  algorithm  is  syntax-directed,  in  t he  sense 
t h at  it  works  recursively  up  the  parse  tree  for  the  regular  expression.  For  each 
subexpression  t he  algorithm  constructs  an  NFA  with  a  single  accepting  state. 

A l g o r i t hm  3 . 2 3:  T he  McNaughton-Yamada-Thompson  algorithm  to  convert 
a  regular  expression  to  an  NFA. 

I N P U T:  A  regular  expression  r  over  alphabet  S. 

O U T P U T:  An  NFA  N  accepting  L(r). 

M E T H O D:  Begin  by  parsing  r  into  its  constituent  subexpressions.  The  rules 
for  constructing  an  NFA  consist  of  basis  rules  for  handling  subexpressions  with 
no  operators,  and  inductive  rules  for  constructing  larger  NFA's  from  the  NFA's 
for  t he  immediate  subexpressions  of  a  given  expression. 

B A S I S:  For  expression  e  construct  the  NFA 

start 

Here,  i  is  a  new  state,  the  start  state  of  this  NFA,  and  /  is  another  new  state, 
t he  accepting  state  for  the  NFA. 

For  any  subexpression  a  in  S,  construct  t he  NFA 

start 

160 

CHAPTER  3. 

LEXICAL  ANALYSIS 

where  again  i  and  /  are  new  states,  the  start  and  accepting  states,  respectively. 
Note  t h at  in  b o th  of the  basis  constructions,  we  construct  a  distinct  NFA,  with 
new  states,  for  every  occurrence  of  e  or  some  o  as  a  subexpression  of  r. 

I N D U C T I O N:  Suppose  N(s)  and  N(t)  are  NFA's  for  regular  expressions  s  and 
t,  respectively. 

a)  Suppose  r  =  s\t.  Then  N(r),  t he  NFA  for  r,  is  constructed  as  in  Fig.  3.40. 
Here,  i  and  /  are  new  states,  the  start  and  accepting  states  of  N(r), 
respectively.  There  are  e-transitions  from  i  to  the  start  states  of  N(s) 
and  N(t),  and  each  of  their  accepting  states  have  e-transitions  to  the 
accepting  state  /.  Note  t h at  t he  accepting  states  of  N(s)  and  N(t)  are 
not  accepting  in  N(r).  Since  any  p a th  from  i  to  /  must  pass  through 
either  N(s)  or  N(t)  exclusively,  and  since  the  label  of  t h at  p a th  is  not 
changed  by  the  e's  leaving  i  or  entering  /,  we  conclude  t h at  N(r)  accepts 
L(s)  U  L(t),  which  is  t he  same  as  L(r).  T h at  is,  Fig.  3.40  is  a  correct 
construction  for  the  union  operator. 

Figure  3.40:  NFA  for  t he  union  of  two  regular  expressions 

b)  Suppose  r  =  st.  Then  construct  N(r)  as  in  Fig.  3.41.  T he  start  state  of 
N(s)  becomes  the  start  state  of  N(r),  and  t he  accepting  state  of  N(t)  is 
the  only  accepting  state  of  N(r).  T he  accepting  state  of  N(s)  and  t he 
start  state  of  N(t)  are  merged  into  a  single  state,  with  all  the  transitions 
in  or  out  of  either  state.  A  p a th  from  i  to  /  in  Fig.  3.41  must  go  first 
through  N(s),  and  therefore  its  label  will  begin  with  some  string  in  L(s). 
T he  p a th  then  continues  through  N(t),  so  the  p a t h 's  label  finishes  with  a 
string  in  L(t).  As  we  shall  soon  argue,  accepting  states  never  have  edges 
out  and  start  states  never  have  edges  in,  so  it  is  not  possible  for  a  p a th  to 
re-enter  N(s)  after  leaving  it.  Thus,  N(r)  accepts  exactly  L(s)L(i),  and 
is  a  correct  NFA  for  r  =  st. 

start 

Figure  3.41:  NFA  for  t he  concatenation  of  two  regular  expressions 

3.7. 

FROM  REGULAR  EXPRESSIONS 

TO  AUTOMATA 

161 

c)  Suppose  r  =  s*.  T h en  for  r  we  construct  t he  NFA  N(r)  shown  in  Fig.  3.42. 
Here,  i  and  /  are  new  states,  t he  start  state  and  lone  accepting  state  of 
N(r).  To  get  from  i  to  /,  we  can  either  follow  t he  introduced  p a th  labeled 
e,  which  takes  care  of  the  one  string  in  L(s)°,  or  we  can  go  to  the  start 
state  of  N(s),  through  t h at  NFA,  then  from  its  accepting  state  back  to 
its  start  state  zero  or  more  times.  These  options  allow  N(r)  to  accept  all 
the  strings  in  L(s)1,  L(s)2,  and  so  on,  so  the  entire  set  of  strings  accepted 
by  N(r) 

is  L(s*). 

£ 

£ 

Figure  3.42:  NFA  for  the  closure  of  a  regular  expression 

d)  Finally,  suppose  r  =  (s).  Then  L(r)  =  L(s),  and  we  can  use  the  NFA 

N(s)  as  N(r). 

• 

The  method  description  in  Algorithm  3.23  contains  hints  as  to  why  t he 
inductive  construction  works  as  it  should.  We  shall  not  give  a formal  correctness 
proof,  but  we  shall  list  several  properties  of  the  constructed  NFA's,  in  addition 
to  t he  all-important  fact  t h at  N(r)  accepts  language  L(r).  These  properties 
are  interesting  in  their  own  right,  and  helpful  in  making  a  formal  proof. 

1.  N(r)  has  at  most  twice  as  many  states  as  there  are  operators  and  operands 
in  r.  This  bound  follows  from  the  fact  t h at  each  step  of  the  algorithm 
creates  at  most  two  new  states. 

2.  N(r)  has  one  start  state  and  one  accepting  state.  T he  accepting  state  has 
no  outgoing  transitions,  and  the  start  state  has  no  incoming  transitions. 

3.  Each  s t a te  of  N(r)  other  t h an  t he  accepting  state  has  either  one  outgoing 
transition  on  a  symbol  in  E  or  two  outgoing  transitions,  b o th  on  e. 

E x a m p le  3 . 2 4:  Let  us  use  Algorithm  3.23  to  construct  an  NFA  for  r  = 
( a | b ) * a b b.  Figure  3.43  shows  a  parse  tree  for  r  t h at  is  analogous  to  the  parse 
trees  constructed  for  arithmetic  expressions  in  Section  2.2.3.  For  subexpression 
r i,  the  first  a,  we  construct  t he  NFA: 

162 

CHAPTER  3. 

LEXICAL  ANALYSIS 

10 

Figure  3.43:  Parse  tree  for  (a|b)*abb 

start 

State  numbers  have  been  chosen  for  consistency  with  what  follows.  For  r2  we 
construct: 

start 

• ©-

We  can  now  combine  JV(n)  and  N(r2),  using  the  construction  of  Fig.  3.40  to 
obtain  t he  NFA  for  r3  =  ri\r2]  this  NFA  is  shown  in  Fig.  3.44. 

start 

Figure  3.44:  NFA  for  r3 

T he  NFA  for  r4  =  (73)  is  the  same  as  t h at  for  7-3.  T he  NFA  for  r5  =  ( r3)*  is 
then  as  shown  in  Fig.  3.45.  We  have  used  t he  construction  in  Fig.  3.42  to  build 
this  NFA  from  the  NFA  in  Fig.  3.44. 

Now,  consider  subexpression  r§,  which  is  another  a.  We  use  t he  basis  con 
struction  for  a  again,  but  we  must  use  new  states.  It  is  not  permissible  to  reuse 

3.7. 

FROM  REGULAR  EXPRESSIONS 

TO  AUTOMATA 

163 

start 

£ 

£ 

Figure  3.45:  NFA  for  r5 

t he  NFA  we  constructed  for  r\,  even  though  r\  and  r%  are  the  same  expression. 
The  NFA  for  r6  is: 

start 

To  obtain  t he  NFA  for  rr  =  r5re,  we  apply  the  construction  of  Fig.  3.41.  We 
merge  states  7  and  7',  yielding  the  NFA  of Fig.  3.46.  Continuing  in  this  fashion 
with  new  NFA's  for  t he  two  subexpressions  b  called  rg  and  rio,  we  eventually 
construct  the  NFA  for  (a|b)*abb  t h at  we  first  met  in  Fig.  3.34. 

• 

start 

£ 

£ 

Figure  3.46:  NFA  for  r7 

3.7.5  Efficiency  of  String-Processing  Algorithms 

We  observed  t h at  Algorithm  3.18  processes  a  string  x  in  time  0(|a?|),  while  in 
Section  3.7.3  we  concluded  t h at  we  could  simulate  an  NFA  in  time  proportional 
to  the  product  of  \x\  and  t he  size  of  t he  NFA's  transition  graph.  Obviously,  it 

164 

CHAPTER  3. 

LEXICAL  ANALYSIS 

is  faster  to  have  a  DFA  to  simulate  t h an  an  NFA,  so  we  might  wonder  whether 
it  ever  makes  sense  to  simulate  an  NFA. 

One  issue  t h at  may  favor  an  NFA  is  t h at  the  subset  construction  can,  in  t he 
worst  case,  exponentiate  the  number  of  states.  While  in  principle,  the  number 
of  DFA  states  does  not  influence  t he  running  time  of  Algorithm  3.18,  should 
the  number  of  states  become  so  large  t h at  t he  transition  table  does  not  fit  in 
main  memory,  then  t he  true  running  time  would  have  to  include  disk  I /O  and 
therefore  rise  noticeably. 

E x a m p le  3 . 2 5:  Consider  the  family  of languages  described  by  regular  expres 
sions  of  t he  form  Ln  —  (a|b)*a(a|b)™_ 1,  t h at  is,  each  language  Ln  consists  of 
strings  of  a's  and  &'s  such  t h at  t he  n th  character  to  t he  left  of  t he  right  end 
holds  a.  An  n  +  1-state  NFA  is  easy  to  construct.  It  stays  in  its  initial  state 
under  any  input,  but  also  has  t he  option,  on  input  a,  of  going  to  state  1.  From 
state  1,  it  goes  to  state  2  on  any  input,  and  so  on,  until  in  state  n  it  accepts. 
Figure  3.47  suggests  this  NFA. 

a 

b 

Figure  3.47:  An  NFA  t h at  has  many  fewer  states  t h an  the  smallest  equivalent 
DFA 

However,  any  DFA  for  the  language  Ln  must  have  at  least  2n  states.  We 
shall  not  prove  this  fact,  but  t he  idea  is  t h at  if  two  strings  of  length  n  can 
get  t he  DFA  to  t he  same  state,  then  we  can  exploit  the  last  position  where 
t he  strings  differ  (and  therefore  one  must  have  a,  the  other  b)  to  continue  t he 
strings  identically,  until  they  are  t he  same  in  t he  last  n —  1  positions.  T he  DFA 
will  then  be  in  a  state  where  it  must  both  accept  and  not  accept.  Fortunately, 
as  we  mentioned,  it  is  rare  for  lexical  analysis  to  involve  p a t t e r ns  of  this  type, 
and  we  do  not  expect  to  encounter  DFA's  with  outlandish  numbers  of  states  in 
practice. 

• 

However,  lexical-analyzer  generators  and  other  string-processing  systems 
often  start  with  a  regular  expression.  We  are  faced  with  a  choice  of  converting 
the  regular  expression  to  an  NFA  or  DFA.  T he  additional  cost  of going  to  a  DFA 
is  thus  the  cost  of  executing  Algorithm  3.23  on  the  NFA  (one  could  go  directly 
from  a  regular  expression  to  a  DFA,  but  t he  work  is  essentially  t he  same).  If 
t he  string-processor  is  one  t h at  will  be  executed  many  times,  as  is  t he  case  for 
lexical  analysis,  then  any  cost  of  converting  to  a  DFA  is  worthwhile.  However, 
in  other  string-processing  applications,  such  as grep,  where  t he  user  specifies 
one  regular  expression  and  one  or  several  files  to  be  searched  for  t he  p a t t e rn 

3.7. 

FROM  REGULAR  EXPRESSIONS 

TO  AUTOMATA 

1 65 

of  t h at  expression,  it  may  be  more  efficient  to  skip  the  step  of  constructing  a 
DFA,  and  simulate  the  NFA  directly. 

Let  us  consider  the  cost  of  converting  a  regular  expression  r  to  an  NFA  by 
Algorithm  3 . 2 3.  A  key  step  is  constructing  t he  parse  tree  for  r.  In  Chapter  4 
we  shall  see  several  methods  t h at  are  capable  of  constructing  this  parse  tree  in 
linear  time,  t h at  is,  in  time  0 ( | r | ),  where  |r|  stands  for  the  size  of  r  —  the  sum 
of t he  number  of  operators  and  operands  in  r.  It  is  also  easy  to  check  t h at  each 
of  the  basis  and  inductive  constructions  of Algorithm  3 . 23  takes  constant  time, 
so  the  entire  time  spent  by  t he  conversion  to  an  NFA  is  0 ( [ r | ). 

Moreover,  as  we  observed  in  Section  3 . 7 . 4,  t he  NFA  we  construct  has  at 
most  |r|  states  and  at  most  2\r\  transitions.  T h at  is,  in  terms  of  t he  analysis 
in  Section  3 . 7 . 3,  we  have  n  <  \r\  and  m  <  2\r\.  Thus,  simulating  this  NFA  on 
an  input  string  x  takes  time  0(\r\  x  \x\).  This  time  dominates  the  time  taken 
by  t he  NFA  construction,  which  is  0 ( | r | ),  and  therefore,  we  conclude  t h at  it  is 
possible  to  take  a  regular  expression  r  and  string  x,  and  tell  whether  x  is  in 
L(r) 

in  time  0(\r\  x 

\x\). 

The  time  taken  by  the  subset  construction  is  highly  dependent  on  t he  num 
ber  of  states  the  resulting  DFA  has.  To  begin,  notice  t h at  in  t he  subset  con 
struction  of  Fig.  3 . 3 2,  t he  key  step,  t he  construction  of  a  set  of  states  U  from 
a  set  of  states  T  and  an  input  symbol  a,  is  very  much  like  the  construction  of 
a  new  set  of  states  from  the  old  set  of  states  in  the  NFA  simulation  of  Algo 
r i t hm  3 . 2 2.  We  already  concluded  t h a t,  properly  implemented,  this  step  takes 
time  at  most  proportional  to  the  number  of  states  and  transitions  of  the  NFA. 
Suppose  we  start  with  a  regular  expression  r  and  convert  it  to  an  NFA.  This 
NFA  has  at  most  |r|  states  and  at  most  2\r\  transitions.  Moreover,  there  are 
at  most  |r|  input  symbols.  Thus,  for  every  DFA  state  constructed,  we  must 
construct  at  most  |r|  new  states,  and  each  one  takes  at  most  0(\r\  +  2\r\)  time. 
T he  time  to  construct  a  DFA  of  s  states  is  thus  0{\r\2s). 

In  t he  common  case  where  s  is  about  |r|,  the  subset  construction  takes  time 
0(\r\3).  However,  in  the  worst  case,  as  in  Example  3 . 2 5,  this  time  is  0(\r\22^). 
Figure  3 . 48  summarizes  the  options  when  one  is  given  a  regular  expression  r 
and  wants  to  produce  a  recognizer  t h at  will  tell  whether  one  or  more  strings  x 
are  in  L(r). 

A U T O M A T ON 

I N I T I AL 

P ER  S T R I NG 

N FA 

D FA  typical  case 

0 ( | r |) 

0 ( | r f) 

D FA  worst  case 

0 ( | rf 

2 M) 

0(\r\  x 

\x\) 

0 ( | s |) 

0 ( | * |) 

Figure  3 . 4 8:  Initial  cost  and  per-string-cost  of  various  methods  of  recognizing 
t he  language  of  a  regular  expression 

If t he  per-string  cost  dominates,  as  it  does  when  we  build  a  lexical  analyzer, 

166 

CHAPTER  3. 

LEXICAL  ANALYSIS 

we  clearly  prefer  the  DFA.  However,  in  commands  like  g r e p,  where  we  run  the 
a u t o m a t on  on  only  one  string,  we  generally  prefer  t he  NFA.  It  is  not  until  |x| 
approaches  | r |3  t h at  we  would  even  think  about  converting  to  a  DFA. 

There  is,  however,  a  mixed  strategy  t h at  is  about  as  good  as  the  better  of 
the  NFA  and  the  DFA  strategy  for  each  expression  r  and  string  x.  Start  off 
simulating  the  NFA,  but  remember  the  sets  of NFA  states  (i.e.,  the  DFA  states) 
and  their  transitions,  as  we  compute  them.  Before  processing  t he  current  set  of 
NFA  states  and  t he  current  input  symbol,  check  to  see  whether  we  have  already 
computed  this  transition,  and  use  the  information  if  so. 

3.7.6  Exercises  for  Section  3.7 

E x e r c i se  3 . 7 . 1:  Convert  to  DFA's  t he  NFA's  of: 

a)  Fig.  3.26. 

b)  Fig.  3.29. 

c)  Fig.  3.30. 

E x e r c i se  3 . 7 . 2:  use  Algorithm  3.22  to  simulate  the  NFA's: 

a)  Fig.  3.29. 

b)  Fig.  3.30. 

on  input  aabb. 

E x e r c i se  3 . 7 . 3:  Convert  the  following  regular  expressions  to  deterministic 
finite  a u t o m a t a,  using  algorithms  3.23  and  3.20: 

a)  (a|b)*. 

b)  (a*|b*)*. 

c)  ((e|a)b*)*. 

d)  (a|b)*abb(a|b)*. 

3.8  Design  of a  Lexical-Analyzer  Generator 

In  this  section  we  shall  apply  the  techniques  presented  in  Section  3.7  to  see 
how  a  lexical-analyzer  generator  such  as  Lex  is  architected.  We  discuss  two 
approaches,  based  on  NFA's  and  DFA's;  the  latter  is  essentially  t he  implemen 
tation  of  Lex. 

3.8. 

DESIGN  OF  A 

LEXICAL-ANALYZER  GENERATOR 

167 

3.8.1  The  Structure  of  the  Generated  Analyzer 

Figure  3.49  Overviews  t he  architecture  of  a  lexical  analyzer  generated  by  Lex. 
T he  program  t h at  serves  as  the  lexical  analyzer  includes  a  fixed  program  t h at 
simulates  an  a u t o m a t o n;  at  this  point  we  leave  open  whether  t h at  a u t o m a t on 
is  deterministic  or  nondeterministic.  T he  rest  of the  lexical  analyzer  consists  of 
components  t h at  are  created  from  the  Lex  program  by  Lex  itself. 

Input  buffer 

lexeme 

lexemeBegin 

Automaton 
simulator 

Transition 
table 

Actions 

Lex 
program 

Lex 
Lex 
compiler 
compiler 

Figure  3.49:  A  Lex  program  is  turned  into  a  transition  table  and  actions,  which 
are  used  by  a  finite-automaton  simulator 

These  components  are: 

1.  A  transition  table  for  t he  automaton. 

2.  Those  functions  t h at  are  passed  directly  through  Lex  to  the  output  (see 

Section  3.5.2). 

3.  T he  actions  from  the  input  program,  which  appear  as  fragments  of  code 

to  be  invoked  at  t he  appropriate  time  by  the  a u t o m a t on  simulator. 

To  construct  t he  automaton,  we  begin  by  taking  each  regular-expression 
p a t t e rn  in  the  Lex  program  and  converting  it,  using  Algorithm  3.23,  to  an  NFA. 
We  need  a  single  a u t o m a t on  t h at  will  recognize  lexemes  matching  any  of  t he 
p a t t e r ns  in  t he  program,  so  we  combine  all  the  NFA's  into  one  by  introducing 
a  new  start  state  with  e-transitions  to  each  of  the  start  states  of  t he  NFA's  N{ 
for  p a t t e rn  pi.  This  construction  is  shown  in  Fig.  3.50. 

E x a m p le  3 . 2 6:  We  shall  illustrate  t he  ideas  of  this  section  with  t he  following 
simple,  abstract  example: 

168 

CHAPTER  3. 

LEXICAL  ANALYSIS 

Figure  3.50:  An  NFA  constructed  from  a Lex  program 

a 
a bb 
a * b+ 

{  action  A\  for  p a t t e rn  p\  } 
{  action  A2  for  p a t t e rn  p2  } 
{  action  As  for  p a t t e rn p%  } 

Note  t h at  these  three  p a t t e r ns  present  some  conflicts  of  t he  type  discussed 
in  Section  3.5.3.  In  particular,  string  abb  matches  both  t he  second  and  third 
patterns,  but  we  shall  consider  it  a  lexeme  for  p a t t e rn  p2,  since  t h at  p a t t e rn 
is  listed  first  in  the  above Lex  program.  Then,  input  strings  such  as  aabbb •  •  • 
have  many  prefixes  t h at  match  t he  third  p a t t e r n.  T he Lex  rule  is  to  take  the 
longest,  so  we  continue  reading  6's,  until  another  a  is  met,  whereupon  we  report 
t he  lexeme  to  be  t he  initial  a's  followed  by  as  many  6's  as  there  are. 

Figure  3.51  shows  three  NFA's  t h at  recognize  t he  three  patterns.  T he  third 
is  a  simplification  of  what  would  come  out  of  Algorithm  3.23.  Then,  Fig.  3.52 
shows  these  three  NFA's  combined  into  a  single  NFA  by  the  addition  of  start 
state  0  and  three  e-transitions. 

• 

3.8.2  Pattern  Matching  Based  on  NFA's 

If t he  lexical  analyzer  simulates  an  NFA  such  as  t h at  of Fig.  3.52,  then  it  must 
read  input  beginning  at  t he  point  on  its  input  which  we  have  referred  to  as 
lexemeBegin.  As  it  moves  t he  pointer  called  forward  ahead  in  the  input, 
it 
calculates  t he  set  of  states  it  is  in  at  each  point,  following  Algorithm  3.22. 

Eventually,  t he  NFA  simulation  reaches  a  point  on  the  input  where  there 
are  no  next  states.  At  t h at  point,  there  is  no  hope  t h at  any  longer  prefix  of the 
input  would  ever  get  t he  NFA  to  an  accepting  state;  rather,  the  set  of  states 
will  always  be  empty.  Thus,  we  are  ready  to  decide  on  t he  longest  prefix  t h at 
is  a  lexeme  matching  some  p a t t e r n. 

Figure  3.53:  Sequence  of  sets  of  states  entered  when  processing  input  aaba 

170 

CHAPTER  3. 

LEXICAL  ANALYSIS 

We  look  backwards  in  the  sequence  of  sets  of  states,  until  we  find  a  set  t h at 
includes  one  or  more  accepting  states.  If  there  are  several  accepting  states  in 
t h at  set,  pick  the  one  associated  with  the  earliest  p a t t e rn  pi  in  t he  list  from 
t he  Lex  program.  Move  the  forward  pointer  back  to  the  end  of the  lexeme,  and 
perform  the  action  Ai  associated  with  p a t t e rn  pi. 

E x a m p le  3 . 2 7:  Suppose  we  have  the  patterns  of  Example  3.26  and  t he  input 
begins  aaba.  Figure  3.53  shows  the  sets  of  states  of  t he  NFA  of  Fig.  3.52  t h at 
we  enter,  starting  with  e-closure  of  t he  initial  state  0,  which  is  { 0 , 1 , 3 , 7 },  and 
proceeding  from  there.  After  reading  the  fourth  input  symbol,  we  are  in  an 
empty  set  of states,  since  in  Fig.  3.52,  there  are  no  transitions  out  of state  8  on 
input  a. 

Thus,  we  need  to  back  up,  looking  for  a  set  of  states  t h at  includes  an  ac 
cepting  state.  Notice  t h a t,  as  indicated  in  Fig.  3.53,  after  reading  a  we  are 
in  a  set  t h at  includes  state  2  and  therefore  indicates  t h at  the  p a t t e rn  a  has 
been  matched.  However,  after  reading  aab,  we  are  in  state  8,  which  indicates 
t h at  a * b+  has  been  matched;  prefix  aab  is  the  longest  prefix  t h at  gets  us  to  an 
accepting  state.  We  therefore  select  aab  as  the  lexeme,  and  execute  action  A3, 
which  should  include  a  return  to  the  parser  indicating  t h at  t he  token  whose 
p a t t e rn  is  p3  =  a * b+  has  been  found. 

• 

3.8.3  DFA's  for  Lexical  Analyzers 

Another  architecture,  resembling  the  output  of  Lex,  is  to  convert  t he  NFA 
for  all  the  patterns  into  an  equivalent  DFA,  using  t he  subset  construction  of 
Algorithm  3.20.  Within  each  DFA  state,  if  there  are  one  or  more  accepting 
NFA  states,  determine  t he  first  p a t t e rn  whose  accepting  state  is  represented, 
and  make  t h at  p a t t e rn  t he  output  of  t he  DFA  state. 

E x a m p le  3 . 2 8:  Figure  3.54  shows  a  transition  diagram  based  on  the  DFA 
t h at  is  constructed  by  the  subset  construction  from  t he  NFA  in  Fig.  3.52.  The 
accepting  states  are  labeled  by  the  p a t t e rn  t h at  is  identified  by  t h at  state.  For 
instance,  t he  state  {6,8}  has  two  accepting  states,  corresponding  to  p a t t e r ns 
a bb  and  a * b+.  Since  t he  former  is  listed  first,  t h at  is  the  p a t t e rn  associated 
with  state  { 6 , 8 }. 

• 

We  use  the  DFA  in  a  lexical  analyzer  much  as  we  did  the  NFA.  We  simulate 
t he  DFA  until  at  some  point  there  is  no  next  state  (or  strictly  speaking,  the 
next  state  is 0,  the  dead  state  corresponding  to  t he  empty  set  of  NFA  states). 
At  t h at  point,  we  back  up  through  the  sequence  of  states  we  entered  and,  as 
soon  as  we  meet  an  accepting  DFA  state,  we  perform  the  action  associated  with 
t he  p a t t e rn  for  t h at  state. 

E x a m p le  3 . 2 9:  Suppose  the  DFA  of  Fig.  3.54  is  given  input  abba.  T he  se 
quence  of  states  entered  is  0137,247,58,68,  and  at  the  final  a  there  is  no  t r a n 
sition  out  of state  68.  Thus,  we  consider  the  sequence  from  t he  end,  and  in  this 
case,  68  itself  is  an  accepting  state  t h at  reports  p a t t e rn  p2  =  a b b. 

• 

3.8. 

DESIGN  OF  A  LEXICAL-ANALYZER  GENERATOR 

171 

a 

start 

b 

a*b+ 

abb 

a*b+ 

Figure 3.54:  Transition graph for DFA  handling t he p a t t e r ns a, abb,  and a * b+ 

3.8.4 

Implementing  the  Lookahead  Operator 

Recall  from  Section 3.5.4  t h at  t he Lex  lookahead  operator  /  in  a Lex  p a t t e rn 
r\/r2  is  sometimes  necessary,  because  the  p a t t e rn  r*i  for  a  particular  token  may 
need  to  describe  some  trailing  context  r2  in  order  to  correctly  identify  the  actual 
lexeme.  W h en  converting  the  p a t t e rn  r\/r2  to  an  NFA,  we  treat  the  /  as  if  it 
were  e,  so  we  do  not  actually  look  for  a  /  on  t he  input.  However,  if  t he  NFA 
recognizes  a  prefix  xy  of  t he  input  buffer  as  matching  this  regular  expression, 
t he  end  of t he  lexeme  is  not  where  t he  NFA  entered  its  accepting  state.  R a t h er 
t he  end  occurs  when  the  NFA  enters  a  state  s  such  t h at 

1.  s  has  an  e-transition  on  the  (imaginary)  /, 

2.  There  is  a  path  from  the  start  state  of t he  NFA  to  state  s  t h at  spells  out 

x. 

3. There  is  a  p a th  from  state  s  to  the  accepting  state  t h at  spells  out  y. 

4. x  is  as  long  as  possible  for  any  xy  satisfying  conditions 1-3. 

If  there  is  only  one  e-transition  state  on  the  imaginary  /  in  t he  NFA,  then 
the  end  of  the  lexeme  occurs  when  this  state  is  entered  for  t he  last  time  as  the 
following  example  illustrates.  If  t he  NFA  has  more  t h an  one  e-transition  state 
on  t he  imaginary  /,  then  t he  general  problem  of  finding  the  correct  state  s  is 
much  more  difficult. 

E x a m p le 3.30:  An  NFA  for  the  p a t t e rn  for  the  Fortran IF  with  lookahead, 
from  Example 3.13,  is  shown  in  Fig. 3.55.  Notice  t h at  t he  e-transition  from 
state 2  to  state 3  represents  t he  lookahead  operator.  State 6  indicates  the  pres 
ence  of t he  keyword IF.  However,  we  find  the  lexeme IF  by  scanning  backwards 
to  t he  last  occurrence  of  state 2,  whenever  state 6  is  entered. 

• 

172 

CHAPTER  3. 

LEXICAL  ANALYSIS 

Dead  States  in  DFA's 

Technically,  the  a u t o m a t on  in  Fig.  3.54  is  not  quite  a  DFA.  T he  reason 
is  t h at  a  DFA  has  a  transition  from  every  state  on  every  input  symbol  in 
its  input  alphabet.  Here,  we  have  omitted  transitions  to  the  dead  state 
0,  and  we  have  therefore  omitted  the  transitions  from  t he  dead  state  to 
itself  on  every  input.  Previous  NFA-to-DFA  examples  did  not  have  a  way 
to  get  from  the  start  state  to 0,  but  the  NFA  of  Fig.  3.52  does. 

However,  when  we  construct  a  DFA  for  use  in  a  lexical  analyzer,  it 
is  important  t h at  we  treat  t he  dead  state  differently,  since  we  must  know 
when  there  is  no  longer  any  possibility  of  recognizing  a  longer  lexeme. 
Thus,  we  suggest  always  omitting  transitions  to  t he  dead  state  and  elimi 
nating  the  dead  state  itself.  In  fact,  t he  problem  is  harder  t h an  it  appears, 
since  an  NFA-to-DFA  construction  may  yield  several  states  t h at  cannot 
reach  any  accepting  state,  and  we  must  know  when  any  of  these  states 
have  been  reached.  Section  3.9.6  discusses  how  to  combine  all  these  states 
into  one  dead  state,  so  their  identification  becomes  easy.  It  is  also  inter 
esting  to  note  t h at  if  we  construct  a  DFA  from  a  regular  expression  using 
Algorithms  3.20  and  3.23,  then  the  DFA  will  not  have  any  states  besides 
0  t h at  cannot  lead  to  an  accepting  state. 

any 

Figure  3.55:  NFA  recognizing  the  keyword  IF 

3.8.5  Exercises  for  Section  3.8 

E x e r c i se  3 . 8 . 1:  Suppose  we  have  two  tokens:  (1)  t he  keyword  if,  and  (2)  id 
entifiers,  which  are  strings  of letters  other  t h an  i f.  Show: 

a)  T he  NFA  for  these  tokens,  and 

b)  The  DFA  for  these  tokens. 

E x e r c i se  3 . 8 .2  :  Repeat  Exercise  3.8.1  for  tokens  consisting  of  (1)  t he  keyword 
w h i l e,  (2)  the  keyword  when,  and  (3)  identifiers  consisting  of  strings  of  letters 
and  digits,  beginning  with  a  letter. 

!  E x e r c i se  3 . 8 . 3:  Suppose  we  were  to  revise  t he  definition  of  a  DFA  to  allow 
zero  or  one  transition  out  of  each  state  on  each  input  symbol  (rather  t h an 
exactly  one  such  transition,  as  in  t he  standard  DFA  definition).  Some  regular 

3.9. 

OPTIMIZATION  OF  DFA-BASED  PATTERN 

MATCHERS 

173 

expressions  would  then  have  smaller  "DFA's"  t h an  they  do  under  the  standard 
definition  of  a  DFA.  Give  an  example  of  one  such  regular  expression. 

!!  E x e r c i se  3 . 8 . 4:  Design  an  algorithm  to  recognize  Lex-lookahead  p a t t e r ns  of 
t he  form  r i / r2,  where  r\  and  r2  are  regular  expressions.  Show  how  your  algo 
rithm  works  on  t he  following  inputs: 

a) 

(abcd\abc)jd 

b) 

(a\ab)/ba 

c)  aa  *  j  a* 

3.9  Optimization  of  DFA-Based  Pattern 

Matchers 

In  this  section  we  present  three  algorithms  t h at  have  been  used  to  implement 
and  optimize  p a t t e rn  matchers  constructed  from  regular  expressions. 

1.  T he  first  algorithm  is  useful  in  a  Lex  compiler,  because  it  constructs  a 
DFA  directly  from  a  regular  expression,  without  constructing  an  interme 
diate  NFA.  The  resulting  DFA  also  may  have  fewer  states  t h an  the  DFA 
constructed  via  an  NFA. 

2.  T he  second  algorithm  minimizes  the  number  of  states  of  any  DFA,  by 
combining  states  t h at  have  the  same  future  behavior.  T he  algorithm 
itself  is  quite  efficient,  running  in  time  0(n log n ),  where  n  is  the  number 
of  states  of  t he  DFA. 

3.  T he  third  algorithm  produces  more  compact  representations  of  transition 

tables  t h an  t he  standard,  two-dimensional  table. 

3.9.1 

Important  States  of  an  NFA 

To  begin  our  discussion  of  how  to  go  directly  from  a  regular  expression  to  a 
DFA,  we  must  first  dissect  the  NFA  construction  of Algorithm  3.23  and  consider 
the  roles  played  by  various  states.  We  call  a  state  of an  NFA  important if it  has  a 
non-e  out-transition.  Notice  t h at  t he  subset  construction  (Algorithm  3.20)  uses 
only  the  important  states  in  a  set  T  when  it  computes  e-closure(move(T,  a)),  the 
set  of  states  reachable  from  T  on  input  a.  T h at  is,  the  set  of  states  move(s,  a) 
is  nonempty  only  if  state  s  is  important.  During  the  subset  construction,  two 
sets  of  NFA  states  can  be  identified  (treated  as  if  they  were  t he  same  set)  if 
they: 

1.  Have  the  same  important  states,  and 

2.  Either  b o th  have  accepting  states  or  neither  does. 

174 

CHAPTER  3. 

LEXICAL  ANALYSIS 

When  the  NFA  is  constructed  from  a  regular  expression  by  Algorithm  3.23, 
we  can  say  more  about  the  important  states.  The  only  important  states  are 
those  introduced  as  initial  states  in  t he  basis  p a rt  for  a  particular  symbol  posi 
tion  in  the  regular  expression.  T h at  is,  each  important  state  corresponds  to  a 
particular  operand  in  the  regular  expression. 

The  constructed  NFA  has  only  one  accepting  state,  but  this  state,  having 
no  out-transitions,  is  not  an  important  state.  By  concatenating  a  unique  right 
endmarker  #  to  a  regular  expression  r,  we  give  the  accepting  state  for  r  a 
transition  on  #,  making  it  an  important  state  of  t he  NFA  for  ( r ) #.  In  other 
words,  by  using  t he  augmented  regular  expression  ( r ) #,  we  can  forget  about 
accepting  states  as  t he  subset  construction  proceeds;  when  the  construction  is 
complete,  any  state  with  a  transition  on  #  must  be  an  accepting  state. 

The  important  states  of  the  NFA  correspond  directly  to  t he  positions  in 
the  regular  expression  t h at  hold  symbols  of  the  alphabet. 
It  is  useful,  as  we 
shall  see,  to  present  the  regular  expression  by  its  syntax  tree,  where  t he  leaves 
correspond  to  operands  and  the  interior  nodes  correspond  to  operators.  An 
interior  node  is  called  a  cat-node,  or-node,  or  star-node  if  it  is  labeled  by  the 
concatenation  operator  (dot),  union  operator  |,  or  star  operator  *,  respectively. 
We  can  construct  a  syntax  tree  for  a  regular  expression  just  as  we  did  for 
arithmetic  expressions  in  Section  2.5.1. 

E x a m p le  3 . 3 1:  Figure  3.56  shows  t he  syntax  tree  for  the  regular  expression 
of  our  running  example.  Cat-nodes  are  represented  by  circles. 

• 

Figure  3.56:  Syntax  tree  for  ( a | b ) * a b b# 

Leaves  in  a  syntax  tree  are  labeled  by  e  or  by  an  alphabet  symbol.  To  each 
leaf  not  labeled  e,  we  attach  a  unique  integer.  We  refer  to  this  integer  as  the 

OPTIMIZATION 

OF  DFA-BASED 

PATTERN  MATCHERS 

175 

position  of  the  leaf  and  also  as  a  position  of  its  symbol.  Note  t h at  a  symbol 
can  have  several  positions;  for  instance,  a  has  positions  1  and  3  in  Fig.  3.56. 
T he  positions  in  the  syntax  tree  correspond  to  the  important  states  of  t he 
constructed  NFA. 

E x a m p le  3 . 3 2:  Figure  3.57  shows  t he  NFA  for  t he  same  regular  expression  as 
Fig.  3.56,  with  the  important  states  numbered  and  other  states  represented  by 
letters.  T he  numbered  states  in  the  NFA  and  the  positions  in  t he  syntax  tree 
correspond  in  a  way  we  shall  soon  see. 

• 

3.9.2  Functions  Computed  From  the  Syntax  Tree 

To  construct  a  DFA  directly  from  a  regular  expression,  we  construct  its  syntax 
tree  and  then  compute  four  functions:  nullable,  firstpos,  lastpos,  and  followpos, 
defined  as  follows.  Each  definition  refers  to  the  syntax  tree  for  a  particular 
augmented  regular  expression  ( r ) #. 

1.  nullable(n)  is  true  for  a  syntax-tree  node  n  if  and  only  if t he  subexpression 
represented  by  n  has  e  in  its  language.  T h at  is,  t he  subexpression  can  be 
"made  null"  or  the  empty  string,  even  though  there  may  be  other  strings 
it  can  represent  as  well. 

2.  firstpos(n)  is  the  set  of  positions  in  the  subtree  rooted  at  n  t h at  corre 
spond  to  t he  first  symbol  of  at  least  one  string  in  the  language  of  t he 
subexpression  rooted  at  n. 

3.  lastpos(n)  is  the  set  of  positions  in  the  subtree  rooted  at  n  t h at  corre 
spond  to  the  last  symbol  of  at  least  one  string  in  the  language  of  the 
subexpression  rooted  at  n. 

176 

CHAPTER  3. 

LEXICAL  ANALYSIS 

4.  followpos(p),  for  a  position  p,  is  the  set  of  positions  q  in  the  entire  syntax 
tree  such  t h at  there  is  some  string  x  =  axa2  •••  an  in  L ( ( r ) #)  such  t h at 
for  some  i,  there  is  a  way  to  explain  the  membership  of  x  in  L ( ( r ) #)  by 
matching 

to  position  p  of  t he  syntax  tree  and  ai+i  to  position  g. 

E x a m p le  3 . 3 3:  Consider  the  cat-node  n  in  Fig.  3.56  t h at  corresponds  to  the 
expression  (a|b)*a.  We  claim  nullable(ri)  is  false,  since  this  node  generates  all 
strings  of a's  and  6's  ending  in  an  a;  it  does  not  generate  e.  On  the  other  hand, 
the  star-node  below  it  is  nullable;  it  generates  e  along  with  all  other  strings  of 
a's  and  6's. 

firstpos{n)  —  { 1 , 2 , 3 }.  In  a typical  generated  string like  aa,  the  first  position 
of  the  string  corresponds  to  position  1  of  the  tree,  and  in  a  string  like  6a,  the 
first  position  of  the  string  comes  from  position  2  of  t he  tree.  However,  when 
the  string  generated  by  the  expression  of  node  n  is  just  a,  then  this  a  comes 
from  position  3. 

lastpos{n)  —  {3}.  T h at  is,  no  m a t t er  what  string  is  generated  from  t he 

expression  of  node  n,  the  last  position  is  t he  a  from  position  3  of  the  tree. 

followpos  is  trickier  to  compute,  but  we  shall  see  the  rules  for  doing  so 
shortly.  Here  is  an  example  of t he  reasoning:  followpos(l)  —  { 1 , 2 , 3 }.  Consider 
a  string  •  •  • ac •  •  •,  where  the  c is  either  a  or  6,  and  the  a  comes  from  position  1. 
T h at  is,  this  a  is  one  of  those  generated  by  the  a  in  expression  (a|b)*.  This 
a  could  be  followed  by  another  a  or  6  coming  from  the  same  subexpression,  in 
which  case  c  comes  from  position  1  or  2.  It  is  also  possible  t h at  this  a  is  t he 
last  in  the  string  generated  by  (a|b)*,  in  which  case  the  symbol  c  must  be  t he 
a  t h at  comes  from  position  3.  Thus,  1,2,  and  3  are  exactly  the  positions  t h at 
can  follow  position  1. 

.  ' 

• 

• 

3.9.3 

Computing  nullable,  firstpos,  and  lastpos 

We  can  compute  nullable,  firstpos,  and  lastpos  by  a  straightforward  recursion 
on  the  height  of t he  tree.  T he  basis  and  inductive  rules  for  nullable  and  firstpos 
are  summarized  in  Fig.  3.58.  T he  rules  for  lastpos  are  essentially  t he  same  as 
for  firstpos,  but  t he  roles  of  children  c\  and  c2  must  be  swapped  in  t he  rule  for 
a  cat-node. 

E x a m p le  3 . 3 4:  Of  all  the  nodes  in  Fig.  3.56  only  t he  star-node  is  nullable. 
We  note  from  the  table  of Fig.  3.58  t h at  none  of the  leaves  are  nullable,  because 
they  each  correspond  to  non-e  operands.  The  or-node  is  not  nullable,  because 
neither  of  its  children  is.  The  star-node  is  nullable,  because  every  star-node  is 
nullable.  Finally,  each  of  t he  cat-nodes,  having  at  least  one  nonnullable  child, 
is  not  nullable. 

T he  computation  of  firstpos  and  lastpos  for  each  of  t he  nodes  is  shown  in 
Fig.  3.59,  with  firstposin)  to  t he  left  of node  n,  and  lastpos(n)  to  its  right.  Each 
of  the  leaves  has  only  itself  for  firstpos  and  lastpos,  as  required  by  t he  rule  for 
non-e  leaves  in  Fig.  3.58.  For  t he  or-node,  we  take  t he  union  of  firstpos  at  t he 

OPTIMIZATION 

OF 

DFA-BASED 

PATTERN  MATCHERS 

177 

N O DE 

n 

nullable{n) 

firstpos(n) 

A  leaf  labeled  e 

A  leaf  with  position  i 

An  or-node  n  =  c\\c2 

A cat-node n = C

1

t r ue 

false 

nullable(c\) 

or 
nullable(c2) 

nullable(ci) 

a nd 
C2 
nullable(c2) 

0 

« 

firstpos(c\)  U  firstpos(c2) 

if  (  nullable(ci)  ) 
firstpos(c\)  U  firstpos(c2) 
e l se f i r s t p o s ( c i) 

A  star-node  n  =  c\ * 

t r ue 

firstpos(ci) 

Figure  3.58:  Rules  for  computing  unliable  and  firstpos 

children  and  do  the  same  for  lastpos.  The  rule  for  the  star-node  says  t h at  we 
take  the  value  of  firstpos  or  lastpos  at  the  one  child  of  t h at  node. 

Now,  consider  the  lowest  cat-node,  which  we  shall  call  n.  To  compute 
firstpos(n),  we  first  consider  whether  the  left  operand  is  mailable,  which  it  is 
in  this  case.  Therefore,  firstpos  for  n  is  the  union  of  firstpos  for  each  of  its 
children,  t h at  is  {1,2}  U  {3}  =  { 1 , 2 , 3 }.  T he  rule  for  lastpos  does  not  ap 
pear  explicitly  in  Fig.  3.58,  but  as  we  mentioned,  the  rules  are  the  same  as 
for  firstpos,  with  the  children  interchanged.  T h at  is,  to  compute  lastpos(n)  we 
must  ask  whether  its  right  child  (the  leaf  with  position  3)  is  nullable,  which  it 
is  not.  Therefore,  lastpos(n)  is  the  same  as  lastpos  of  t he  right  child,  or  {3}. 
• 

3.9.4  Computing  followpos 

Finally,  we  need  to  see  how  to  compute  followpos.  There  are  only  two  ways 
t h at  a  position  of  a  regular  expression  can  be  made  to  follow  another. 

1.  If n is a cat-node with left child c\ and right child C

2, then for every 

position  i  in  lastpos(ci),  all  positions  in firstpos(c2) are  in  followpos(i). 

2.  If  n  is  a  star-node,  and  i  is  a  position  in  lastpos(n),  t h en  all  positions  in 

firstpos(n)  are 

in 

followpos(i). 

E x a m p le  3 . 35  :  Let  us  continue  with  our  running  example;  recall  t h at  firstpos 
and  lastpos  were  computed  in  Fig.  3.59.  Rule  1  for  followpos  requires  t h at  we 
look  at  each  cat-node,  and  put  each  position  in  firstpos  of  its  right  child  in 
followpos  for  each  position  in  lastpos  of  its  left  child.  For  the  lowest  cat-node  in 
Fig.  3.59,  t h at  rule  says  position  3  is  in  followpos(l)  and  followpos{2).  The  next 
cat-node  above  says  t h at  4  is  in  followpos(2>),  and  t he  remaining  two  cat-nodes 
give  us  5  in  followpos(4)  and  6  in  followpos(5). 

178 

CHAPTER  3. 

LEXICAL  ANALYSIS 

{1,2,3}  o (6) 

{1,2,3}  o {5} 

{6}  # { 6} 

{1,2,3}  o {4} 

{5}  b {5} 

{1,2,3}  o {3} 

{4}  b {4} 

{1,2}  * {1,2} 

{3}  a {3} 

{1,2} I {1,2} 

{1}  a {1} 

{2}  b 12} 

Figure  3.59:  firstpos  and  lastpos  for  nodes  in  t he  syntax  tree  for  ( a | b ) * a b b# 

We  must  also  apply  rule  2  to  the  star-node.  T h at  rule  tells  us  positions  1  and 
2  are  in  b o th  followpos(l)  and  followpos(2),  since  both  firstpos  and  lastpos  for 
this  node  are  { 1 , 2 }.  T he  complete  sets  followpos  are  summarized  in  Fig.  3.60. 
• 

N O DE 

n 

followpos(n) 

1 
2 
3 
4 
5 
6 

{ 1 , 2 , 3} 
{ 1 , 2 , 3} 

{4} 
{5} 
{6} 
0 

Figure  3.60:  The  function  followpos 

We  can  represent  the  function  followpos  by  creating  a  directed  graph  with 
a  node  for  each  position  and  an  arc  from  position  i  to  position  j  if  and  only  if 
j  is  in  followpos(i).  Figure  3.61  shows  this  graph  for  the  function  of  Fig.  3.60. 
It  should  come  as  no  surprise  t h at  t he  graph  for  followpos  is  almost  an  NFA 
without  e-transitions  for  t he  underlying  regular  expression,  and  would  become 
one  if  we: 

1.  Make  all  positions  in  firstpos  of  the  root  be  initial  states, 

2.  Label  each  arc  from  i  to  j  by  t he  symbol  at  position  i,  and 

OPTIMIZATION 

OF 

DFA-BASED 

PATTERN  MATCHERS 

179 

:0 

Figure  3.61:  Directed  graph  for  the  function  followpos 

3.  Make  the  position  associated  with  endmarker  #  be  the  only  accepting 

state. 

3 . 9 .5  Converting a Regular Expression Directly to  a DFA 

A l g o r i t hm  3 . 3 6:  Construction  of  a  DFA  from  a  regular  expression  r. 

I N P U T:  A  regular  expression  r. 

O U T P U T:  A  DFA  D  t h at  recognizes  L(r). 

M E T H O D: 

1.  Construct  a  syntax  tree  T  from  the  augmented  regular  expression  ( r ) #. 

2.  Compute  nullable,  firstpos,  lastpos,  and  followpos  for  T,  using  the  methods 

of  Sections  3.9.3  and  3.9.4. 

3.  Construct  Dstates,  the  set  of  states  of  DFA  D,  and  Dtran,  t he  transition 
function  for  D,  by  the  procedure  of  Fig.  3.62.  T he  states  of  D  are  sets  of 
positions  in  T.  Initially,  each  state  is  "unmarked,"  and  a  state  becomes 
"marked"  just  before  we  consider  its  out-transitions.  T he  start  state  of 
D  is  firstpos(no),  where  node  no  is  t he  root  of  T.  T he  accepting  states 
are  those  containing  t he  position  for  the  endmarker  symbol  #. 

• 

E x a m p le  3 . 3 7:  We  can  now  put  together  the  steps  of  our  running  example 
to  construct  a  DFA  for  the  regular  expression  r  =  (a|b)*abb.  T he  syntax  tree 
for  ( r )#  appeared  in  Fig.  3.56.  We  observed  t h at  for  this  tree,  nullable  is  true 
only  for  the  star-node,  and  we  exhibited  firstpos  and  lastpos  in  Fig.  3.59.  T he 
values  of  followpos  appear  in  Fig.  3.60. 

T he  value  of  firstpos  for  t he  root  of  t he  tree  is  { 1 , 2 , 3 },  so  this  set  is  the 
start  state  of  D.  Call  this  set  of  states  A.  We  must  compute  Dtran[A, a] 
and  Dtran[A,  b].  Among  t he  positions  of  A,  1  and  3  correspond  to  a,  while  2 
corresponds  to  b.  Thus,  Dtran[A,a]  =  followpos(l)  U  followpos(3)  =  { 1 , 2 , 3 , 4 }, 

180 

CHAPTER  3. 

LEXICAL  ANALYSIS 

initialize  Dstates  to  contain  only  the  unmarked  state  firstpos(no), 

where  no  is  t he  root  of  syntax  tree  T  for  ( r ) #; 

w h i le  (  there  is  an  unmarked  state  S  in  Dstates  )  { 

mark  S; 
for  (  each  input  symbol  a  )  { 

let  U  be  the  union  of followpos(p)  for  all  p 

in  S  t h at  correspond  to  a; 

if  (  U  is  not  in  Dstates  ) 

add  U  as  an  unmarked  state  to  Dstates; 

Dtran[S,  a)  =  U; 

} 

} 

Figure  3.62:  Construction  of  a  DFA  directly  from  a  regular  expression 

and  Dtran[A,  b]  =  followpos{2)  =  { 1 , 2 , 3 }.  T he  latter  is  state  A,  and  so  does 
not  have  to  be  added  to  Dstates,  but  the  former,  B  =  { 1 , 2 , 3 , 4 },  is  new,  so  we 
add  it  to  Dstates  and  proceed  to  compute  its  transitions.  T he  complete  DFA  is 
shown  in  Fig.  3.63. 

• 

b 

start 

a 

Figure  3.63:  DFA  constructed  from  Fig.  3.57 

3.9.6  Minimizing  the  Number  of  States  of  a  DFA 

There  can  be  many  DFA's  t h at  recognize  the  same  language.  For  instance,  note 
t h at  the  DFA's  of  Figs.  3.36  and  3.63  both  recognize  language  L ( ( a | b ) * a b b ). 
Not  only  do  these  a u t o m a ta  have  states  with  different  names,  but  they  don't 
even  have  the  same  number  of  states. 
If  we  implement  a  lexical  analyzer  as 
a  DFA,  we  would  generally  prefer  a  DFA  with  as  few  states  as  possible,  since 
each  state  requires  entries  in  the  table  t h at  describes  the  lexical  analyzer. 

T he  m a t t er  of t he  names  of states  is  minor.  We  shall  say  t h at  two  a u t o m a ta 
are  the  same  up  to  state  names  if one  can  be  transformed  into  t he  other  by  doing 
nothing  more  t h an  changing  t he  names  of states.  Figures  3.36  and  3.63  are  not 
the  same  up  to  state  names.  However,  there  is  a  close  relationship  between  t he 

OPTIMIZATION 

OF  DFA-BASED 

PATTERN  MATCHERS 

181 

states  of each.  States  A  and  C  of  Fig.  3.36  are  actually  equivalent,  in  t he  sense 
t h at  neither  is  an  accepting  state,  and  on  any  input  they  transfer  to  t he  same 
state  —  to  B  on  input  a  and  to  C  on  input  b.  Moreover,  b o th  states  A  and  C 
behave  like  state  123  of  Fig.  3.63.  Likewise,  state  B  of  Fig.  3.36  behaves  like 
state  1234  of  Fig.  3.63,  state  D  behaves  like  state  1235,  and  state  E  behaves 
like  state  1236. 

It  turns  out  t h at  there  is  always  a  unique  (up  to  state  names)  minimum 
state  DFA  for  any  regular  language.  Moreover,  this  minimum-state  DFA  can  be 
constructed  from  any  DFA  for  the  same  language  by  grouping  sets  of equivalent 
states.  In  t he  case  of L ( ( a | b ) * a b b ),  Fig.  3.63  is  the  minimum-state  DFA,  and  it 
can  be  constructed  by  partitioning  the  states  of  Fig.  3.36  as  {A,  C}{B}{D}{E}. 
In  order  to  understand  t he  algorithm  for  creating  the  partition  of  states 
t h at  converts  any  DFA  into  its  minimum-state  equivalent  DFA,  we  need  to 
see  how  input  strings  distinguish  states  from  one  another.  We  say  t h at  string 
x  distinguishes  state  s  from  state  t  if  exactly  one  of  the  states  reached  from 
s  and  t  by  following  the  p a th  with  label  x  is  an  accepting  state.  State  s  is 
distinguishable  from  state  t  if  there  is  some  string  t h at  distinguishes  them. 

E x a m p le  3 . 3 8:  The  empty  string  distinguishes  any  accepting  state  from  any 
nonaccepting  state.  In  Fig.  3.36,  the  string  bb  distinguishes  state  A  from  state 
B,  since  bb  takes  A  to  a  nonaccepting  state  C,  but  takes  B  to  accepting  state 
E. 

• 

The  state-minimization  algorithm  works  by  partitioning  the  states  of a  DFA 
into  groups  of  states  t h at  cannot  be  distinguished.  Each  group  of  states  is  then 
merged  into  a  single  state  of  t he  minimum-state  DFA.  The  algorithm  works 
by  maintaining  a  partition,  whose  groups  are  sets  of  states  t h at  have  not  yet 
been  distinguished,  while  any  two  states  from  different  groups  are  known  to  be 
distinguishable.  When  the  partition  cannot  be  refined  further  by  breaking  any 
group  into  smaller  groups,  we  have  the  minimum-state  DFA. 

Initially,  the  partition  consists  of  two  groups:  the  accepting  states  and  the 
nonaccepting  states.  T he  fundamental  step  is  to  take  some  group  of t he  current 
partition,  say  A  =  { s i,  s2, . ..  ,  sk},  and  some  input  symbol  a,  and  see  whether 
a  can  be  used  to  distinguish  between  any  states  in  group  A.  We  examine  t he 
on  input  a,  and  if  the  states  reached  fall 
transitions  from  each  of  si,  s2,...  , 
into  two  or  more  groups  of  the  current  partition,  we  split  A  into  a  collection  of 
groups,  so  t h at  si  and Sj  are  in  the  same  group  if  and  only  if  they  go  to  the 
same  group  on  input  a.  We  repeat  this  process  of  splitting  groups,  until  for 
no  group,  and  for  no  input  symbol,  can  t he  group  be  split  further.  The  idea  is 
formalized  in  the  next  algorithm. 

A l g o r i t hm  3 . 3 9:  Minimizing  the  number  of  states  of  a  DFA. 

I N P U T:  A  DFA  D  with  set  of  states  5,  input  alphabet  S,  state  state  s0,  and 
set  of  accepting  states  F. 

O U T P U T:  A  DFA  D'  accepting  the  same  language  as  D  and  having  as  few 
states  as  possible. 

182 

CHAPTER  3. 

LEXICAL  ANALYSIS 

Why  the  State-Minimization  Algorithm  Works 

We  need  to  prove  two  things:  t h at  states  remaining  in  t he  same  group  in 
Hfinal  are  indistinguishable  by  any  string,  and  t h at  states  winding  up  in 
different  groups  are  distinguishable.  T he  first  is  an  induction  on  i  t h at 
if  after  the  ith  iteration  of  step  (2)  of  Algorithm  3 . 3 9,  s  and  t  are  in  t he 
same  group,  then  there  is  no  string  of  length  i  or  less  t h at  distinguishes 
them.  We  shall  leave  the  details  of  t he  induction  to  you. 

The  second  is  an  induction  on  i  t h at  if  states  s  and  t  are  placed  in 
different  groups  at  the  ith  iteration  of  step  ( 2 ),  then  there  is  a  string  t h at 
distinguishes  them.  T he  basis,  when  s  and  t  are  placed  in  different  groups 
of  the  initial  partition,  is  easy:  one  must  be  accepting  and  the  other  not, 
so  e  distinguishes  them.  For  t he  induction,  there  must  be  an  input  a  and 
states p  and  q  such  t h at  s  and  t  go  to  states  p  and  q,  respectively,  on  input 
a.  Moreover,  p  and  q  must  already  have  been  placed  in  different  groups. 
T h en  by  t he  inductive  hypothesis,  there  is  some  string  x  t h at  distinguishes 
p  from  q.  Therefore,  ax  distinguishes  s  from  t. 

M E T H O D: 

1.  Start  with  an  initial  partition  II  with  two  groups,  F  and  S  —  F,  the 

accepting  and  nonaccepting  states  of  D. 

2.  Apply  t he  procedure  of Fig.  3 . 64  to  construct  a new  partition  nn ew 

initially,  let  llnew  =  II; 
for  (  each  group  G  of  U  )  { 

partition  G  into  subgroups  such  t h at  two  states  s  and  t 

are  in  t he  same  subgroup  if  and  only  if  for  all 
input  symbols  a,  states  s  and  t  have  transitions  on  a 
to  states  in  the  same  group  of  Tl; 

/*  at  worst,  a  state  will  be  in  a  subgroup  by  itself  */ 
replace  G  in nn ew  by  the  set  of  all  subgroups  formed; 

} 

Figure  3.64:  Construction  of nn ew 

3.  If nn ew  =  FT,  let  llflnai  =  II  and  continue  with  step  ( 4 ).  Otherwise,  repeat 

step  (2)  with  Ilnew  in  place  of  Tl. 

4.  Choose  one  state  in  each  group  of  IIfin ai  as  the  representative  for  t h at 
group.  T he  representatives  will  be  the  states  of  t he  minimum-state  DFA 
D'.  T he  other  components  of  D'  are  constructed  as  follows: 

OPTIMIZATION 

OF 

DFA-BASED 

PATTERN  MATCHERS 

183 

Eliminating  the  Dead  State 

T he  minimization  algorithm  sometimes  produces  a  DFA  with  one  dead 
state  —  one  t h at  is  not  accepting  and  transfers  to  itself  on  each  input 
symbol.  This  state  is  technically  needed,  because  a  DFA  must  have  a 
transition  from  every  state  on  every  symbol.  However,  as  discussed  in 
Section  3.8.3,  we  often  want  to  know  when  there  is  no  longer  any  possibility 
of acceptance,  so  we  can  establish  t h at  the  proper  lexeme  has  already  been 
seen.  Thus,  we  may  wish  to  eliminate  the  dead  state  and  use  an  a u t o m a t on 
t h at  is  missing  some  transitions.  This  a u t o m a t on  has  one  fewer  state  t h an 
t he  minimum-state  DFA,  b ut  is  strictly  speaking  not  a  DFA,  because  of 
the  missing  transitions  to  the  dead  state. 

(a)  T he  state  state  of  D'  is  the  representative  of  the  group  containing 

t he  start  state  of  D. 

(b)  The  accepting  states  of  D'  are  the  representatives  of  those  groups 
t h at  contain  an  accepting  state  of  D.  Note  t h at  each  group  contains 
either  only  accepting  states,  or  only  nonaccepting  states,  because  we 
started  by  separating  those  two  classes  of  states,  and  the  procedure 
of Fig.  3.64  always  forms  new  groups  t h at  are  subgroups  of previously 
constructed  groups. 

(c)  Let  s  be  t he  representative  of  some  group  G  of  nfin ai,  and  let  t he 
transition  of  D  from  s  on  input  a  be  to  state  t.  Let  r  be  the  rep 
resentative  of  fs  group  H.  Then  in  D',  there  is  a  transition  from  s 
to  r  on  input  a.  Note  t h at  in  D,  every  state  in  group  G  must  go  to 
some  state  of  group  H  on  input  a,  or  else,  group  G  would  have  been 
split  according  to  Fig.  3.64. 

E x a m p le  3 . 4 0:  Let  us  reconsider  the  DFA  of  Fig.  3.36.  The  initial  partition 
consists  of  the  two  groups  {A,  B,  C,  D}{E},  which  are  respectively  the  nonac 
cepting  states  and  the  accepting  states.  To  construct  nne w5  the  procedure  of 
Fig.  3.64  considers  b o th  groups  and  inputs  a  and  b.  The  group  {E}  cannot  be 
split,  because  it  has  only  one  state,  so  {E}  will  remain  intact  in  nn e w-

T he  other  group  {A,  B:C,D}  can  be  split,  so  we  must  consider  t he  effect  of 
each  input  symbol.  On  input  a,  each  of  these  states  goes  to  state  B,  so  there 
is  no  way  to  distinguish  these  states  using  strings  t h at  begin  with  a.  On  input 
6,  states  A,  5,  and  C  go  to  members  of  group  {A,  B,  C,  D}:  while  s t a te  D  goes 
to  E,  a  member  of  another  group.  Thus,  in  nn e w,  group  {A,  B,C,  D}  is  split 
into 

{A,B,C}{D}{E}. 

{A,B,C}{D}, 

and  nn ew 

round 

this 

for 

is 

184 

CHAPTER  3. 

LEXICAL  ANALYSIS 

In 

the  next  round,  we  can  split  {A,B,C} 

into  {A,C}{B},  since  A  and 
C  each  go  to  a  member  of  {A,  B,  C}  on  input  b,  while  B  goes  to  a  member  of 
another  group,  {D}.  Thus,  after  the  second  round,  nn ew  =  {A,  C}{B}{D}{E}. 
For  the  third  round,  we  cannot  split  the  one  remaining  group  with  more  t h an 
one  state,  since  A  and  C  each  go  to  the  same  state  (and  therefore  to  the  same 
group)  on  each  input.  We  conclude  t h at  Ilfin ai  =  {A,  C}{B}{D}{E}. 

Now,  we  shall  construct  the  minimum-state  DFA.  It  has  four  states,  corre 
sponding  to  the  four  groups  of  Ufina\,  and  let  us  pick  A,  B,  D,  and  E  as  the 
representatives  of  these  groups.  T he  initial  state  is  A,  and  the  only  accepting 
state  is  E.  Figure  3.65  shows  the  transition  function  for  the  DFA.  For  instance, 
the  transition  from  state  E  on  input  b  is  to  A,  since  in  the  original  DFA,  E  goes 
to  C  on  input  6,  and  A  is  the  representative  of  C's  group.  For  the  same  reason, 
the  transition  on  b  from  state  A  is  to  A  itself,  while  all  other  transitions  are  as 
in  Fig.  3.36. 

• 

S T A TE 

A 
B 
D 
E 

a 

b 
A 
B 
B  D 
E 
B 
A 
B 

Figure  3.65:  Transition  table  of  minimum-state  DFA 

3.9.7 

State  Minimization  in  Lexical  Analyzers 

To  apply  the  state  minimization  procedure  to  the  DFA's  generated  in  Sec 
tion  3.8.3,  we  must  begin  Algorithm  3.39  with  the  partition  t h at  groups  to 
gether  all  states  t h at  recognize  a  particular  token,  and  also  places  in  one  group 
all  those  states  t h at  do  not  indicate  any  token.  An  example  should  make  t he 
extension  clear. 

E x a m p le  3 . 4 1:  For  the  DFA  of Fig.  3.54,  the  initial  partition  is 

{0137,7}{247}{8,58}{7}{68}{0} 

T h at  is,  states  0137  and  7  belong  together  because  neither  announces  any  token. 
States  8  and  58  belong  together  because  they  both  announce  token  a * b+.  Note 
t h at  we  have  added  a  dead  state 0,  which  we  suppose  has  transitions  to  itself 
on  inputs  a  and  b.  The  dead  state  is  also  the  target  of missing  transitions  on  a 
from  states  8,  58,  and  68. 

We  must  split  0137  from  7,  because  they  go  to  different  groups  on  input  a. 
We  also  split  8  from  58,  because  they  go  to  different  groups  on  b.  Thus,  all 
states  are  in  groups  by  themselves,  and  Fig.  3.54  is  the  minimum-state  DFA 

OPTIMIZATION 

OF  DFA-BASED 

PATTERN  MATCHERS 

185 

recognizing  its  three  tokens.  Recall  t h at  a  DFA  serving  as  a  lexical  analyzer 
will  normally  drop  the  dead  state,  while  we  treat  missing  transitions  as  a  signal 
to  end  token  recognition. 

• 

3.9.8  Trading  Time  for  Space  in  DFA  Simulation 

T he  simplest  and  fastest  way  to  represent  the  transition  function  of  a  DFA  is 
a  two-dimensional  table  indexed  by  states  and  characters.  Given  a  state  and 
next  input  character,  we  access  the  array  to  find  the  next  state  and  any  special 
action  we  must  take,  e.g.,  returning  a token  to  t he  parser.  Since  a  typical  lexical 
analyzer  has  several  hundred  states  in  its  DFA  and  involves  the  ASCII  alphabet 
of  128  input  characters,  t he  array  consumes  less  t h an  a  megabyte. 

However,  compilers  are  also  appearing  in  very  small  devices,  where  even 
a  megabyte  of  storage  may  be  too  much.  For  such  situations,  there  are  many 
methods  t h at  can  be  used  to  compact  the  transition  table.  For  instance,  we  can 
represent  each  state  by  a  list  of  transitions  —  t h at  is,  character-state  pairs  — 
ended  by  a  default  state  t h at  is  to  be  chosen  for  any  input  character  not  on  the 
list.  If  we  choose  as  the  default  the  most  frequently  occurring  next  state,  we 
can  often  reduce  the  amount  of  storage  needed  by  a  large  factor. 

There  is  a  more  subtle  d a ta  structure  t h at  allows  us  to  combine  the  speed 
of  array  access  with  the  compression  of  lists  with  defaults.  We  may  think  of 
this  structure  as  four  arrays,  as  suggested  in  Fig.  3.66.5  T he  base  array  is  used 
to  determine  the  base  location  of  the  entries  for  state  s,  which  are  located  in 
the  next  and  check  arrays.  The  default  array  is  used  to  determine  an  alternative 
base  location  if t he  check  array  tells  us  the  one  given  by  base[s]  is  invalid. 

Figure  3.66:  D a ta  structure  for  representing  transition  tables 

To  compute  nextState(s,  a),  the  transition  for  state  s  on  input  a,  we  examine 
t he  next and  check entries  in  location  I  =  base[s]+a,  where  character  o  is  t r e a t ed 
as  an  integer,  presumably  in  the  range  0  to  127.  If  check[l)  =  s,  then  this  entry 

5In  practice,  there  would  be  another  array  indexed  by  states  to  give  the  action  associated 

with  that  state,  if  any. 

186 

CHAPTER  3. 

LEXICAL  ANALYSIS 

is  valid,  and  the  next  state  for  state  s  on  input  a  is  next[l].  If  check[l]  ^  s,  then 
we  determine  another  state  t  =  defaults]  and  repeat  the  process  as  if  t  were 
the  current  state.  More  formally,  the  function  nextState  is  defined  as  follows: 

int  nextState(s,a) 

{ 

if  (  check[base[s]  +  a]  =  s  )  r e t u rn  next[base[s]  +  a]; 
nextState(default[s],a); 
e l se 

r e t u rn 

} 

The  intended  use  of  the  structure  of  Fig.  3.66  is  to  make  the  next-check 
arrays  short  by  taking  advantage  of the  similarities  among  states.  For  instance, 
state  t,  the  default  for  state  s,  might  be  t he  state  t h at  says  "we  are  working  on 
an  identifier,"  like  state  10  in  Fig.  3.14.  Perhaps  state  s  is  entered  after  seeing 
the  letters  t h,  which  are  a  prefix  of  keyword  t h en  as  well  as  potentially  being 
the  prefix  of  some  lexeme  for  an  identifier.  On  input  character  e,  we  must  go 
from  state  s  to  a  special  state  t h at  remembers  we  have  seen  t h e,  but  otherwise, 
state  s  behaves  as  t  does.  Thus,  we  set  check[base[s]  +  e]  to  s  (to  confirm  t h at 
this  entry  is  valid  for  s)  and  we  set  next[base[s]  + e]  to  the  state  t h at  remembers 
t h e.  Also,  default[s]  is  set  to  t. 

While  we  may  not  be  able  to  choose  base  values  so  t h at  no  next-check entries 
remain  unused,  experience  has  shown  t h at  t he  simple  strategy  of  assigning  base 
values  to  states  in  t u r n,  and  assigning  each  base[s]  value  t he  lowest  integer  so 
t h at  the  special  entries  for  state  s  are  not  previously  occupied  utilizes  little 
more  space  t h an  the  minimum  possible. 

3.9.9  Exercises  for  Section  3.9 

E x e r c i se  3 . 9 . 1:  Extend  the  table  of  Fig.  3.58  to  include  t he  operators  (a)  ? 
and  (b)  +  . 

E x e r c i se  3 . 9 . 2:  Use  Algorithm  3.36  to  convert  t he  regular  expressions  of  Ex 
ercise  3.7.3  directly  to  deterministic  finite  a u t o m a t a. 

!  E x e r c i se  3 . 9 . 3:  We  can  prove  t h at  two  regular  expressions  are  equivalent  by 
showing  t h at  their  minimum-state  DFA's  are  the  same  up  to  renaming  of states. 
Show  in  this  way  t h at  the  following  regular  expressions:  (a|b)*,  (a*|b*)*,  and 
((e|a)b*)*  are  all  equivalent.  Note:  You  may  have  constructed  the  DFA's  for 
these  expressions  in  response  to  Exercise  3.7.3. 

!  E x e r c i se  3 . 9 . 4:  Construct  the  minimum-state  DFA's  for  the  following  regular 

expressions: 

a)  ( a | b ) * a ( a | b ). 

b)  ( a | b ) * a ( a | b ) ( a | b ). 

c)  ( a | b ) * a ( a | b ) ( a | b ) ( a | b ). 

3.10. 

SUMMARY  OF  CHAPTER  3 

187 

Do  you  see  a  pattern? 

!!  E x e r c i se  3 . 9 . 5:  To  make  formal  the  informal  claim  of  Example  3.25,  show 

t h at  any  deterministic  finite  a u t o m a t on  for  t he  regular  expression 

( a | b ) * a ( a | b ) ( a | b ) . . . ( a | b) 

where  ( a | b)  appears  n  —  1  times  at  the  end,  must  have  at  least  2n  states.  Hint: 
Observe  t he  p a t t e rn  in  Exercise  3.9.4.  W h at  condition  regarding  the  history  of 
inputs  does  each  state  represent? 

3.10  Summary  of  Chapter  3 

•  Tokens.  T he  lexical  analyzer  scans  the  source  program  and  produces  as 
output  a  sequence  of  tokens,  which  are  normally  passed,  one  at  a  time  to 
the  parser.  Some  tokens  may  consist  only  of  a  token  name  while  others 
may  also  have  an  associated  lexical  value  t h at  gives  information  about 
t he  particular  instance  of  the  token  t h at  has  been  found  on  the  input. 

•  Lexemes.  Each  time  the  lexical  analyzer  returns  a  token  to  the  parser, 
it  has  an  associated  lexeme  —  the  sequence  of  input  characters  t h at  the 
token  represents. 

•  Buffering.  Because  it  is  often  necessary  to  scan  ahead  on  t he  input  in 
order  to  see  where  the  next  lexeme  ends,  it  is  usually  necessary  for  the 
lexical  analyzer  to  buffer  its  input.  Using  a  pair  of  buffers  cyclicly  and 
ending  each  buffer's  contents  with  a  sentinel  t h at  warns  of its  end  are  two 
techniques  t h at  accelerate  the  process  of  scanning  the  input. 

•  Patterns.  Each  token  has  a  p a t t e rn  t h at  describes  which  sequences  of 
characters  can  form  t he  lexemes  corresponding  to  t h at  token.  The  set 
of  words,  or  strings  of  characters,  t h at  match  a  given  p a t t e rn  is  called  a 
language. 

•  Regular  Expressions.  These  expressions  are  commonly  used  to  describe 
patterns.  Regular  expressions  are  built  from  single  characters,  using 
union,  concatenation,  and  t he  Kleene  closure,  or  any-number-of,  oper 
ator. 

•  Regular  Definitions.  Complex  collections  of  languages,  such  as  the  pat 
terns  t h at  describe  the  tokens  of  a  programming  language,  are  often  de 
fined  by  a  regular  definition,  which  is  a  sequence  of  statements  t h at  each 
define  one  variable  to  stand  for  some  regular  expression.  T he  regular  ex 
pression  for  one  variable  can  use  previously  defined  variables  in  its  regular 
expression. 

188 

CHAPTER  3. 

LEXICAL  ANALYSIS 

4-  Extended  Regular-Expression  Notation. 

A  number  of  additional  opera 
tors  may  appear  as  shorthands  in  regular  expressions,  to  make  it  easier 
to  express  patterns.  Examples  include  the  +  operator  (one-or-more-of), 
(zero-or-one-of),  and  character  classes  (the  union  of  the  strings  each 
? 
consisting  of  one  of  the  characters). 

•  Transition  Diagrams.  The  behavior  of  a  lexical  analyzer  can  often  be 
described  by  a  transition  diagram.  These  diagrams  have  states,  each 
of  which  represents  something  about  the  history  of  the  characters  seen 
during  the  current  search  for  a  lexeme  t h at  matches  one  of  the  possible 
patterns.  There  are  arrows,  or  transitions,  from  one  state  to  another, 
each  of  which  indicates  t he  possible  next  input  characters  t h at  cause  t he 
lexical  analyzer  to  make  t h at  change  of  state. 

•  Finite  Automata.  These  are  a  formalization  of  transition  diagrams  t h at 
include  a  designation  of  a  start  state  and  one  or  more  accepting  states, 
input  characters,  and  transitions  among 
as  well  as  the  set  of  states, 
states.  Accepting  states  indicate  t h at  the  lexeme  for  some  token  has  been 
found.  Unlike  transition  diagrams,  finite  a u t o m a ta  can  make  transitions 
on  empty  input  as  well  as  on  input  characters. 

•  Deterministic  Finite  Automata.  A  DFA 

is  a  special  kind  of  finite  au 
tomaton  t h at  has  exactly  one  transition  out  of  each  state  for  each  input 
symbol.  Also,  transitions  on  empty  input  are  disallowed.  T he  DFA  is 
easily  simulated  and  makes  a  good  implementation  of  a  lexical  analyzer, 
similar  to  a  transition  diagram. 

•  Nondeterministic  Finite  Automata.  A u t o m a ta 

t h at  are  not  DFA's  are 
called  nondeterministic.  NFA's  often  are  easier  to  design  t h an  are  DFA's. 
Another  possible  architecture  for  a  lexical  analyzer  is  to  tabulate  all  t he 
states  t h at  NFA's  for  each  of  the  possible  p a t t e r ns  can  be  in,  as  we  scan 
the  input  characters. 

•  Conversion  Among  Pattern  Representations. 

It  is  possible  to  convert  any 

regular  expression  into  an  NFA  of  about  t he  same  size,  recognizing  t he 
same  language  as  the  regular  expression  defines.  Further,  any  NFA  can 
be  converted  to  a  DFA  for  the  same  pattern,  although  in  t he  worst  case 
(never  encountered  in  common  programming  languages)  the  size  of  t he 
a u t o m a t on  can  grow  exponentially.  It  is  also  possible  to  convert  any  non-
deterministic  or  deterministic  finite  a u t o m a t on  into  a  regular  expression 
t h at  defines  the  same  language  recognized  by  the  finite  automaton. 

*  Lex.  There  is  a  family  of  software  systems,  including Lex  and Flex, 
t h at  are  lexical-analyzer  generators.  The  user  specifies  the  p a t t e r ns  for 
tokens  using  an  extended  regular-expression  notation. Lex  converts  these 
expressions  into  a  lexical  analyzer  t h at  is  essentially  a  deterministic  finite 
a u t o m a t on  t h at  recognizes  any  of  the  patterns. 

3.11.  REFERENCES  FOR  CHAPTER  3 

189 

•  Minimization  of  Finite  Automata.  For  every  DFA 

there  is  a  minimum-
state  DFA  accepting  t he  same  language.  Moreover,  t he  minimum-state 
DFA  for  a  given  language  is  unique  except  for  t he  names  given  to  t he 
various  states. 

3.11  References  for  Chapter  3 

Regular  expressions  were  first  developed  by  Kleene  in  the  1950's  [9].  Kleene  was 
interested  in  describing  the  events  t h at  could  be  represented  by  McCullough  and 
P i t t s'  [12]  finite-automaton  model  of  neural  activity.  Since  t h at  time  regular 
expressions  and  finite  a u t o m a ta  have  become  widely  used  in  computer  science. 
Regular  expressions  in  various  forms  were  used  from  the  outset  in  many 
popular  Unix utilities  such as  awk, ed, egrep, grep, lex, sed, sh,  and v i.  T he 
I E EE  1003  and  I S O / I EC  9945  standards  documents  for  t he  Portable  Operating 
System  Interface  (POSIX)  define  the  POSIX  extended  regular  expressions  which 
are  similar  to  the  original  Unix  regular  expressions  with  a  few  exceptions  such 
as  mnemonic  representations  for  character  classes.  Many  scripting  languages 
such  as  Perl,  P y t h o n,  and  Tel  have  adopted  regular  expressions  but  often  with 
incompatible  extensions. 

T he  familiar 

finite-automaton  model  and  the  minimization  of  finite  au 
t o m a t a,  as  in  Algorithm  3.39,  come  from  Huffman  [6]  and  Moore  [14].  Non-
deterministic  finite  a u t o m a ta  were  first  proposed  by  Rabin  and  Scott  [15];  t he 
subset  construction  of  Algorithm  3.20,  showing  the  equivalence  of  deterministic 
and  nondeterministic  finite  a u t o m a t a,  is  from  there. 

McNaughton  and  Yamada  [13]  first  gave  an  algorithm  to  convert  regular 
expressions  directly  to  deterministic  finite  a u t o m a t a.  Algorithm  3.36  described 
in  Section  3.9  was  first  used  by  Aho  in  creating  the  Unix  regular-expression 
matching  tool egrep.  This  algorithm  was  also  used  in  the  regular-expression 
p a t t e rn  matching  routines  in  awk  [3].  The  approach  of  using  nondeterministic 
a u t o m a ta  as  an  intermediary  is  due  Thompson  [17].  The  latter  paper  also  con 
tains  the  algorithm  for  the  direct  simulation  of nondeterministic  finite  a u t o m a ta 
(Algorithm  3.22),  which  was  used  by  Thompson  in  the  text  editor  QED. 

Lesk  developed  t he  first  version  of Lex  and  then  Lesk  and  Schmidt  created 
a  second  version  using  Algorithm  3.36  [10].  Many  variants  of Lex  have  been 
subsequently  implemented.  T he  GNU  version, Flex,  can  be  downloaded,  along 
with  documentation  at  [4].  Popular  Java  versions  of Lex  include JFlex  [7]  and 
JLex  [8]. 

T he  K MP  algorithm,  discussed  in  the  exercises  to  Section  3.4  just  prior  to 
Exercise  3.4.3,  is  from  [11].  Its  generalization  to  many  keywords  appears  in  [2] 
and  was  used  by  Aho  in  t he  first  implementation  of  the  Unix  utility  f grep. 

The  theory  of  finite  a u t o m a ta  and  regular  expressions  is  covered  in  [5].  A 

survey  of  string-matching  techniques  is  in  [1]. 

1.  Aho,  A.  V.,  "Algorithms  for  finding  patterns  in  strings,"  in  Handbook  of 
Theoretical  Computer  Science  (J.  van  Leeuwen,  ed.),  Vol.  A,  Ch.  5,  M IT 

190 

CHAPTER  3. 

LEXICAL  ANALYSIS 

Press,  Cambridge,  1990. 

2.  Aho,  A.  V.  and  M.  J.  Corasick,  "Efficient  string  matching:  an  aid  to 

bibliographic  search,"  Comm.  ACM  18:6  (1975),  pp.  333-340. 

3.  Aho,  A.  V.,  B.  W.  Kernighan,  and  P.  J.  Weinberger,  The  AWK Program 

ming Language,  Addison-Wesley,  Boston,  MA,  1988. 

4.  F l ex  home  page  h t t p : / / w w w . g n u . o r g / s o f t w a r e / f l e x /,  Free  Software 

Foundation. 

5.  Hopcroft,  J.  E.,  R.  Motwani,  and  J.  D.  Ullman,  Introduction  to  Automata 
Theory,  Languages,  and  Computation,  Addison-Wesley,  Boston MA,  2006. 

6.  Huffman,  D.  A.,  "The  synthesis  of sequential  machines,"  J.  Franklin  Inst. 

2 57  (1954),  pp.  3-4,  161,  190,  275-303. 

7.  J F l ex  home  page  h t t p : / / j f l e x . d e/  . 

8.  h t t p : / / w w w . c s . p r i n c e t o n . e d u / ~ a p p e l / m o d e r n / j a v a / J L ex 

. 

9.  Kleene,  S.  C,  "Representation  of  events  in  nerve  nets,"  in  [16],  pp.  3-40. 

10.  Lesk,  M.  E.,  "Lex  -  a  lexical  analyzer  generator,"  Computing  Science 
Tech.  Report  39,  Bell  Laboratories,  Murray  Hill,  NJ,  1975.  A  similar 
document  with  t he  same  title  but  with  E.  Schmidt  as  a  coauthor,  appears 
in Vol.  2  of t he  Unix Programmer's  Manual,  Bell laboratories,  Murray Hill 
NJ,  1975;  see  h t t p : / / d i n o s a u r . c o m p i l e r t o o l s . n e t / l e x / i n d e x . h t m l. 

11.  Knuth,  D.  E.,  J.  H.  Morris,  and  V.  R.  P r a t t,  "Fast  p a t t e rn  matching  in 

strings,"  SIAM  J.  Computing  6:2  (1977),  p p.  323-350. 

12.  McCullough,  W.  S.  and  W.  P i t t s,  "A  logical  calculus  of the  ideas  imma 

nent  in  nervous  activity,"  Bull.  Math.  Biophysics  5  (1943),  p p.  115-133. 

13.  McNaughton,  R.  and  H.  Yamada,  "Regular  expressions  and  state  graphs 
for  a u t o m a t a ,"  IRE  Trans,  on  Electronic  Computers  E C- 9:1  (1960),  p p. 
38-47. 

14.  Moore,  E.  F.,  "Gedanken  experiments  on  sequential  machines,"  in  [16], 

pp.  129-153. 

15.  Rabin,  M.  O.  and  D.  Scott,  "Finite  a u t o m a ta  and  their  decision  prob 

lems,"  IBM  J.  Res.  and  Deuel.  3:2  (1959),  p p.  114-125. 

16.  Shannon,  C.  and  J.  McCarthy  (eds.),  Automata  Studies,  Princeton  Univ. 

Press,  1956. 

17.  Thompson,  K.,  "Regular  expression  search  algorithm,"  Comm.  ACM  11:6 

(1968),  pp.  419-422. 

Chapter  4 

Syntax  Analysis 

This  chapter  is  devoted  to  parsing  methods  t h at  are  typically  used  in  compilers. 
We  first  present  t he  basic  concepts,  then  techniques  suitable  for  hand  implemen 
tation,  and  finally  algorithms  t h at  have  been  used  in  a u t o m a t ed  tools.  Since 
programs  may  contain  syntactic  errors,  we  discuss  extensions  of  the  parsing 
methods  for  recovery  from  common  errors. 

By  design,  every  programming  language  has  precise  rules  t h at  prescribe  the 
syntactic  structure  of  well-formed  programs.  In  C,  for  example,  a  program  is 
made  up  of functions,  a  function  out  of declarations  and  statements,  a  statement 
out  of expressions,  and  so  on.  T he  syntax  of  programming  language  constructs 
can  be  specified  by  context-free  grammars  or  B NF  (Backus-Naur  Form)  nota 
tion,  introduced  in  Section  2.2.  G r a m m a rs  offer  significant  benefits  for  b o th 
language  designers  and  compiler  writers. 

•  A  g r a m m ar  gives  a  precise,  yet  easy-to-understand,  syntactic  specification 

of  a  programming  language. 

•  From  certain  classes  of grammars,  we  can  construct  automatically  an  effi 
cient  parser  t h at  determines  the  syntactic  structure  of  a  source  program. 
As  a  side  benefit,  t he  parser-construction  process  can  reveal  syntactic 
ambiguities  and  trouble  spots  t h at  might  have  slipped  through  the  initial 
design  phase  of  a  language. 

•  T he  structure  imparted  to  a  language  by  a  properly  designed  grammar 
is  useful  for  translating  source  programs  into  correct  object  code  and  for 
detecting  errors. 

•  A  grammar  allows  a  language  to  be  evolved  or  developed  iteratively,  by 
adding  new  constructs  to  perform  new  tasks.  These  new  constructs  can 
be  integrated  more  easily  into  an  implementation  t h at  follows  t he  gram 
matical  structure  of  the  language. 

191 

192 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

4.1 

Introduction 

In  this  section,  we  examine  the  way  the  parser  fits  into  a  typical  compiler.  We 
then  look  at  typical  grammars  for  arithmetic  expressions.  G r a m m a rs  for  ex 
pressions  suffice  for  illustrating  the  essence  of  parsing,  since  parsing  techniques 
for  expressions  carry  over  to  most  programming  constructs.  This  section  ends 
with  a  discussion  of  error  handling,  since  t he  parser  must  respond  gracefully  to 
finding  t h at  its  input  cannot  be  generated  by  its  grammar. 

4.1.1  The  Role  of  the  Parser 

In  our  compiler  model,  the  parser  obtains  a  string  of  tokens  from  t he  lexical 
analyzer,  as  shown  in  Fig.  4.1,  and  verifies  t h at  the  string  of  token  names 
can  be  generated  by  the  grammar  for  the  source  language.  We  expect  the 
parser  to  report  any  syntax  errors  in  an  intelligible  fashion  and  to  recover  from 
commonly  occurring  errors  to  continue  processing  t he  remainder  of the  program. 
Conceptually,  for  well-formed  programs,  t he  parser  constructs  a  parse  tree  and 
passes  it  to  the  rest  of  t he  compiler  for  further  processing.  In  fact,  t he  parse 
tree  need  not  be  constructed  explicitly,  since  checking  and  translation  actions 
can  be  interspersed  with  parsing,  as  we  shall  see.  Thus,  t he  parser  and  t he  rest 
of  the  front  end  could  well  be  implemented  by  a  single  module. 

source 
program 

Lexical 
Analyzer 

token 

get  next 
token 

Parser 

|  Rest  of 
|  Front  End 

intermediate 
representation 

Symbol 
Table 

Figure  4.1:  Position  of  parser  in  compiler  model 

There  are  three  general  types  of parsers  for  grammars:  universal,  top-down, 
and  bottom-up.  Universal  parsing  methods  such  as  t he  Cocke-Younger-Kasami 
algorithm  and  Earley's  algorithm  can  parse  any  grammar  (see  t he  bibliographic 
notes).  These  general  methods  are,  however,  too  inefficient  to  use  in  production 
compilers. 

The  methods  commonly  used  in  compilers  can  be  classified  as  being  either 
top-down  or  b o t t o m - u p.  As  implied  by  their  names,  top-down  methods  build 
parse  trees  from  the  top  (root)  to  the  b o t t om  (leaves),  while  b o t t o m - up  methods 
start  from  t he  leaves  and  work  their  way  up  to  t he  root. 
In  either  case,  t he 
input  to  t he  parser  is  scanned  from  left  to  right,  one  symbol  at  a  time. 

4.1. 

INTRODUCTION 

193 

The  most  efficient  top-down  and  bottom-up  methods  work  only  for  sub 
classes  of grammars,  but  several  of these  classes,  particularly,  LL  and  LR  gram 
mars,  are  expressive  enough  to  describe  most  of  t he  syntactic  constructs  in 
modern  programming  languages.  Parsers  implemented  by  hand  often  use  LL 
grammars;  for  example,  t he  predictive-parsing  approach  of  Section  2.4.2  works 
for  LL  grammars.  Parsers  for  t he  larger  class  of  LR  grammars  are  usually 
constructed  using  automated  tools. 

In  this  chapter,  we  assume  t h at  t he  output  of  the  parser  is  some  represent 
ation  of  t he  parse  tree  for  t he  stream  of  tokens  t h at  comes  from  the  lexical 
analyzer. 
In  practice,  there  are  a  number  of  tasks  t h at  might  be  conducted 
during  parsing,  such  as  collecting  information  about  various  tokens  into  the 
symbol  table,  performing  type  checking  and  other  kinds  of  semantic  analysis, 
and  generating  intermediate  code.  We  have  lumped  all  of  these  activities  into 
t he  "rest  of  the  front  end"  box  in  Fig.  4.1.  These  activities  will  be  covered  in 
detail  in  subsequent  chapters. 

4.1.2  Representative  Grammars 

Some  of  the  grammars  t h at  will  be  examined  in  this  chapter  are  presented  here 
for  ease  of reference.  Constructs  t h at  begin  with  keywords  like  w h i le  or  i n t,  are 
relatively  easy  to  parse,  because  the  keyword  guides  the  choice  of the  grammar 
production  t h at  must  be  applied  to  match  the  input.  We  therefore  concentrate 
on  expressions,  which  present  more  of  challenge,  because  of  the  associativity 
and  precedence  of  operators. 

Associativity  and  precedence  are  captured  in  the  following  grammar,  which 
is  similar  to  ones  used  in  Chapter  2  for  describing  expressions,  terms,  and 
factors.  E  represents  expressions  consisting  of  terms  separated  by  +  signs,  T 
represents  terms  consisting  of  factors  separated  by  *  signs,  and  F  represents 
factors  t h at  can  be  either  parenthesized  expressions  or  identifiers: 

E 
T 
F 

-)> 

E  +  T 
T  *  F 
| 
(E) 

|  T 
|  F 
id 

(4.1) 

Expression  g r a m m ar  (4.1)  belongs  to  the  class  of LR  grammars  t h at  are  suitable 
for  bottom-up  parsing.  This  g r a m m ar  can  be  adapted  to  handle  additional 
operators  and  additional  levels  of  precedence.  However,  it  cannot  be  used  for 
top-down  parsing  because  it  is  left  recursive. 

T he  following  non-left-recursive  variant  of the  expression  grammar  (4.1)  will 

be  used  for  top-down  parsing: 

E 
E' 
T 
V 
F 

T  E' 
+  T  E' 
FT 
*  F  T' 
(  E  ) 

| 

| 

e 

| 

e 
id 

(4.2) 

194 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

The  following  g r a m m ar  treats  +  and  *  alike,  so  it  is  useful  for  illustrating 
techniques  for  handling  ambiguities  during  parsing: 

E 

-> 

E  +  E\  E * E \ ( E) 

\ 

id 

(4.3) 

Here,  E  represents  expressions  of  all  types.  G r a m m ar  (4.3)  permits  more  t h an 
one  parse  tree  for  expressions  like  a  +  b*c. 

4.1.3 

Syntax  Error  Handling 

The  remainder  of  this  section  considers  the  n a t u re  of  syntactic  errors  and  gen 
eral  strategies  for  error  recovery.  Two  of these  strategies,  called  panic-mode  and 
phrase-level  recovery,  are  discussed  in  more  detail  in  connection  with  specific 
parsing  methods. 

If a  compiler  had  to  process  only  correct  programs,  its  design  and  implemen 
tation  would  be  simplified  greatly.  However,  a  compiler  is  expected  to  assist 
the  programmer  in  locating  and  tracking  down  errors  t h at  inevitably  creep  into 
programs,  despite  the  programmer's  best  efforts.  Strikingly,  few  languages  have 
been  designed  with  error  handling  in  mind,  even  though  errors  are  so  common 
place.  Our  civilization  would  be  radically  different  if  spoken  languages  had 
the  same  requirements  for  syntactic  accuracy  as  computer  languages.  Most 
programming  language  specifications  do  not  describe  how  a  compiler  should 
respond  to  errors;  error  handling  is  left  to  t he  compiler  designer.  Planning  the 
error  handling  right  from  t he  start  can  b o th  simplify  the  structure  of a  compiler 
and  improve  its  handling  of  errors. 

Common  programming  errors  can  occur  at  many  different  levels. 

•  Lexical  errors  include  misspellings  of identifiers,  keywords,  or  operators  — 
e.g.,  t he  use  of  an  identifier  e l i p s e S i ze  instead  of  e l l i p s e S i ze  —  and 
missing  quotes  around  text  intended  as  a  string. 

•  Syntactic  errors  include  misplaced  semicolons  or  extra  or  missing  braces; 
t h at  is,  " {"  or  " } ."  As  another  example,  in  C  or  Java,  t he  appearance 
of  a  c a se  statement  without  an  enclosing  s w i t ch  is  a  syntactic  error 
(however,  this  situation  is  usually  allowed  by  t he  parser  and  caught  later 
in  the  processing,  as  t he  compiler  a t t e m p ts  to  generate  code). 

•  Semantic  errors  include  type  mismatches  between  operators  and  operands. 
An  example  is  a  r e t u rn  statement  in  a  Java  method  with  result  type  v o i d. 

•  Logical  errors  can  be  anything  from  incorrect  reasoning  on  t he  part  of 
the  programmer  to  t he  use  in  a  C  program  of  t he  assignment  operator  = 
instead  of  the  comparison  operator  ==.  T he  program  containing  =  may 
be  well  formed;  however,  it  may  not  reflect  the  programmer's  intent. 

T he  precision  of parsing  methods  allows  syntactic  errors  to  be  detected  very 
efficiently.  Several  parsing  methods,  such  as  the  LL  and  LR  methods,  detect 

4.1. 

INTRODUCTION 

195 

an  error  as  soon  as  possible;  t h at  is,  when  t he  stream  of tokens  from  the  lexical 
analyzer  cannot  be  parsed  further  according  to  the  grammar  for  the  language. 
More  precisely,  they  have  the  viable-prefix  property,  meaning  t h at  they  detect 
t h at  an  error  has  occurred  as  soon  as  they  see  a  prefix  of  the  input  t h at  cannot 
be  completed  to  form  a  string  in  the  language. 

Another  reason  for  emphasizing  error  recovery  during  parsing  is  t h at  many 
errors  appear  syntactic,  whatever  their  cause,  and  are  exposed  when  parsing 
cannot  continue.  A  few  semantic  errors,  such  as  type  mismatches,  can  also  be 
detected  efficiently;  however,  accurate  detection  of  semantic  and  logical  errors 
at  compile  time  is  in  general  a  difficult  task. 

T he  error  handler  in  a  parser  has  goals  t h at  are  simple  to  state  but  chal 

lenging  to  realize: 

•  Report  the  presence  of  errors  clearly  and  accurately. 

•  Recover  from  each  error  quickly  enough  to  detect  subsequent  errors. 

•  Add  minimal  overhead  to  the  processing  of  correct  programs. 

Fortunately,  common  errors  are  simple  ones,  and  a  relatively  straightforward 

error-handling  mechanism  often  suffices. 

How  should  an  error  handler  report  the  presence  of  an  error?  At  t he  very 
least,  it  must  report  the  place  in  the  source  program  where  an  error  is  detected, 
because  there  is  a good  chance  t h at  the  actual  error  occurred  within  the  previous 
few  tokens.  A  common  strategy  is  to  print  the  offending  line  with  a  pointer  to 
t he  position  at  which  an  error  is  detected. 

4.1.4  Error-Recovery  Strategies 

Once  an  error  is  detected,  how  should  t he  parser  recover?  Although  no  strategy 
has  proven  itself  universally  acceptable,  a  few  methods  have  broad  applicabil 
ity.  T he  simplest  approach  is  for  the  parser  to  quit  with  an  informative  error 
message  when  it  detects  the  first  error.  Additional  errors  are  often  uncovered 
if  t he  parser  can  restore  itself  to  a  state  where  processing  of  the  input  can  con 
tinue  with  reasonable  hopes  t h at  the  further  processing  will  provide  meaningful 
diagnostic  information. 
If  errors  pile  up,  it  is  better  for  the  compiler  to  give 
up  after  exceeding  some  error  limit  t h an  to  produce  an  annoying  avalanche  of 
"spurious"  errors. 

The  balance  of  this  section  is  devoted  to  the  following  recovery  strategies: 

panic-mode,  phrase-level,  error-productions,  and  global-correction. 

P a n i c - M o de  R e c o v e ry 

W i th  this  method,  on  discovering  an  error,  the  parser  discards  input  symbols 
one  at  a  time  until  one  of  a  designated  set  of  synchronizing  tokens  is  found. 
T he  synchronizing  tokens  are  usually  delimiters,  such  as  semicolon  or  },  whose 
role  in  the  source  program  is  clear  and  unambiguous.  T he  compiler  designer 

196 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

must  select  the  synchronizing  tokens  appropriate  for  the  source  language.  While 
panic-mode  correction  often  skips  a  considerable  amount  of input  without  check 
ing  it  for  additional  errors,  it  has  the  advantage  of  simplicity,  and,  unlike  some 
methods  to  be  considered  later,  is  guaranteed  not  to  go  into  an  infinite  loop. 

P h r a s e - L e v el  R e c o v e ry 

On  discovering  an  error,  a  parser  may  perform  local  correction  on  the  remaining 
input;  t h at  is,  it  may  replace  a  prefix  of t he  remaining  input  by  some  string  t h at 
allows  the  parser  to  continue.  A  typical  local  correction  is  to  replace  a  comma 
by  a  semicolon,  delete  an  extraneous  semicolon,  or  insert  a  missing  semicolon. 
T he  choice  of  t he  local  correction  is  left  to  t he  compiler  designer.  Of  course, 
we  must  be  careful  to  choose  replacements  t h at  do  not  lead  to  infinite  loops,  as 
would  be  the  case,  for  example,  if  we  always  inserted  something  on  t he  input 
ahead  of  the  current  input  symbol. 

Phrase-level  replacement  has  been  used  in  several  error-repairing  compilers, 

as  it  can  correct  any  input  string.  Its  major  drawback  is  the  difficulty  it  has  in 
coping  with  situations  in  which  the  actual  error  has  occurred  before  the  point 
of  detection. 

Error  P r o d u c t i o ns 

By  anticipating  common  errors  t h at  might  be  encountered,  we  can  augment  the 
grammar  for  the  language  at  hand  with  productions  t h at  generate  t he  erroneous 
constructs.  A  parser  constructed  from  a  g r a m m ar  augmented  by  these  error 
productions  detects  t he  anticipated  errors  when  an  error  production  is  used 
during  parsing.  T he  parser  can  then  generate  appropriate  error  diagnostics 
a b o ut  t he  erroneous  construct  t h at  has  been  recognized  in  t he  input. 

G l o b al  C o r r e c t i on 

Ideally,  we  would  like  a compiler to make  as  few  changes  as  possible  in  processing 
an  incorrect  input  string.  There  are  algorithms  for  choosing  a  minimal  sequence 
of  changes  to  obtain  a  globally  least-cost  correction.  Given  an  incorrect  input 
string  x  and  grammar  G,  these  algorithms  will  find  a  parse  tree  for  a  related 
string  y,  such  t h at  t he  number  of  insertions,  deletions,  and  changes  of  tokens 
required  to  transform  x  into  y  is  as  small  as  possible.  Unfortunately,  these 
methods  are  in  general  too  costly  to  implement  in  terms  of  time  and  space,  so 
these  techniques  are  currently  only  of  theoretical  interest. 

Do  note  t h at  a  closest  correct  program  may  not  be  what  the  programmer had 
in  mind.  Nevertheless,  the  notion  of  least-cost  correction  provides  a  yardstick 
for  evaluating  error-recovery  techniques,  and  has  been  used  for  finding  optimal 
replacement  strings  for  phrase-level  recovery. 

4.2. 

CONTEXT-FREE  GRAMMARS 

197 

4.2  Context-Free  Grammars 

G r a m m a rs  were  introduced  in  Section  2.2  to  systematically  describe  the  syntax 
of  programming  language  constructs  like  expressions  and  statements.  Using 
a  syntactic  variable  stmt  to  denote  statements  and  variable  expr  to  denote 
expressions,  the  production 

stmt  —> 

if  (  expr  )  stmt  e l se  stmt 

(4.4) 

specifies  the  structure  of this  form  of  conditional  statement.  Other  productions 
then  define  precisely  what  an  expr  is  and  what  else  a  stmt  can  be. 

This  section  reviews  the  definition  of a  context-free  grammar  and  introduces 
terminology  for  talking  about  parsing.  In  particular,  t he  notion  of  derivations 
is  very  helpful  for  discussing  the  order  in  which  productions  are  applied  during 
parsing. 

4.2.1  The  Formal  Definition  of  a  Context-Free  Grammar 

From  Section  2.2,  a  context-free  grammar  (grammar  for  short)  consists  of  ter 
minals,  nonterminals,  a  start  symbol,  and  productions. 

1.  Terminals  are  the  basic  symbols  from  which  strings  are  formed.  T he  t e rm 
"token  name"  is  a  synonym  for  "terminal"  and  frequently  we  will  use  the 
word  "token"  for  terminal  when  it  is  clear  t h at  we  are  talking  about  just 
the  token  name.  We  assume  t h at  t he  terminals  are  t he  first  components 
of  t he  tokens  output  by  the  lexical  analyzer.  In  (4.4),  the  terminals  are 
t he  keywords  if  and  e l se  and  the  symbols  " ("  and  " ) ." 

2.  Nonterminals  are  syntactic  variables  t h at  denote  sets  of  strings.  In  (4.4), 
stmt  and  expr  are  nonterminals.  T he  sets  of  strings  denoted  by  nontermi 
nals  help  define  the  language  generated  by  the  grammar.  Nonterminals 
impose  a  hierarchical  structure  on  the  language  t h at  is  key  to  syntax 
analysis  and  translation. 

3.  In  a  grammar,  one  nonterminal  is  distinguished  as  the  start  symbol,  and 
the  set  of  strings  it  denotes  is  the  language  generated  by  t he  grammar. 
Conventionally,  t he  productions  for  t he  start  symbol  are  listed  first. 

4.  T he  productions  of  a  grammar  specify  the  manner  in  which  the  termi 

nals  and  nonterminals  can  be  combined  to  form  strings.  Each  production 
consists  of: 

(a)  A  nonterminal  called  t he  head  or  left  side  of  the  production;  this 

production  defines  some  of  the  strings  denoted  by  t he  head. 

(b)  T he  symbol  -K  Sometimes  :  : =  has  been  used  in  place  of the  arrow. 

(c)  A  body  or  right  side  consisting  of  zero  or  more  terminals  and  non 
terminals.  T he  components  of  the  body  describe  one  way  in  which 
strings  of  the  nonterminal  at  the  head  can  be  constructed. 

198 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

E x a m p le  4 . 5:  The  grammar  in  Fig.  4.2  defines  simple  arithmetic  expressions. 
In  this  grammar,  the  terminal  symbols  are 

id  +  -  * 

/ 

( 

) 

T he nonterminal symbols  are  expression,  term a nd factor,  a nd  expression is t he 
start  symbol 

• 

expression 
expression 
expression 
term 
term 
term 
factor 
factor 

-> 

-> 
-> 
-» 
-» 

-> 

expression  +  term 
expression  -  term 
term 
term  *  factor 
term  /  factor 
factor 
(  expression  ) 
id 

Figure  4.2:  G r a m m ar  for  simple  arithmetic  expressions 

4.2.2  Notational  Conventions 

To  avoid  always  having  to  state  t h at  "these  are  t he  terminals,"  "these  are  the 
nonterminals,"  and  so  on,  the  following  notational  conventions  for  grammars 
will  be  used  throughout  t he  remainder  of  this  book. 

1.  These  symbols  are  terminals: 

(a)  Lowercase  letters  early  in  the  alphabet,  such  as  a,  b,  c. 

(b)  Operator  symbols  such  as  +,  *,  and  so  on. 

(c)  Punctuation  symbols  such  as  parentheses,  comma,  and  so  on. 

(d)  The  digits  0 , 1 , . ..  , 9. 

(e)  Boldface  strings  such  as  id  or  if,  each  of  which  represents  a  single 

terminal  symbol. 

2.  These  symbols  are  nonterminals: 

(a)  Uppercase  letters  early  in  the  alphabet,  such  as  A,  B,  C. 

(b)  The  letter  S,  which,  when  it  appears,  is  usually  t he  start  symbol. 

(c)  Lowercase,  italic  names  such  as  expr or  stmt. 

(d)  When  discussing  programming  constructs,  uppercase  letters  may  be 
used  to  represent  nonterminals  for  the  constructs.  For  example,  non 
terminals  for  expressions,  terms,  and  factors  are  often  represented  by 
E,  T,  and  F,  respectively. 

4.2. 

CONTEXT-FREE  GRAMMARS 

199 

3.  Uppercase  letters  late  in  the  alphabet,  such  as  X,  7,  Z,  represent  grammar 

symbols;  t h at  is,  either  nonterminals  or  terminals. 

4.  Lowercase  letters  late  in  t he  alphabet,  chiefly  u,v,...,  z,  represent  (pos 

sibly  empty)  strings  of  terminals. 

5.  Lowercase  Greek  letters,  a,  0,  7  for  example,  represent  (possibly  empty) 
strings  of  grammar  symbols.  Thus,  a  generic  production  can  be  written 
as  A  ->•  a,  where  A  is  the  head  and  a  the  body. 

6.  A  set  of  productions  A  -»  ai,  A  -»•  a2,... 

A  (call  t h em  A-productions),  may  be  written  A  ->•  a\  |  0:2  |  •  •  • 
a i,  « 25  •  •  •  ?  c K fc  t he  alternatives  for  A. 

,  A  ->  ak  with  a  common  head 
|  0 ^.  Call 

7.  Unless  stated  otherwise,  t he  head  of  the  first  production  is  the  start  sym 

bol. 

E x a m p le  4 . 6:  Using  these  conventions,  t he  grammar  of  Example  4.5  can  be 
rewritten  concisely  as 

E 
T 
F 

E  +  T\  E  —  T \T 
\  F 
T  *  F 
I 
(E) 

\  T  /  F 
id 

-> 
-» 

The  notational  conventions  tell  us  t h at  E,  T,  and  F  are  nonterminals,  with  E 
the  start  symbol.  T he  remaining  symbols  are  terminals. 

• 

4.2.3  Derivations 

The  construction  of  a  parse  tree  can  be  made  precise  by  taking  a  derivational 
view,  in  which  productions  are  treated  as  rewriting  rules.  Beginning  with  the 
start  symbol,  each  rewriting  step  replaces  a nonterminal  by  the  body  of one  of its 
productions.  This  derivational  view  corresponds  to  the  top-down  construction 
of a parse tree,  but  t he  precision  afforded  by  derivations  will  be  especially  helpful 
when  bottom-up  parsing  is  discussed.  As  we  shall  see,  bottom-up  parsing  is 
related  to  a  class  of derivations  known  as  "rightmost"  derivations,  in  which  the 
rightmost  nonterminal  is  rewritten  at  each  step. 

For  example,  consider  the  following  grammar,  with  a  single  nonterminal  E, 

which  adds  a  production  E  ->•  —  E  to  the  grammar  (4.3): 

E 

->  E  +  E  I  E  *  E  I 

-  E 

\ 

(E) 

\ 

id 

(4.7) 

The  production  E  ->•  -  E  signifies  t h at  if  E  denotes  an  expression,  then  -  E 
must  also  denote  an  expression.  The  replacement  of  a  single  E  by  -  E  will  be 
described  by  writing 

E 

-E 

200 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

which  is  read,  "E  derives  —E."  T he  production  E  ->  (  E  )  can  be  applied 
to  replace  any  instance  of  E  in  any  string  of  g r a m m ar  symbols  by  (E),  e.g., 
E*  E 
(E)  *E  or  E*E=>E*  (E).  We  can  take  a  single  E  and  repeatedly 
apply  productions  in  any  order  to  get  a  sequence  of replacements.  For  example, 

E=>-E=>-(E) 

=> 

- ( i d) 

We  call  such  a  sequence  of  replacements  a  derivation  of  - ( i d)  from  E.  This 
derivation  provides  a  proof  t h at  the  string  - ( i d)  is  one  particular  instance  of 
an  expression. 

For  a  general  definition  of derivation,  consider  a  nonterminal  A  in  the  middle 
of  a  sequence  of  grammar  symbols,  as  in  aA(3,  w h e r e .a  and  (3  are  arbitrary 
strings  of  grammar  symbols.  Suppose  A  ->•  7  is  a  production.  Then,  we  write 
means,  "derives  in  one  step."  When  a  sequence 
aAj3 
of  derivation  steps  a\  =>•  a2  =>  •  •  • 
an  rewrites  a±  to  an,  we  say  at  derives 
an.  Often,  we  wish  to  say,  "derives  in  zero  or  more  steps."  For  this  purpose, 
we  can  use  the  symbol 

aj(3.  T he  symbol 

.  Thus, 

1.  a  =k-  a,  for  any  string  a,  and 

2.  If a  =^  (3  and  (3 

7,  then  cu  =4>  7. 

Likewise,  ^  means,  "derives  in  one  or  more  steps." 

If  S  =$>  a,  where  S  is  the  start  symbol  of  a  grammar  G,  we  say  t h at  a  is  a 
sentential  form  of  G.  Note  t h at  a  sentential  form  may  contain  both  terminals 
and  nonterminals,  and  may  be  empty.  A  sentence  of G  is  a  sentential  form  with 
no  nonterminals.  The  language  generated  by  a  g r a m m ar  is  its  set  of  sentences. 
Thus,  a  string  of  terminals  w  is  in  L(G),  t he  language  generated  by  G,  if  and 
only  if  w  is  a  sentence  of  G  (or  S  4>  w).  A  language  t h at  can  be  generated  by 
a  g r a m m ar  is  said  to  be  a  context-free  language.  If  two  grammars  generate  t he 
same  language,  the  grammars  are  said  to  be  equivalent. 

T he  string  - ( id  +  id)  is  a  sentence  of  grammar  (4.7)  because  there  is  a 

derivation 

E 

—E  =>•  —(E) 

-{E  +  E) 

- ( id  +  E) 

- ( id  +  id) 

(4.8) 

T he  strings  E,  -E,  -(E),... 
mar.  We  write  E  ^ 
from  E. 

,  - (id  +  id)  are  all  sentential  forms  of  this  gram 
- ( id  +  id)  to  indicate  t h at  - ( id  +  id)  can  be  derived 

At  each  step  in  a  derivation,  there  are  two  choices  to  be  made.  We  need 
to  choose  which  nonterminal  to  replace,  and  having  made  this  choice,  we  must 
pick  a  production  with  t h at  nonterminal  as  head.  For  example,  the  following 
alternative  derivation  of  - ( id  +  id)  differs  from  derivation  (4.8)  in  t he  last  two 
steps: 

E  =>•  —E 

-(E) 

-(E  +  E) 

-(E  +  id) 

- ( id  +  id) 

(4.9) 

4.2. 

CONTEXT-FREE  GRAMMARS 

201 

Each  nonterminal  is  replaced  by  the  same  body  in  t he  two  derivations,  but  t he 
order  of  replacements  is  different. 

To  understand  how  parsers  work,  we  shall  consider  derivations  in  which  the 

nonterminal  to  be  replaced  at  each  step  is  chosen  as  follows: 

1.  In  leftmost  derivations,  the  leftmost  nonterminal  in  each  sentential  is  al 
is  a  step  in  which  t he  leftmost  nonterminal  in  a  is 

ways  chosen.  If  a 
replaced,  we  write  a 

0. 

Im 

2.  In  rightmost  derivations,  the  rightmost  nonterminal  is  always  chosen;  we 

write  a 

(3  in  this  case. 

rm 

Derivation  (4.8)  is  leftmost,  so  it  can  be  rewritten  as 

E  =>•  —E 

Im 

Im 

-{E)=> 
Im 

-{E  +  E)=> 
Im 

- ( id  +  E)  => 
Im 

- ( id  +  id) 

Note  t h at  (4.9)  is  a  rightmost  derivation. 

Using  our  notational  conventions,  every  leftmost  step  can  be  written  as 
wAj  =>•  w8y,  where  w  consists  of  terminals  only,  A  ->  S  is  the  production 

Im 

applied,  and  7  is  a  string  of  grammar  symbols.  To  emphasize  t h at  a  derives  (3 
a,  then  we  say  t h at  a;  is  a 
by  a  leftmost  derivation,  we  write  a  =>  (3.  If  S 

left-sentential  form  of  t he  grammar  at  hand. 

Im 

Im 

Analogous  definitions  hold  for  rightmost  derivations.  Rightmost  derivations 

are  sometimes  called  canonical  derivations. 

4.2.4  Parse  Trees  and  Derivations 

A  parse  tree  is  a  graphical  representation  of  a  derivation  t h at  filters  out  the 
order  in  which  productions  are  applied  to  replace  nonterminals.  Each  interior 
node  of  a  parse  tree  represents  the  application  of  a  production.  The  interior 
node  is  labeled  with  t he  nonterminal  A  in  t he  head  of  the  production; 
the 
children  of  the  node  are  labeled,  from  left  to  right,  by  t he  symbols  in  t he  body 
of  the  production  by  which  this  A  was  replaced  during  t he  derivation. 

For  example,  the  parse  tree  for  - ( id  +  id)  in  Fig.  4.3,  results  from  t he 

derivation  (4.8)  as  well  as  derivation  (4.9). 

T he  leaves  of a  parse  tree  are  labeled  by  nonterminals  or  terminals  and,  read 
from  left  to  right,  constitute  a  sentential  form,  called  the  yield  or  frontier  of  the 
tree. 

To  see  t he  relationship  between  derivations  and  parse  trees,  consider  any 
derivation  ai 
an,  where  a±  is  a  single  nonterminal  A.  For  each 
sentential  form  at  in  the  derivation,  we  can  construct  a  parse  tree  whose  yield 
is  ai.  The  process  is  an  induction  on  i. 

•  •  • 

a2 

B A S I S:  T he  tree  for  a\  =  A  is  a  single  node  labeled  A. 

202 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

E 

\ 
/ 

E 

id 

E 

E 

+ 

\ 

E 

id 

Figure  4.3:  Parse  tree  for  - ( id  +  id) 

I N D U C T I O N:  Suppose  we  already  have  constructed  a  parse  tree  with  yield 
a.i-1  =  X1X2  •  •  - Xk  (note  t h at  according  to  our  notational  conventions,  each 
grammar  symbol  X{  is  either  a  nonterminal  or  a  terminal).  Suppose  on  is 
derived  from  q j j _i  by  replacing  Xj,  a  nonterminal,  by  (3  =  Y\Y2  •  •  •  Ym.  T h at 
is,  at  the  ith.  step  of  t he  derivation,  production  Xj  —>  /?  is  applied  to  ai-i  to 
derive 

=  X\X2  •  •  •  Xj-IJ3XJ+\  •  •  •  Xk-

To  model  this  step  of  the  derivation,  find  the  j ' th  leaf  from  the  left  in  t he 
current  parse  tree.  This  leaf  is  labeled  Xj.  Give  this  leaf  m  children,  labeled 
Y i ,Y 2 , ..  •  ,Ym,  from  the  left.  As  a  special  case,  if  m  =  0,  then  (3  —  e,  and  we 
give  the  j th  leaf  one  child  labeled  e. 

E x a m p le  4 . 1 0:  T he  sequence  of  parse  trees  constructed  from  the  derivation 
(4.8)  is  shown  in  Fig.  4.4. 
-E.  To 
model  this  step,  add  two  children,  labeled  —  and  E,  to  the  root  E  of the  initial 
tree.  T he  result  is  t he  second  tree. 

In  the  first  step  of  t he  derivation,  E 

In  the  second  step  of t he  derivation,  —E  =$>  -(E).  Consequently,  add  three 
children,  labeled  (j  E,  and  ),  to  the  leaf  labeled  E  of  t he  second  tree,  to 
obtain  the  third  tree  with  yield  -(E).  Continuing  in  this  fashion  we  obtain  the 
complete  parse  tree  as  the  sixth  tree. 

• 

Since  a  parse  tree  ignores  variations  in  t he  order  in  which  symbols  in  senten 
tial  forms  are  replaced,  there  is  a  many-to-one  relationship  between  derivations 
and  parse  trees.  For  example,  both  derivations  (4.8)  and  (4.9),  are  associated 
with  the  same  final  parse  tree  of  Fig.  4.4. 

In  what  follows,  we  shall  frequently  parse  by  producing  a  leftmost  or  a 
rightmost  derivation,  since  there  is  a  one-to-one  relationship  between  parse 
trees  and  either  leftmost  or  rightmost  derivations.  Both  leftmost  and  rightmost 
derivations  pick  a  particular  order  for  replacing  symbols  in  sentential  forms,  so 
they  too  filter  out  variations  in  t he  order.  It  is  not  ha rd  to  show  t h at  every  parse 
tree  has  associated  with  it  a  unique  leftmost  and  a  unique  rightmost  derivation. 

4.2. 

CONTEXT-FREE  GRAMMARS 

203 

E 

=> 

E 

=> 

E 

- 

£1 

( 

/ I\ 
B 
/ IV 

) 

/ l\ 
( 
£ 
/ l\ 

) 

# 
/ l\ 
E 

( 

/
l\ 
( 
E 
/ l\ 

) 

) 

E  + 

E 

E  + 

E 

E  + 

E 

id 
Figure  4.4:  Sequence  of  parse  trees  for  derivation  (4.8) 

id 

id 

4.2.5  Ambiguity 

From  Section  2.2.4,  a  g r a m m ar  t h at  produces  more  t h an  one  parse  tree  for  some 
sentence  is  said  to  be  ambiguous.  P ut  another  way,  an  ambiguous  grammar  is 
one  t h at  produces  more  t h an  one  leftmost  derivation  or  more  t h an  one  rightmost 
derivation  for  the  same  sentence. 

E x a m p le  4 . 1 1:  T he  arithmetic  expression  g r a m m ar  (4.3)  permits  two  distinct 
leftmost  derivations  for  t he  sentence  id  +  id  *  id: 

E 

E +  E 
id  +  E 
id  +E*E 
i d H - i d *# 
id + id * id 

=> 
=>• 

E 

=> 

E*E 

E  +  E*E 
id 
+E*E 
id  +  i d * .E 
id  +  id  *  id 

=> 

T he  corresponding  parse  trees  appear  in  Fig.  4.5. 

Note  t h at  the  parse  tree  of Fig.  4.5(a)  reflects  the  commonly  assumed  prece 
dence  of +  and  *,  while  the  tree  of Fig.  4.5(b)  does  not.  T h at  is,  it  is  customary 
to  treat  operator  *  as  having  higher  precedence  t h an  +,  corresponding  to  t he 
fact  t h at  we  would  normally  evaluate  an  expression  like  a  +  b  *  c  as  a  +  (b  *  c), 
rather  t h an  as  (a  +  b)  *  c. 

• 

For  most  parsers,  it  is  desirable  t h at  t he  grammar  be  made  unambiguous, 
for  if  it  is  not,  we  cannot  uniquely  determine  which  parse  tree  to  select  for  a 
sentence. 
In  other  cases,  it  is  convenient  to  use  carefully  chosen  ambiguous 
grammars,  together  with  disambiguating  rules  t h at  "throw  away"  undesirable 
parse  trees,  leaving  only  one  tree  for  each  sentence. 

204 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

id 

E 

E 

id 

(a) 

* 

E 

id 

+ 

E 

id 

E 

E 

id 

(b) 

id 

Figure  4.5:  Two  parse  trees  for  id+id*id 

4.2.6  Verifying  the  Language  Generated  by  a  Grammar 

Although  compiler  designers  rarely  do  so  for  a  complete  programming-language 
grammar,  it  is  useful  to  be  able  to  reason  t h at  a  given  set  of productions  gener 
ates  a  particular  language.  Troublesome  constructs  can  be  studied  by  writing 
a  concise,  abstract  g r a m m ar  and  studying  t he  language  t h at  it  generates.  We 
shall  construct  such  a  grammar  for  conditional  statements  below. 

A  proof t h at  a  grammar  G  generates  a  language  L  has  two  parts:  show  t h at 
every  string  generated  by  G  is  in  L,  and  conversely  t h at  every  string  in  L  can 
indeed  be  generated  by  G. 

E x a m p le  4 . 1 2:  Consider  the  following  grammar: 

S->(S)  S 

I  e 

(4.13) 

It  may  not  be  initially  apparent,  but  this  simple  g r a m m ar  generates  all 
strings  of  balanced  parentheses,  and  only  such  strings.  To  see  why,  we  shall 
show  first  t h at  every  sentence  derivable  from  S  is  balanced,  and  then  t h at  every 
balanced  string  is  derivable  from  5.  To  show  t h at  every  sentence  derivable  from 
S  is  balanced,  we  use  an  inductive  proof on  the  number  of steps  n  in  a  derivation. 

B A S I S:  T he  basis  is  n  =  1.  T he  only  string  of  terminals  derivable  from  S  in 
one  step  is  the  empty  string,  which  surely  is  balanced. 

I N D U C T I O N:  Now  assume  t h at  all  derivations  of fewer  t h an  n  steps  produce 
balanced  sentences,  and  consider  a  leftmost  derivation  of  exactly  n  steps.  Such 
a  derivation  must  be  of  t he  form 

(S)S^ 

(x)S^ 

{x)y 

lm 

Im 

Ira 

The  derivations  of x  and  y  from  S  take  fewer  t h an  n  steps,  so  by  t he  inductive 
hypothesis  x  and  y  are  balanced.  Therefore,  t he  string  (x)y  must  be  balanced. 
T h at  is,  it  has  an  equal  number  of  left  and  right  parentheses,  and  every  prefix 
has  at  least  as  many  left  parentheses  as  right. 

4.2. 

CONTEXT-FREE  GRAMMARS 

205 

Having  thus  shown  t h at  any  string  derivable  from  S  is  balanced,  we  must 
next  show t h at  every balanced  string is  derivable from  S.  To  do  so,  use  induction 
on  t he  length  of  a  string. 

B A S I S:  If the  string  is  of length  0,  it  must  be  e,  which  is  balanced. 

I N D U C T I O N:  First,  observe  t h at  every  balanced  string  has  even  length.  As 
sume  t h at  every  balanced  string  of  length  less  t h an  2n  is  derivable  from  5, 
and  consider  a  balanced  string  w  of  length  2n,  n  >  1.  Surely  w  begins  with  a 
left  parenthesis.  Let  (x)  be  the  shortest  nonempty  prefix  of  w  having  an  equal 
number  of left  and  right  parentheses.  T h en  w  can  be  written  as  w  =  (x)y  where 
both  x  and  y  are  balanced.  Since  x  and  y  are  of  length  less  t h an  2n,  they  are 
derivable  from  S  by  t he  inductive  hypothesis.  Thus,  we  can  find  a  derivation 
of  t he  form 

5 

( 5 )5  4 

(x)S  4 

(x)y 

proving  t h at  w  =  (x)y  is  also  derivable  from  5. 

• 

4.2.7  Context-Free  Grammars  Versus  Regular 

Expressions 

Before  leaving  this  section  on  grammars  and  their  properties,  we  establish  t h at 
grammars  are  a  more  powerful  notation  t h an  regular  expressions.  Every  con 
struct  t h at  can  be  described  by  a  regular  expression  can  be  described  by  a  gram 
mar,  but  not  vice-versa.  Alternatively,  every  regular  language  is  a  context-free 
language,  but  not  vice-versa. 

For  example,  the  regular  expression  (a|b)*abb  and  t he  grammar 

I  bA0 

A0 
Ai 
A2 
A3 

-> 
-* 
-> 
-> 

aA0 
bA2 
bA3 
e 

describe  t he  same  language,  the  set  of  strings  of  a's  and  6's  ending  in  abb. 

We  can  construct  mechanically  a  g r a m m ar  to  recognize  t he  same  language 
as  a  nondeterministic  finite  automaton  (NFA).  T he  grammar  above  was  con 
structed  from  the  NFA  in  Fig.  3.24  using  t he  following  construction: 

1.  For  each  state  i  of  the  NFA,  create  a  nonterminal  Ai. 

2.  If  state  i  has  a  transition  to  state  j  on  input  a,  add  the  production  Ai  —> 
aAj.  If  state  i  goes  to  state  j  on  input  e,  add  the  production  Ai  —•  Aj. 

3.  Hi  is  an  accepting  state,  add  Ai  —>  e. 

4.  If  i  is  the  start  state,  make  Ai  be  the  start  symbol  of  t he  grammar. 

206 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

On  t he  other  hand,  the  language  L  =  {anbn  |  n  >  1}  with  an  equal  number 
of  a's  and  6's  is  a  prototypical  example  of  a  language  t h at  can  be  described 
by  a  grammar  but  not  by  a  regular  expression.  To  see  why,  suppose  L  were 
the  language  defined  by  some  regular  expression.  We  could  construct  a  DFA  D 
with  a  finite  number  of states,  say  k,  to  accept  L.  Since  D  has  only  k  states,  for 
an  input  beginning  with  more  t h an  k  a's,  D  must  enter  some  state  twice,  say 
Si,  as  in  Fig.  4.6.  Suppose  t h at  the  p a th  from  Si  back  to  itself  is  labeled  with 
a  sequence  a?~l.  Since  a1  bl  is  in  t he  language,  there  must  be  a  p a th  labeled  bl 
from  Si  to  an  accepting  state  /.  But,  then  there  is  also  a  p a th  from  t he  initial 
state  «o  through 
to  /  labeled  a?bl,  as  shown  in  Fig.  4.6.  Thus,  D  also  accepts 
o?b%,  which  is  not  in  t he  language,  contradicting  the  assumption  t h at  L  is  t he 
language  accepted  by  D. 

path  labeled  a?~% 

Figure  4.6:  DFA  D  accepting  b o th  albl  and  a?b%. 

Colloquially,  we  say  t h at  "finite  a u t o m a ta  cannot  count,"  meaning  t h at 
a  finite  a u t o m a t on  cannot  accept  a  language  like  {anbn\n  >  1}  t h at  would 
require  it  to  keep  count  of the  number  of  a's  before  it  sees  t he  6's.  Likewise,  "a 
grammar  can  count  two  items  but  not  three,"  as  we  shall  see  when  we  consider 
non-context-free  language  constructs  in  Section  4.3.5. 

4.2.8  Exercises  for  Section  4.2 

E x e r c i se  4 . 2 . 1:  Consider  t he  context-free  grammar: 

5  ->  S  S  + 

\  S  S  *  \  a 

and  the  string  aa  +  a*. 

a)  Give  a  leftmost  derivation  for  t he  string. 

b)  Give  a  rightmost  derivation  for  the  string. 

c)  Give  a  parse  tree  for  the  string. 

!  d)  Is  t he  grammar  ambiguous  or  unambiguous?  Justify  your  answer. 

!  e)  Describe  the  language  generated  by  this  grammar. 

E x e r c i se  4 . 2 . 2:  Repeat  Exercise  4.2.1  for  each  of t he  following  grammars  and 
strings: 

4.2. 

CONTEXT-FREE  GRAMMARS 

207 

a)  S 

b)  S 

! c)  S 

0  5  1  |  0  1  with  string  000111. 

+  5  5  |  *  S  S  |  a  with  string  +  *  aaa. 

S 

(S)  S\e  with  string 

(()()). 

! d)  S 

->  S  + 

S\S  S\(S)\S 

* 

\ 

a  with  string  (a  +  a)  *  a. 

! e)  S 

-» 

(  L  )  |  a  and  L  -»  L  ,  5  |  5  with  string  ((a  , a ) , a , ( a ) ). 

!!  f)  S 

-» 

a 5 6 5 | & 5,a 5 |e  with  string  aabbab. 

The  following  grammar  for  boolean  expressions: 

-» 

bexpr 
ftterra  —>• 
-» 
bfactor 

6e:rpr  or  fcierm  |  frterm 

frterm 

a nd  bfactor  |  bfactor 
n ot  bfactor  |  (  fcezpr)  |  t r ue  |  false 

E x e r c i se  4 . 2 . 3:  Design  grammars  for  the  following  languages: 

a)  The  set  of all  strings  of 0s  and  Is  such  t h at  every  0  is  immediately  followed 

by  at  least  one  1. 

!  b)  T he  set  of  all  strings  of  0s  and  Is  t h at  are  palindromes;  t h at  is,  t he  string 

reads  the  same  backward  as  forward. 

!  c)  T he  set  of  all  strings  of  0s  and  Is  with  an  equal  number  of  0s  and  I s. 

!!  d)  T he  set  of  all  strings  of  0s  and  Is  with  an  unequal  number  of  0s  and  Is. 

!  e)  T he  set  of  all  strings  of  0s  and  Is  in  which  Oil  does  not  appear  as  a 

substring. 

!!  f)  T he  set  of  all  strings  of  0s  and  Is  of  the  form  xy,  where  x  ^  y  and  x  and 

y  are  of  the  same  length. 

E x e r c i se  4 . 2 . 4:  There  is  an  extended  g r a m m ar  notation  in  common  use.  In 
this  notation,  square  and  curly  braces  in  production  bodies  are  metasymbols 
(like  —>•  or  |)  with  the  following  meanings: 

i)  Square  braces  around  a  grammar  symbol  or  symbols  denotes  t h at  these 
constructs  are  optional.  T h u s,  production  A  —>  X  [Y]  Z  has  t he  same 
effect  as  t he  two  productions  A 

X  Y  Z  and  A  -±  X  Z. 

ii)  Curly  braces  around  a  grammar  symbol  or  symbols  says  t h at  these  sym 
bols  may  be  repeated  any  number  of  times,  including  zero  times.  Thus, 
A  —>•  X  {Y  Z}  has  t he  same  effect  as  t he  infinite  sequence  of productions 
A-*X,A->XYZ,A-*XYZYZ, 

and 

on. 

so 

208 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

Show  t h at  these  two  extensions  do  not  add  power  to  grammars;  t h at  is,  any 
language  t h at  can  be  generated  by  a  grammar  with  these  extensions  can  be 
generated  by  a  grammar  without  t he  extensions. 

E x e r c i se  4 . 2 . 5:  Use  the  braces  described  in  Exercise  4.2.4  to  simplify  t he 
following  grammar  for  statement  blocks  and  conditional  statements: 

stmt 

stmtList 

-> 
| 
| 
-> 

if  expr  t h en  stmt  e l se  stmt 
if  stmt  t h en  stmt 
b e g in 
stmt; 

stmtList  e nd 

stmtList 

stmt 

| 

!  E x e r c i se  4 . 2 . 6:  Extend  the  idea  of Exercise  4.2.4  to  allow  any  regular  expres 
sion  of g r a m m ar  symbols  in  the  body  of a  production.  Show  t h at  this  extension 
does  not  allow  grammars  to  define  any  new  languages. 

!  E x e r c i se  4 . 2 . 7:  A  grammar  symbol  X  (terminal  or  nonterminal)  is  useless  if 
wXy  ^  wxy.  T h at  is,  X  can  never 

there  is  no  derivation  of  the  form  S 
appear  in  t he  derivation  of  any  sentence. 

a)  Give  an  algorithm  to  eliminate  from  a  g r a m m ar  all  productions  containing 

useless  symbols. 

b)  Apply  your  algorithm  to  the  grammar: 

S 
A 
B 

-+ 
-> 
-> 

0  |  A 
AB 
1 

E x e r c i se  4 . 2 . 8:  T he  grammar  in  Fig.  4.7  generates  declarations  for  a  sin 
gle  numerical  identifier;  these  declarations  involve  four  different,  independent 
properties  of  numbers. 

stmt 
optionList 
option 
mode 
scale 
precision 
base 

d e c l a re 
optionList  option  \  e 

id  optionList 

-»  mode  |  scale  |  precision  |  base 
-¥ 
-> 
-> 
-> 

real  |  c o m p l ex 
fixed 
|  floating 
s i n g le  |  d o u b le 
b i n a ry  |  d e c i m al 

Figure  4.7:  A  g r a m m ar  for  multi-attribute  declarations 

a)  Generalize  t he  g r a m m ar  of  Fig.  4.7  by  allowing  n  options  Ai,  for  some 
fixed  n  and  for  i  =  1 , 2 . ..  , n,  where  Ai  can  be  either  ai  or  bi.  Your 
grammar  should  use  only  0(n)  g r a m m ar  symbols  and  have  a  total  length 
of  productions  t h at  is  0(n). 

4.3.  WRITING  A  GRAMMAR 

209 

!  b)  T he  g r a m m ar  of  Fig.  4.7  and  its  generalization  in  part  (a)  allow  declara 

tions  t h at  are  contradictory  a n d / or  redundant,  such  as: 

declare  foo  real  fixed  real  floating 

We  could  insist  t h at  the  syntax  of  the  language  forbid  such  declarations; 
t h at  is,  every  declaration  generated  by  the  grammar  has  exactly  one  value 
for  each  of the  n  options.  If we  do,  then  for  any  fixed  n  there  is  only  a  finite 
number  of legal  declarations.  The  language  of  legal  declarations  thus  has 
a  g r a m m ar  (and  also  a  regular  expression),  as  any  finite  language  does. 
T he  obvious  grammar,  in  which  the  start  symbol  has  a  production  for 
every  legal  declaration  has  n!  productions  and  a  total  production  length 
of  0 (n  x  n!).  You  must  do  better:  a  total  production  length  t h at  is 
0 ( n 2n). 

!!  c)  Show  t h at  any  grammar  for  part  (b)  must  have  a  total  production  length 

of  at  least  2n. 

d)  W h at  does  part  (c)  say  about  the  feasibility  of  enforcing  nonredundancy 
and  noncontradiction  among  options  in  declarations  via  the  syntax  of  the 
programming  language? 

4.3  Writing  a  Grammar 

G r a m m a rs  are  capable  of  describing  most,  but  not  all,  of  t he  syntax  of  pro 
gramming  languages.  For  instance,  the  requirement  t h at  identifiers  be  declared 
before  they  are  used,  cannot  be  described  by  a  context-free  grammar.  Therefore, 
the  sequences  of  tokens  accepted  by  a  parser  form  a  superset  of  the  program 
ming  language;  subsequent  phases  of  the  compiler  must  analyze  t he  output  of 
the  parser  to  ensure  compliance  with  rules  t h at  are  not  checked  by  the  parser. 
This  section  begins  with  a  discussion  of how  to  divide  work  between  a  lexical 
analyzer  and  a  parser.  We  then  consider  several  transformations  t h at  could  be 
applied  to  get  a  g r a m m ar  more  suitable  for  parsing.  One  technique  can  elim 
inate  ambiguity  in  t he  grammar,  and  other  techniques  —  left-recursion  elimi 
nation  and  left  factoring  —  are  useful  for  rewriting  grammars  so  they  become 
suitable  for  top-down  parsing.  We  conclude  this  section  by  considering  some 
programming  language  constructs  t h at  cannot  be  described  by  any  grammar. 

4.3.1  Lexical  Versus  Syntactic  Analysis 

As  we  observed  in  Section  4.2.7,  everything  t h at  can  be  described  by  a  regular 
expression  can  also  be  described  by  a  grammar.  We  may  therefore  reasonably 
ask:  "Why  use  regular  expressions  to  define  the  lexical  syntax  of  a  language?" 
There  are  several  reasons. 

210 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

1.  Separating  t he  syntactic  structure  of  a  language  into  lexical  and  non-
lexical  parts  provides  a  convenient  way  of  modularizing  t he  front  end  of 
a  compiler  into  two  manageable-sized  components. 

2.  The  lexical  rules  of a  language  are  frequently  quite  simple,  and  to  describe 

them  we  do  not  need  a  notation  as  powerful  as  grammars. 

3.  Regular  expressions  generally  provide  a  more  concise  and  easier-to-under-

stand  notation  for  tokens  t h an  grammars. 

4.  More  efficient  lexical  analyzers  can  be  constructed  automatically  from 

regular  expressions  t h an  from  arbitrary  grammars. 

There  are  no  firm  guidelines  as  to  what  to  put  into  t he  lexical  rules,  as  op 
posed  to  the  syntactic  rules.  Regular  expressions  are  most  useful  for  describing 
the  structure  of  constructs  such  as  identifiers,  constants,  keywords,  and  white 
space.  G r a m m a r s,  on  the  other  hand,  are  most  useful  for  describing  nested 
structures  such  as  balanced  parentheses,  matching  begin-end's,  corresponding 
if-then-else's,  and  so  on.  These  nested  structures  cannot  be  described  by  regular 
expressions. 

4.3.2  Eliminating  Ambiguity 

Sometimes  an  ambiguous  grammar  can  be  rewritten  to  eliminate  t he  ambiguity. 
As  an  example,  we  shall  eliminate  t he  ambiguity  from  the  following  "dangling-
else"  grammar: 

stmt  —> 

| 
| 

if  expr  t h en  stmt 
if  expr  t h en  stmt  e l se  stmt 
o t h er 

(4.14) 

Here  "other"  stands  for  any  other  statement.  According  to  this  g r a m m a r,  t he 
compound  conditional  statement 

if  Ei  t h en  Si  e l se  if  E2  t h en  S2  e l se 53 

Figure  4.8:  Parse  tree  for  a  conditional  statement 

4.3. 

WRITING  A  GRAMMAR 

211 

has  the  parse  tree  shown  in  Fig.  4 . 8 .1  G r a m m ar  (4.14)  is  ambiguous  since  t he 

string 

if Ei  t h en  if E2  t h en  Si  e l se  S2 

(4.15) 

has  the  two  parse  trees  shown  in  Fig.  4.9. 

stmt 

E2 

Si 

52 

E2 

Si 

Figure  4.9:  Two  parse  trees  for  an  ambiguous  sentence 

In  all  programming  languages  with  conditional  statements  of  this  form,  t he 
first  parse  tree  is  preferred.  T he  general  rule  is,  "Match  each  else  with  the 
closest  unmatched  t h e n . "2  This  disambiguating  rule  can  theoretically  be  in 
corporated  directly  into  a  grammar,  but  in  practice  it  is  rarely  built  into  t he 
productions. 

E x a m p le  4 . 1 6:  We  can  rewrite  the  dangling-else  grammar  (4.14)  as  t he  fol 
lowing  unambiguous  grammar.  T he  idea  is  t h at  a  statement  appearing  between 
a  t h en  and  an  e l se  must  be  "matched";  t h at  is,  t he  interior  statement  must 
not  end  with  an  unmatched  or  open  t h e n.  A  matched  statement  is  either  an 
if-then-else  statement  containing  no  open  statements  or  it  is  any  other  kind 
of  unconditional  statement.  Thus,  we  may  use  t he  grammar  in  Fig.  4.10.  This 
g r a m m ar  generates  the  same  strings  as  the  dangling-else  g r a m m ar  (4.14),  but 
it  allows  only  one  parsing  for  string  (4.15);  namely,  the  one  t h at  associates  each 
e l se  with  the  closest  previous  unmatched  t h e n. 

• 

1T he  subscripts  on  E  and  S  are  just  to  distinguish  different  occurrences  of  the  same 

nonterminal,  and  do  not  imply  distinct  nonterminals. 

2We  should  note  that  C  and  its  derivatives  are  included  in  this  class.  Even  though  the  C 
family  of languages  do  not  use  the  keyword then,  its  role  is  played  by  the  closing  parenthesis 
for  the  condition  that  follows if. 

212 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

stmt 

-» 
| 

matchedstmt 
openstmt 

matchedstmt 

openstmt 

-» 
| 
-» 
| 

if  expr  t h en  matchedstmt  e l se  matchedstmt 
o t h er 
if  expr  t h en  s£m£ 
if  expr  t h en  matchedstmt  e l se 

openstmt 

Figure  4.10:  Unambiguous  g r a m m ar  for  if-then-else  statements 

4.3.3  Elimination  of  Left  Recursion 

A  grammar  is  left  recursive  if  it  has  a  nonterminal  A  such  t h at  there  is  a 
derivation  A  4  Aa  for  some  string  a.  Top-down  parsing  methods  cannot 
handle  left-recursive  grammars,  so  a  transformation  is  needed  to  eliminate  left 
recursion.  In  Section  2.4.5,  we  discussed  immediate  left  recursion,  where  there 
In 
is  a  production  of  the  form  A  ->•  Aa.  Here,  we  study  t he  general  case. 
Section  2.4.5,  we  showed  how  the  left-recursive  pair  of productions  A  -»•  Aa  |  ft 
could  be  replaced  by  the  non-left-recursive  productions: 

A->0A' 
A'-+aA' 

| 

e 

without  changing  t he  strings  derivable  from  A.  This  rule  by  itself  suffices  for 
many  grammars. 

E x a m p le  4 . 1 7:  The  non-left-recursive  expression  grammar  (4.2),  repeated 
here, 

E  ->  T  E' 
E'  ^  +  T  E' 
T 
^  FT' 
T'  ->  *  F  T 
F->(E) 

| 

id 

is  obtained  by  eliminating  immediate  left  recursion  from  the  expression  gram 
m ar  (4.1).  T he  left-recursive  pair  of productions  E  -»  E  +  T 
|  T  are  replaced 
e.  T he  new  productions  for  T  and  T'  are 
by  E  ->  T  E'  and  E'  -»•  +  T  E' 
obtained  similarly  by  eliminating  immediate  left  recursion. 

• 

\ 

Immediate  left  recursion  can  be  eliminated  by  the  following technique,  which 

works  for  any  number  of  A-productions.  First,  group  the  productions  as 

A-±Aai 

|  Aa2 

| 

••• 

|  Aam 

| 

(31 

| 

ft 

| 

•  •  • 

| 

/3n 

where  no  ft  begins  with  an  A.  Then,  replace  the  A-productions  by 

4.3. 

WRITING  A  GRAMMAR 

213 

A' 

a i A' 

|  a2A' 

|  •  •  • 

|  amA' 

\  e 

T he  nonterminal  A  generates  the  same  strings  as  before  but  is  no  longer  left 
recursive.  This  procedure  eliminates  all  left  recursion  from  t he  A  and  A'  pro 
ductions  (provided  no 
is  e),  b ut  it  does  not  eliminate  left  recursion  involving 
derivations  of two  or  more  steps.  For  example,  consider  t he  g r a m m ar 

A 

A  c 

|  S  d 

|  e 

v 

; 

T he  nonterminal  S  is  left  recursive  because  S 
immediately  left  recursive. 

Aa 

Sda,  b ut  it  is  not 

Algorithm  4.19,  below,  systematically  eliminates  left  recursion  from  a  gram 
mar.  It  is  guaranteed  to  work  if  the  g r a m m ar  has  no  cycles  (derivations  of  the 
form  A 
A)  or  e-productions  (productions  of t he  form  A  —>  e).  Cycles  can  be 
eliminated  systematically  from  a  grammar,  as  can  e-productions  (see  Exercises 
4.4.6  and  4.4.7). 

A l g o r i t hm  4 . 1 9:  Eliminating  left  recursion. 

I N P U T:  G r a m m ar  G  with  no  cycles  or  e-productions. 

O U T P U T:  An  equivalent  g r a m m ar  with  no  left  recursion. 

M E T H O D:  Apply  the  algorithm  in  Fig.  4.11  to  G.  Note  t h at  the  resulting 
non-left-recursive  g r a m m ar  may  have  e-productions. 

• 

1) 
2) 
3) 
4) 

5) 
6) 
7) 

arrange  the  nonterminals 
for  (  each  i  from  1  to  n  )  { 

in  some  order  Ai,Az,... 

,An. 

for  (  each  j  from  1  to  i  —  1  )  { 

replace  each  production  of  t he  form  Ai  —>  Ajj  by  the 
productions  Ai  ->  <5i7  |  #27  |  • • •  |  Sky,  where 
Aj  —> Si  I  S2  I  • • •  I  Sk  are all current Aj-productions 

} 
eliminate  the  immediate  left  recursion  among  the  ^ - p r o d u c t i o ns 

} 

Figure  4.11:  Algorithm  to  eliminate  left  recursion  from  a  g r a m m ar 

T he  procedure  in  Fig.  4.11  works  as  follows.  In  the  first  iteration  for  %  = 
1,  t he  outer  for-loop  of  lines  (2)  through  (7)  eliminates  any  immediate  left 
recursion  among  A\-productions.  Any  remaining  A\  productions  of  the  form 
A\  —>  A\a  must  therefore  have  /  >  1.  After  the  i —  1st  iteration  of the  outer  for-
loop,  all  nonterminals  Ak,  where  k  <  i,  are  "cleaned";  t h at  is,  any  production 
Ak  —>  Aia,  must  have  I  >  k.  As  a  result,  on  the  ith.  iteration,  t he  inner  loop 

214 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

of  lines  (3)  through  (5)  progressively  raises  the  lower  limit  in  any  production 
Ai  -+  A  ma,  until  we  have  m  >  i.  Then,  eliminating  immediate  left  recursion 
for  the  Ai  productions  at  line  (6)  forces  m  to  be  greater  t h an  i. 

E x a m p le  4 . 2 0:  Let  us  apply  Algorithm  4.19  to  t he  g r a m m ar  (4.18).  Techni 
cally,  the  algorithm  is  not  guaranteed  to  work,  because  of the  e-production,  but 
in  this  case,  the  production  A  -»  e  t u r ns  out  to  be  harmless. 

We  order  the  nonterminals  S,  A.  There  is  no  immediate  left  recursion 
among  the  5-productions,  so  nothing  happens  during  the  outer  loop  for  i  =  1. 
For i  =  2,  we  substitute  for  S  in  A  —>  S  d to  obtain  t he  following ^.-productions. 

A^  Ac 

|  Aa  d 

|  b  d 

| 

e 

Eliminating  the  immediate  left  recursion  among  these  ^ - p r o d u c t i o ns  yields  t he 
following  grammar. 

S-^Aa 
A^bdA' 
A'-*cA' 

| 

b 

| 

A' 
ad  A' 

| 

| 

e 

• 

4.3.4  Left  Factoring 

Left  factoring  is  a  grammar  transformation  t h at  is  useful  for  producing  a  gram 
mar  suitable  for  predictive,  or  top-down,  parsing.  W h en  t he  choice  between 
two  alternative  ^-productions  is  not  clear,  we  may  be  able  to  rewrite  t he  pro 
ductions  to  defer  the  decision  until  enough  of  the  input  has  been  seen  t h at  we 
can  make  the  right  choice. 

For  example,  if  we  have  t he  two  productions 

stmt 

->• 
| 

if  expr  t h en  stmt  e l se  stmt 
if  expr  t h en  stmt 

on  seeing  the  input  if,  we  cannot  immediately  tell  which  production  to  choose 
to  expand  stmt.  In  general,  if  A  ->•  a ft 
|  a ft  are  two  A-productions,  and  t he 
input  begins  with  a  nonempty  string  derived  from  a,  we  do  not  know  whether 
to  expand  A  to  a ft  or  a f t.  However,  we  may  defer  t he  decision  by  expanding 
A  to  aA'.  Then,  after  seeing  t he  input  derived  from  a,  we  expand  A'  to  ft  or 
to  ft.  T h at  is,  left-factored,  t he  original  productions  become 

A  ->•  aA' 
A ' ^ ft 

|  ft 

A l g o r i t hm  4 . 2 1:  Left  factoring  a  grammar. 

I N P U T:  G r a m m ar  G. 

O U T P U T:  An  equivalent  left-factored  grammar. 

4.3. 

WRITING  A  GRAMMAR 

215 

M E T H O D:  For  each  nonterminal  A,  find  the  longest  prefix  a  common  to  two 
If  a  ^  e  —  i.e.,  there  is  a  nontrivial  common 
or  more  of  its  alternatives. 
prefix  —  replace  all  of t he  A-productions  A  -» 
|  afo  |  •  •  •  |  oi(5n  |  7,  where 
7  represents  all  alternatives  t h at  do  not  begin  with  a,  by 

A  -»•  aA'  I  7 
ft 
A ' - > / 3i 

j 

I  ••• 

I  (3n 

Here  A'  is  a  new  nonterminal.  Repeatedly  apply  this  transformation  until  no 
two  alternatives  for  a  nonterminal  have  a  common  prefix. 

• 

E x a m p le  4 . 2 2:  T he  following  g r a m m ar  abstracts  the  "dangling-else"  prob 
lem: 

S ^ i E tS 
b 
E 

I 

i E t S eS 

\  a 

, 

. 

Here,  i,  t,  and  e  stand  for  if,  t h e n,  and  e l s e;  E  and  5  stand  for  "conditional 
expression"  and  "statement."  Left-factored,  this  grammar  becomes: 

S  -M  Et  S  S'  I  a 
S ' ^ eS  I  e 
E  ->  6 

(4.24) 

T h u s,  we  may  expand  5  to  iEtSS'  on  input  i,  and  wait  until  i £ t t5  has  been 
seen  to  decide  whether  to  expand  S'  to  eS  or  to  e.  Of  course,  these  grammars 
are  b o th  ambiguous,  and  on  input  e,  it  will  not  be  clear  which  alternative  for 
S'  should  be  chosen.  Example  4.33  discusses  a  way  out  of  this  dilemma. 

• 

4.3.5  Non-Context-Free  Language  Constructs 

A  few  syntactic  constructs  found  in  typical  programming  languages  cannot  be 
specified  using  grammars  alone.  Here,  we  consider  two  of  these  constructs, 
using  simple  abstract  languages  to  illustrate  the  difficulties. 

E x a m p le  4 . 2 5:  The  language  in  this  example  abstracts  the  problem  of check 
ing  t h at  identifiers  are  declared  before  they  are  used  in  a  program.  T he  language 
consists  of  strings  of t he  form  wcw,  where  the  first  w  represents  the  declaration 
of an  identifier  w,  c  represents  an  intervening program  fragment,  and  the  second 
w  represents  the  use  of  the  identifier. 

T he  abstract  language  is  L\  —  {wcw  \  w  is  in  ( a | b ) * }.  L\  consists  of 
all  words  composed  of  a  repeated  string  of  a's  and  6's  separated  by  c,  such 
as  aabcaab.  While  it  is  beyond  t he  scope  of  this  book  to  prove  it,  t he  non-
context-freedom  of  Li  directly  implies  t he  non-context-freedom  of programming 
languages  like  C  and  Java,  which  require  declaration  of  identifiers  before  their 
use  and  which  allow  identifiers  of  arbitrary  length. 

For  this  reason,  a  g r a m m ar  for  C  or  Java  does  not  distinguish  among  identi 
fiers  t h at  are  different  character  strings.  Instead,  all  identifiers  are  represented 

216 

CHAPTER  4. 

SYNTAX  ANALYSIS 

by  a  token  such  as  id  in  the  grammar. 
In  a  compiler  for  such  a  language, 
the  semantic-analysis  phase  checks  t h at  identifiers  are  declared  before  they  are 
used. 

• 

E x a m p le  4 . 2 6:  T he  non-context-free  language  in  this  example  abstracts  the 
problem  of checking t h at  the  number  of formal  parameters  in  the  declaration  of a 
function  agrees  with  t he  number  of  actual  parameters  in  a  use  of  the  function. 
The  language  consists  of  strings  of  the  form  anbmcndm. 
(Recall  an  means  a 
written  n  times.)  Here  an  and  bm  could  represent  the  formal-parameter  lists  of 
two  functions  declared  to  have  n  and  m  arguments,  respectively,  while  cn  and 
dm  represent  t he  actual-parameter  lists  in  calls  to  these  two  functions. 

T he  abstract  language  is  L2  =  {anbmcndm  \  n  >  1  and  m  >  1}.  T h at  is,  L2 
consists  of strings  in  the  language  generated  by  t he  regular  expression  a*b*c*d* 
such  t h at  the  number  of  a's  and  c's  are  equal  and  t he  number  of  6's  and  d's  are 
equal.  This  language  is  not  context  free. 

Again,  the  typical  syntax  of function  declarations  and  uses  does  not  concern 
itself  with  counting  the  number  of  parameters.  For  example,  a  function  call  in 
C-like  language  might  be  specified  by 

stmt 
exprJist 

-> 
-» 
| 

id  (  exprJist) 
exprJist  ,  expr 
expr 

with  suitable  productions  for  expr.  Checking  t h at  t he  number  of  parameters  in 
a  call  is  correct  is  usually  done  during  t he  semantic-analysis  phase. 

• 

4.3.6  Exercises  for  Section  4.3 

E x e r c i se  4 . 3 . 1:  T he  following  is  a  grammar  for  regular  expressions  over  sym 
bols  a  and  b  only,  using  +  in  place  of  |  for  union,  to  avoid  conflict  with  t he  use 
of  vertical  bar  as  a  metasymbol  in  grammars: 

rexpr 
rterm 
rfactor 
rprimary 

rexpr  +  rterm  |  rterm 
rterm  rfactor  \  rfactor 
rfactor  *  |  rprimary 
a  |  b 

a)  Left  factor  this  grammar. 

b)  Does  left  factoring  make  t he  g r a m m ar  suitable  for  top-down  parsing? 

c)  In  addition  to  left  factoring,  eliminate  left  recursion  from  t he  original 

grammar. 

d)  Is  the  resulting  g r a m m ar  suitable  for  top-down  parsing? 

E x e r c i se  4 . 3 . 2:  Repeat  Exercise  4.3.1  on  the  following  grammars: 

4.4. 

TOP-DOWN  PARSING 

217 

a)  T he  g r a m m ar  of  Exercise  4.2.1. 

b)  The  g r a m m ar  of  Exercise  4.2.2(a). 

c)  T he  g r a m m ar  of  Exercise  4.2.2(c). 

d)  T he  g r a m m ar  of  Exercise  4.2.2(e). 

e)  T he  g r a m m ar  of  Exercise  4.2.2(g). 

!  E x e r c i se  4 . 3 . 3:  T he  following  g r a m m ar  is  proposed  to  remove  the  "dangling-

else  ambiguity"  discussed  in  Section  4.3.2: 

stmt 

matchedStmt 

-» 
| 
—> 
| 

if  expr  t h en  stmt 

matchedStmt 
if  expr  t h en  matchedStmt  e l se  stmt 

o t h er 

Show  t h at  this  g r a m m ar  is  still  ambiguous. 

4.4  Top-Down  Parsing 

Top-down  parsing  can  be  viewed  as  the  problem  of  constructing  a  parse  tree  for 
t he  input  string,  starting  from  t he  root  and  creating  the  nodes  of t he  parse  tree 
in  preorder  (depth-first,  as  discussed  in  Section  2.3.4).  Equivalently,  top-down 
parsing  can  be  viewed  as  finding  a  leftmost  derivation  for  an  input  string. 

E x a m p le  4. 2 7:  The  sequence  of parse  trees  in  Fig.  4.12  for  the  input  i d + i d * id 
is  a  top-down  parse  according  to  g r a m m ar  (4.2),  repeated  here: 

E 
E' 
T 
V 
F 

-> 
T  E' 
->  +  T  E1  1 c 
->  F  V 
-> 
-» 

*  F  r  1 c 
|  id 
(E) 

This  sequence  of  trees  corresponds  to  a  leftmost  derivation  of  t he  input. 

• 

At  each  step  of  a  top-down  parse,  the  key  problem  is  t h at  of  determining 
t he  production  to  be  applied  for  a  nonterminal,  say  A.  Once  an  A-production 
is  chosen,  t he  rest  of  t he  parsing  process  consists  of  "matching"  the  terminal 
symbols  in  t he  production  body  with  the  input  string. 

The  section  begins  with  a  general  form  of top-down  parsing,  called  recursive-
descent  parsing,  which  may  require  backtracking  to  find  the  correct  A-produc-
tion  to  be  applied.  Section  2.4.2  introduced  predictive  parsing,  a  special  case  of 
recursive-descent  parsing,  where  no  backtracking is  required.  Predictive  parsing 
chooses  t he  correct  A-production  by  looking  ahead  at  t he  input  a  fixed  number 
of  symbols,  typically  we  may  look  only  at  one  (that  is,  the  next  input  symbol). 

218 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

E  =>  EI  => 
I  \ 
Im 
T  E' 

Im 

EI  => 
/  \ 
Im 
T  E' 

E 
/  \ 
T  E' 

/\ 
FT' 

/\, 
FT' 

id 

=> 
Im 

E 
\ 

/ 

T 
/\ 

FT' 
id e 

E' 

=> 
Im 

E 
/ 

\ 

T 

E' 

/I  / l\ 
F  T'  +  T  E' 
id e 

E 

Im 

T 

E' 

Im 

/I  / V  . 
T  E' 

F  T'  + 
II 
id  e 

/ \ 
T' 

F 

E 

/ 
T 

\ 

E' 

Im 

/I  / \  . 
T  E' 

F  T'  + 

id  e 

T' 

F 

id 

E 

/ 
T 

\ 

E' 

/I  / V  . 
T  E' 

F  T'  + 
II 
id  e 

/ \ 
T' 

F 
I  / l\ 
FT' 
* 
id 

E 

Im 

T 

E' 

/I  / V 

Im 

F  T'  + 
II 
id  e 

T  E' 

/  \ 
F 
T' 
I  / l\ 
FT' 
id 
I 
id 

* 

E 
^ 

/ 
T 

E' 

/I  / V 

F  T'  + 
II 
id  e 

T  E' 

/  \ 
F 
T' 
I  / l\ 
FT' 
id 
\ I 
id e 

* 

E 

\ 

/ 
T 

E' 
/I  / 

F  T'  + 
If 
id  e 

T 

E' 
/ \  I 
T'  e 
F 
I  / l\ 
id  *  F  T' 

id e 

Figure  4.12:  Top-down  parse  for  id  +  id  *  id 

For  example,  consider  the  top-down  parse  in  Fig.  4.12,  which  constructs 
a  tree  with  two  nodes  labeled  E'.  At  the  first  E'  node  (in  preorder),  t he 
production  E'  —>  +TE'  is  chosen;  at  the  second  E'  node,  the  production  E'  —>  e 
is  chosen.  A  predictive  parser  can  choose  between  E'-productions  by  looking 
at  the  next  input  symbol. 

T he  class  of grammars  for  which  we  can  construct  predictive  parsers  looking 
k  symbols  ahead  in  t he  input  is  sometimes  called  the  LL(k)  class.  We  discuss  t he 
LL(1)  class  in  Section  4.4.3,  but  introduce  certain  computations,  called  FIRST 
and  FOLLOW,  in  a  preliminary  Section  4.4.2.  From  the  FIRST  and  FOLLOW 
sets  for  a  grammar,  we  shall  construct  "predictive  parsing  tables,"  which  make 
explicit  t he  choice  of  production  during  top-down  parsing.  These  sets  are  also 
useful  during  bottom-up  parsing, 

In  Section  4.4.4  we  give  a  nonrecursive  parsing  algorithm  t h at  maintains 
a  stack  explicitly,  rather  t h an  implicitly  via  recursive  calls.  Finally,  in  Sec 
tion  4.4.5  we  discuss  error  recovery  during  top-down  parsing. 

4.4. 

TOP-DOWN  PARSING 

219 

4.4.1  Recursive-Descent  Parsing 

v o id  A{)  { 

Choose  an  A-production,  A 
for  (i  =  1  to  k  )  { 

X\X2  -  •  •  Xk\ 

if  (  X{  is  a  nonterminal  ) 

call  procedure  XiQ; 

e l se  if  (  Xi  equals  the  current  input  symbol  a  ) 

advance  the  input  to  t he  next  symbol; 

e l se  /*  an  error  has  occurred  */; 

1) 
2) 
3) 
4) 
5) 
6) 
7) 

} 

} 

Figure  4.13:  A  typical  procedure  for  a  nonterminal  in  a  top-down  parser 

A  recursive-descent  parsing  program  consists  of  a  set  of procedures,  one  for  each 
nonterminal.  Execution  begins  with  the  procedure  for  the  start  symbol,  which 
halts  and  announces  success  if  its  procedure  body  scans  t he  entire  input  string. 
Pseudocode  for  a  typical  nonterminal  appears  in  Fig.  4.13.  Note  t h at  this 
pseudocode  is  nondeterministic,  since  it  begins  by  choosing  the  A-production 
to  apply  in  a  manner  t h at  is  not  specified. 

General  recursive-descent  may  require  backtracking;  t h at  is,  it  may  require 
repeated  scans  over  the  input.  However,  backtracking  is  rarely  needed  to  parse 
programming  language  constructs,  so  backtracking  parsers  are  not  seen  fre 
quently.  Even  for  situations  like  natural  language  parsing,  backtracking  is  not 
very  efficient,  and  tabular  methods  such  as  the  dynamic  programming  algo 
rithm  of  Exercise  4.4.9  or  the  method  of  Earley  (see  the  bibliographic  notes) 
are  preferred. 

To  allow  backtracking,  t he  code  of Fig.  4.13  needs  to  be  modified.  First,  we 
cannot  choose  a  unique  A-production  at  line  (1),  so  we  must  try  each  of  several 
productions  in  some  order.  Then,  failure  at  line  (7)  is  not  ultimate  failure,  but 
suggests  only  t h at  we  need  to  return  to  line  (1)  and  try  another  A-production. 
Only  if  there  are  no  more  A-productions  to  try  do  we  declare  t h at  an  input 
error  has  been  found.  In  order  to  try  another  A-production,  we  need  to  be  able 
to  reset  t he  input  pointer  to  where  it  was  when  we  first  reached  line  (1).  Thus, 
a  local  variable  is  needed  to  store  this  input  pointer  for  future  use. 

E x a m p le  4 . 2 9:  Consider  the  grammar 
-> 
-» 

S 
A 

cAd 
a  b  I  a 

To  construct  a  parse  tree  top-down  for  the  input  string  w  =  cad,  begin  with  a 
tree  consisting  of  a  single  node  labeled  S,  and  the  input  pointer  pointing  to  c, 
t he  first  symbol  ofw.S  has  only  one  production,  so  we  use  it  to  expand  S  and 

220 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

obtain  the  tree  of  Fig.  4.14(a).  T he  leftmost  leaf,  labeled  c,  matches  the  first 
symbol  of  input  w,  so  we  advance  t he  input  pointer  to  a,  t he  second  symbol  of 
w,  and  consider  the  next  leaf,  labeled  A. 

S 

s 

i  -

A 

(a) 

S 

A 

d 

b 

(b) 

S 

A 

a 

(c) 

Figure  4.14:  Steps  in  a  top-down  parse 

Now,  we  expand  A  using  the  first  alternative  A  ->  a  b  to  obtain  the  tree  of 
Fig.  4.14(b).  We  have  a  match  for  the  second  input  symbol,  a,  so  we  advance 
the  input  pointer  to  d,  the  third  input  symbol,  and  compare  d  against  t he  next 
leaf,  labeled  b.  Since  b  does  not  match  d,  we  report  failure  and  go  back  to  A  to 
see  whether  there  is  another  alternative  for  A  t h at  has  not  been  tried,  but  t h at 
might  produce  a  match. 

In  going  back  to  A,  we  must  reset  the  input  pointer  to  position  2,  t he 
position  it  had  when  we  first  came  to  A,  which  means  t h at  t he  procedure  for  A 
must  store  the  input  pointer  in  a  local  variable. 

T he  second  alternative  for  A  produces  t he  tree  of  Fig.  4.14(c).  T he  leaf 
a  matches  the  second  symbol  of  w  and  the  leaf  d  matches  the  third  symbol. 
Since  we  have  produced  a  parse  tree  for  w,  we  halt  and  announce  successful 
completion  of  parsing. 

• 

A  left-recursive  grammar  can  cause  a  recursive-descent  parser,  even  one 

with  backtracking,  to  go  into  an  infinite  loop.  T h at  is,  when  we  t ry  to  expand 
a  nonterminal  A,  we  may  eventually  find  ourselves  again  trying  to  expand  A 
without  having  consumed  any  input. 

4.4.2  FIRST  and  FOLLOW 

The  construction  of  b o th  top-down  and  bottom-up  parsers  is  aided  by  two 
functions,  FIRST  and  FOLLOW,  associated  with  a  g r a m m ar  G.  During  top-
down  parsing,  FIRST  and  FOLLOW  allow  us  to  choose  which  production  to 
apply,  based  on  the  next  input  symbol.  During  panic-mode  error  recovery,  sets 
of  tokens  produced  by  FOLLOW  can  be  used  as  synchronizing  tokens. 

Define  FIRST(a),  where  a  is  any  string  of  grammar  symbols,  to  be  the  set 
If  a  =>-  e,  then  e  is  also  in 

of  terminals  t h at  begin  strings  derived  from  a. 
FIRST(cn).  For  example,  in  Fig.  4.15,  A  ^  cy,  so  c  is  in  FIRST(A). 

For  a  preview  of how  FIRST  can  be  used  during  predictive  parsing,  consider 
two  A-productions  A  ->•  a  |  0,  where  FlRST(a)  and  FiRST(/3)  are  disjoint  sets. 
We  can  then  choose  between  these  A-productions  by  looking  at  t he  next  input 

4.4. 

TOP-DOWN  PARSING 

221 

S 

1 

Figure  4.15:  Terminal  c  is  in  FIRST(A)  and  a  is  in  FOLLOW(A) 

symbol  a,  since  a  can  be  in  at  most  one  of  FIRST  (a)  and  FlRST(/3),  not  b o t h. 
/?.  This  idea  will 
For  instance,  if  a  is  in  F I R S T ( ^)  choose  the  production  A 
be  explored  when  LL(1)  grammars  are  defined  in  Section  4.4.3. 

Define  FOLLOW(A),  for  nonterminal  A,  to  be  the  set  of terminals  a  t h at  can 
appear  immediately  to  the  right  of  A  in  some  sentential  form;  t h at  is,  the  set 
aAa/3,  for 
of  terminals  a  such  t h at  there  exists  a  derivation  of  t he  form  S 
some  a  a nd  ft,  as  in  Fig.  4.15.  Note  t h at  there  may  have  been  symbols  between 
A  and  a,  at  some  time  during  the  derivation,  but  if  so,  they  derived  e  and 
disappeared.  In  addition,  if  A  can  be  the  rightmost  symbol  in  some  sentential 
form,  then  $  is  in  FOLLOW(A);  recall  t h at  $  is  a  special  "endmarker"  symbol 
t h at  is  assumed  not  to  be  a  symbol  of  any  grammar. 

To  compute  FIRST(X)  for  all  g r a m m ar  symbols  X,  apply  t he  following  rules 

until  no  more  terminals  or  e  can  be  added  to  any  FIRST  set. 

1.  If  X  is  a  terminal,  then  FIRST(AT)  =  {X}. 

2.  If X  is  a nonterminal  and  X  —>  Y{Y2  •  •  • Yfc  is  a production for  some  k  >  1, 
then  place  a  in  F I R S T ( X)  if for  some  i,  a  is  in  FIRST(1^),  and  e  is  in  all  of 
F l R S T ( Y i ) , . ..  ,  F I R S T ( F i _ i );  t h at  is,  Yx  •  •  •  Yi-i  4  e.  If  e  is  in  FIRST 
for  all  j  =  1 , 2 , . ..  , k,  then  add  e  to  F I R S T ( X ).  For  example,  everything 
in  FIRST(Yi)  is  surely  in  F I R S T ( X ).  If  Y±  does  not  derive  e,  then  we  add 
nothing  more  to  F I R S T ( X ),  b ut  if  Yi  4  e,  then  we  add  F I R S T ( F2),  and 
so  on. 

3.  If  X  ->  e  is  a  production,  then  add  e  to  F I R S T ( X ). 

Now,  we  can  compute  F I R ST  for  any  string  XXX2  •  •  •  Xn  as  follows.  Add  to 

F l R S T ( X i X2  • ••Xn)  all  non-e  symbols  of F I R S T ( X I ).  Also  add  t he  non-e  sym 
bols  of FIRST(AT2),  if  e  is  in  F l R S T ( X i );  the  non-e  symbols  of  F I R S T ( X3),  if  e  is 
in  F I R S T ( X L)  and  F I R S T ( X2);  and  so  on.  Finally,  add  e  to  FIRST(A:iX2  •  •  •  Xn) 
if, 

in  F I R ST (Xj). 

for  a l H,  e 

is 

To  compute  FOLLOW(A)  for  all  nonterminals  A,  apply  the  following  rules 

until  nothing  can  be  added  to  any  FOLLOW  set. 

1.  Place  $  in  F O L L O W ( 5 ),  where  S  is  the  start  symbol,  and  $  is  the  input 

right  endmarker. 

222 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

2.  If  there  is  a  production  A 

aB/3,  then  everything  in  FIRST(/3)  except  e 

is  in  F O L L O W ( 5 ). 

3.  If  there  is  a  production  A 

aB,  or  a  production  A  ->  aB/3,  where 

F I R S T ( ^)  contains  e,  then  everything  in  F O L L O W( A)  is  in  F O L L O W( J B ). 

E x a m p le  4 . 3 0:  Consider  again  t he  non-left-recursive  g r a m m ar  (4.28).  Then: 

1.  F I R S T ( F)  =  F I R S T ( T)  =  F I R S T ( E)  =  { ( , i d }.  To  see  why,  note  t h at  t he 
two  productions  for  F  have  bodies  t h at  start  with  these  two  terminal 
symbols,  id  and  t he  left  parenthesis.  T  has  only  one  production,  and  its 
body  starts  with  F.  Since  F  does  not  derive  e,  F I R S T ( T)  must  be  t he 
same  as  F I R ST (F).  T he  same  a r g u m e nt  covers  F I R ST (E). 

2.  F I R S T ( E ')  =  { +, e}.  T he  reason  is  t h at  one  of the  two  productions  for  E' 
has  a  body  t h at  begins  with  terminal  +,  and  t he  other's  body  is  e.  When 
ever  a  nonterminal  derives  e,  we  place  e  in  F I R ST  for  t h at  nonterminal. 

3.  F I R S T ( T ')  =  {*,e}.  The  reasoning  is  analogous  to  t h at  for  F I R S T ( E ' )-

4.  F O L L O W ( E)  =  F O L L O W ( E ')  =  { ) , $ }. 

Since  E  is  the  start  symbol, 
F O L L O W ( E)  must  contain  $.  The production  body  (  E  )  explains  why  the 
right  parenthesis  is  in  F O L L O W ( E ).  For  E',  note  t h at  this  nonterminal 
appears  only  at  t he  ends  of bodies  of E-productions.  Thus,  F O L L O W ( E ') 
must  be  the  same  as  F O L L O W ( E ). 

5.  F O L L O W ( T)  =  F O L L O W ( T ')  =  { + , ),  $}.  Notice  t h at  T  appears  in  bodies 
only  followed  by  E'.  Thus,  everything  except  e  t h at  is  in  F I R S T ( E ')  must 
be  in  F O L L O W ( T );  t h at  explains  the  symbol  +.  However,  since  F I R S T ( E ') 
contains  e  (i.e.,  E'  4*  e),  and  E'  is  t he  entire  string  following  T  in  the 
bodies  of t he  E-productions,  everything  in  F O L L O W ( E)  must  also  be  in 
F O L L O W ( T ).  T h at  explains  the  symbols  $  and  the  right  parenthesis.  As 
for  T",  since  it  appears  only  at  the  ends  of  t he  T-productions,  it  must  be 
t h at  F O L L O W ( T ')  =  F O L L O W ( T ). 

6.  F O L L O W ( F)  =  { + , * , ) , $ }.  T he  reasoning  is  analogous  to  t h at  for  T  in 

point  (5). 

• 

4.4.3  LL(1)  Grammars 

Predictive  parsers,  t h at  is,  recursive-descent  parsers  needing  no  backtracking, 
can  be  constructed  for  a  class  of grammars  called  LL(1).  T he  first  "L"  in  LL(1) 
stands  for  scanning  the  input  from  left  to  right,  t he  second  "L"  for  producing 
a  leftmost  derivation,  and  the  " 1"  for  using  one  input  symbol  of  lookahead  at 
each  step  to  make  parsing  action  decisions. 

4.4. 

TOP-DOWN  PARSING 

223 

Transition  Diagrams  for  Predictive  Parsers 

Transition  diagrams  are  useful  for  visualizing  predictive  parsers.  For  exam 
ple,  t he  transition  diagrams  for  nonterminals  E  and  E'  of  g r a m m ar  (4.28) 
appear  in  Fig.  4.16(a).  To  construct  the  transition  diagram  from  a  gram 
mar,  first  eliminate  left  recursion  and  then  left  factor  t he  grammar.  Then, 
for  each  nonterminal  A, 

1.  Create  an  initial  and  final  (return)  state. 

2.  For  each  production  A  ->•  X\X2  •  •  •  Xk,  create  a  p a th  from  the  initial 
If  A  -»  e,  the 

to  t he  final  state,  with  edges  labeled  X\,X2,  •  •.  , 
p a th  is  an  edge  labeled  e. 

Transition  diagrams  for  predictive  parsers  differ  from  those  for  lexical 
analyzers.  Parsers  have  one  diagram  for  each  nonterminal.  T he  labels  of 
edges  can  be  tokens  or  nonterminals.  A  transition  on  a  token  (terminal) 
means  t h at  we  take  t h at  transition  if  t h at  token  is  the  next  input  symbol. 
A  transition  on  a  nonterminal  A  is  a  call  of  the  procedure  for  A. 

W i th  an  LL(1)  grammar,  the  ambiguity  of  whether  or  not  to  take  an 

e-edge  can  be  resolved  by  making  e-transitions  the  default  choice. 

Transition  diagrams  can  be  simplified,  provided  the  sequence  of gram 
m ar  symbols  along  paths  is  preserved.  We  may  also  substitute  the  dia 
gram  for  a  nonterminal  A  in  place  of  an  edge  labeled  A.  T he  diagrams  in 
Fig.  4.16(a)  and  (b)  are  equivalent:  if we  trace  paths  from  E  to  an  accept 
ing  state  and  substitute  for  E',  then,  in  both  sets  of diagrams,  the  g r a m m ar 
symbols  along  the  p a t hs  make  up  strings  of the  form  T + T-\ 
h T.  The 
diagram  in  (b)  can  be  obtained  from  (a)  by  transformations  akin  to  those 
in  Section  2.5.4,  where  we  used  tail-recursion  removal  and  substitution  of 
procedure  bodies  to  optimize  the  procedure  for  a  nonterminal. 

T he  class  of  LL(1)  grammars  is  rich  enough  to  cover  most  programming 
constructs,  although  care  is  needed  in  writing  a  suitable  g r a m m ar  for  the  source 
language.  For  example,  no  left-recursive  or  ambiguous  g r a m m ar  can  be  LL(1). 
A  g r a m m ar  G  is  LL(1)  if  a nd  only  if  whenever  A  —>  a  |  f3  sere  two  distinct 

productions  of  G,  the  following  conditions  hold: 

1.  For  no  terminal  a  do  both  a  and  f3  derive  strings  beginning  with  a. 

2.  At  most  one  of  a  and  (3  can  derive  the  empty  string. 

3.  If  j3  4  e,  then  a  does  not  derive  any  string  beginning  with  a  terminal 
in  FOLLOW  (A).  Likewise,  if  a  e,  then  (3  does  not  derive  any  string 
beginning  with  a  terminal  in  FOLLOW(A). 

224 

CHAPTER  4. 

SYNTAX  ANALYSIS 

Figure  4.16:  Transition  diagrams  for  nonterminals  E  and  E'  of  g r a m m ar  4.28 

T he  first  two  conditions  are  equivalent  to  the  statement  t h at  FIRST  (a)  and 
FIRST(/?)  are  disjoint  sets.  T he  third  condition  is  equivalent  to  stating  t h at  if 
e  is  in  FIRST(/3),  then  FIRST  (a)  and  FOLLOW(A)  are  disjoint  sets,  and  likewise 
if  e  is  in  FIRST (a). 

Predictive  parsers  can  be  constructed  for  LL(1)  g r a m m a rs  since  the  proper 
production  to  apply  for  a  nonterminal  can  be  selected  by  looking  only  at  the 
current  input  symbol.  Flow-of-control  constructs,  with  their  distinguishing  key 
words,  generally  satisfy  the  LL(1)  constraints.  For  instance,  if  we  have  the 
productions 

stmt 

if  (  expr  )  stmt  else  stmt 

-> 
|  w h i le  (  expr )  stmt 
| 

{  stmtJist  } 

then  the  keywords  if,  w h i l e,  and  the  symbol  {  tell  us  which  alternative  is  the 
only  one  t h at  could  possibly  succeed  if  we  are  to  find  a  statement. 

T he  next  algorithm  collects  the  information  from  FIRST  and  FOLLOW  sets 
into  a  predictive  parsing  table  M[A,a],  a  two-dimensional  array,  where  A  is  a 
nonterminal,  and  a  is  a  terminal  or  t he  symbol  $,  t he  input  endmarker.  T he 
algorithm  is  based  on  the  following  idea:  the  production  A  —>  a  is  chosen  if 
the  next  input  symbol  a  is  in  FIRST  ( a ).  T he  only  complication  occurs  when 
a  =  e  or,  more  generally,  a  ^  e.  In  this  case,  we  should  again  choose  A  -»  a, 
if the  current  input  symbol  is  in  FOLLOW(A),  or  if t he  $  on  t he  input  has  been 
reached  and  $  is  in  FOLLOW (A). 

A l g o r i t hm  4 . 3 1:  Construction  of  a  predictive  parsing  table. 

I N P U T:  G r a m m ar  G. 

O U T P U T:  Parsing  table  M. 

M E T H O D:  For  each  production  A  ->  a  of  the  grammar,  do  the  following: 

1.  For  each  terminal  a  in  FIRST(A),  add  A  -4  a  to  M[A, a]. 

2.  If  e  is  in  F l R S T ( a ),  then  for  each  terminal  6  in  FOLLOW(A),  add  A  -»•  a 
to  M[A,b].  If  e  is  in  FIRST  (a)  and  $  is  in  FOLLOW(A),  add  A  -4  a  to 
M[A,  $]  as  well. 

4.4. 

TOP-DOWN  PARSING 

225 

If,  after  performing  t he  above,  there  is  no  production  at  all  in  M[A,  a],  then 
set  M[A,  a]  to  e r r or  (which  we  normally  represent  by  an  empty  entry  in  t he 
table). 

• 

E x a m p le  4 . 3 2:  For  the  expression  g r a m m ar  (4.28),  Algorithm  4.31  produces 
t he  parsing  table  in  Fig.  4.17.  Blanks  are  error  entries;  nonblanks  indicate  a 
production  with  which  to  expand  a  nonterminal. 

N ON  -
T E R M I N AL 

E 
E' 

T 
r 
F 

id 
E  -» TE' 

T  -»  FT' 

F -¥  id 

I N P UT  S Y M B OL 

+ 

* 

E' -»• +TE' 

( 
E  -»•  T E' 

T  ->•  F T' 

) 

$ 

£7' ->• e 

T'  -»  e 

T' -»• *FT' 

T' —>• e  T'  ->  e 

F  -»  (F) 

Figure  4.17:  Parsing  table  M  for  Example  4.32 

Consider  production  E  ->  T E '.  Since 

F I R S T ( T E ')  =  F I R S T ( T)  = 

{ ( , i d} 

this  production  is  added  to  M[E,{]  and  M[E,  id].  Production  E'  ->•  + T F/  is 
added  to  M[E',+]  since  F I R S T ( + T E ')  =  { + }.  Since  F O L L O W ^ ')  =  { ) , $ }, 
production  E'  -+  e  is  added  to  M[E',)]  and  M[E',  $]. 

• 

Algorithm  4.31  can  be  applied  to  any  g r a m m ar  G  to  produce  a  parsing  table 
M.  For  every  LL(1)  grammar,  each  parsing-table  entry  uniquely  identifies  a 
production  or  signals  an  error.  For  some  grammars,  however,  M  may  have 
some  entries  t h at  are  multiply  defined.  For  example,  if  G  is  left-recursive  or 
ambiguous,  then  M  will  have  at  least  one  multiply  defined  entry.  Although  left-
recursion  elimination  and  left  factoring  are  easy  to  do,  there  are  some  g r a m m a rs 
for  which  no  amount  of  alteration  will  produce  an  LL(1)  g r a m m a r. 

T he  language  in  the  following  example  has  no  LL(1)  g r a m m ar  at  all. 

E x a m p le  4 . 3 3:  T he  following  grammar,  which  abstracts  the  dangling-else 
problem,  is  repeated  here  from  Example  4.22: 

S 
S' 
E 

iEtSS1  |  a 

->  eS\  e 
-»  b 

T he  parsing  table  for  this  g r a m m ar  appears  in  Fig.  4.18.  T he  entry  for  M[S',  e) 
contains  both  S'  —>  eS  and  S'  —>  e. 

T he  g r a m m ar  is  ambiguous  a nd  t he  ambiguity  is  manifested  by  a  choice  in 
what  production  to  use  when  an  e  (else)  is  seen.  We  can  resolve  this  ambiguity 

226 

NON 

-

T E R M I N AL 

S 

S' 

E 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

IN P UT  SY M B OL 

a 

b 

e 

i 

t 

$ 

S  ->•  a 

S 

iEtSS' 

S' 

S' 

->eS 

E->b 

Figure  4.18:  Parsing  table  M  for  Example  4.33 

by  choosing  S'  -»  eS.  This  choice  corresponds  to  associating  an  e l se  with  the 
closest  previous  t h e n.  Note  t h at  t he  choice  S'  ->  e  would  prevent  e  from  ever 
being  p ut  on  t he  stack  or  removed  from  t he  input,  and  is  surely  wrong. 

• 

4.4.4  Nonrecursive  Predictive  Parsing 

A  nonrecursive  predictive  parser  can  be  built  by  maintaining  a  stack  explicitly, 
rather  t h an  implicitly  via  recursive  calls.  The  parser  mimics  a  leftmost  deriva 
If  w  is  the  input  t h at  has  been  matched  so  far,  then  t he  stack  holds  a 
tion. 
sequence  of  grammar  symbols  a  such  t h at 

S 

wd 

T he  table-driven  parser  in  Fig.  4.19  has  an  input  buffer,  a  stack  containing  a 
sequence  of  g r a m m ar  symbols,  a  parsing  table  constructed  by  Algorithm  4.31, 
and  an  output  stream.  The  input  buffer  contains  t he  string  to  be  parsed, 
followed  by  t he  endmarker  $.  We  reuse  t he  symbol  $  to  m a rk  t he  b o t t om  of t he 
stack,  which  initially  contains  the  start  symbol  of  the  g r a m m ar  on  top  of  $. 

The  parser  is  controlled  by  a  program  t h at  considers  X,  the  symbol  on  t op 
of the  stack,  and  a,  t he  current  input  symbol.  If  X  is  a  nonterminal,  the  parser 
chooses  an  X-production  by  consulting  entry  M[X,  a]  of  t he  parsing  table  M. 
(Additional  code  could  be  executed  here,  for  example,  code  to  construct  a  node 
in  a  parse  tree.)  Otherwise,  it  checks  for  a  match  between  t he  terminal  X  and 
current  input  symbol  a. 

T he  behavior  of  the  parser  can  be  described  in  terms  of  its  configurations, 
which  give  t he  stack  contents  and  the  remaining  input.  T he  next  algorithm 
describes  how  configurations  are  manipulated. 

A l g o r i t hm  4 . 3 4:  Table-driven  predictive  parsing. 

I N P U T:  A  string  w  and  a  parsing  table  M  for  g r a m m ar  G. 

O U T P U T:  If  w  is  in  L(G),  a  leftmost  derivation  of  w;  otherwise,  an  error 
indication. 

4.4. 

TOP-DOWN  PARSING 

227 

Input 

a  + 

b 

$ 

Stack 

X 

Y 

Z 

Predictive 
Parsing 
Program 

Parsing 
Table 
M 

Output 

Figure  4.19:  Model  of  a  table-driven  predictive  parser 

M E T H O D:  Initially,  the  parser  is  in  a  configuration  with  w$  in  the  input  buffer 
and  t he  start  symbol  S  of  G  on  top  of  the  stack,  above  $.  T he  program  in 
Fig.  4.20  uses  the  predictive  parsing  table  M  to  produce  a  predictive  parse  for 
the  input. 

• 

set  ip  to  point  to  the  first  symbol  of  w; 
set  X  to  the  top  stack  symbol; 
w h i le  (  X 

$  )  {  /*  stack  is  not  empty  */ 
if  (  X  is  a  )  pop  the  stack  and  advance  ip; 
e l se  if  (  X  is  a  terminal  )  errorQ; 
e l se  if  (  M[X,a]  is  an  error  entry  )  errorQ; 
e l se  if  (  M[X,a]  =  X  ->  YXY2  •••Yk)  { 

output  the  production  X  ->  Y\ Y2  •  •  •  Yk; 
pop  the  stack; 
push  Yk,  Y f c - i , . ..  ,Yi  onto  t he  stack,  with  Y\  on  top; 

} 
set  X  to  the  top  stack  symbol; 

} 

Figure  4.20:  Predictive  parsing  algorithm 

E x a m p le  4 . 35  :  Consider  grammar  (4.28);  we  have  already  seen  its  the  parsing 
table  in  Fig.  4.17.  On  input  id  +  id  *  id,  t he  nonrecursive  predictive  parser 
of  Algorithm  4.34  makes  the  sequence  of  moves  in  Fig.  4.21.  These  moves 
correspond  to  a  leftmost  derivation  (see  Fig.  4.12  for  the  full  derivation): 

E 

TE' 

FT'E'  =» 

id T'E' 

id  E' 

id  + TE'  =>•  •  •  • 

Im 

Im 

Im 

Im 

Im 

Im 

228 

CHAPTER  4. 

SYNTAX  ANALYSIS 

MA T C H ED 

ST A CK 

IN P UT 

AC T I ON 

E% 
TE'% 
FT'E'% 
id  T'E'% 
T'E'% 
E'% 
+  TE'% 
TE'% 
FT'E'% 
id  T'E'% 
T'E'% 
*  FT'E'% 
FT'E'% 
id  T'E'% 
T'E'% 
E'% 

% 

id  +  id  *  id$ 
id  +  id  *  id$ 
id  +  id  *  id$ 
id  +  id  *  id$ 

output  E  ->  TE' 
output  T  -+  FT' 
output  F  ->  id 

+  id  *  id$  match  id 
+  id  *  id$ 
+  id  *  id$ 

output  T"  ->  e 
output  E'  -+  +  TE' 

id  *  id$  match  + 
id  *  id$ 
output  T 
id  *  id$ 
output  F  -»  id 

FT' 

* i d$  match  id 
* i d$ 

output  T"  -»  *  FT' 

id$  match  * 
id$ 

output  F  -»  id 

$  match  id 
$ 
$ 

o u t p ut  T'  -+  e 
output  E'  -+  e 

id 
id 
id 
id  + 
id  + 
id  + 
id  +  id 
id  +  id 
id  +  id  * 
id  +  id  * 
id  +  id  *  id 
id  +  id  *  id 
id  +  id  *  id 

Figure  4.21:  Moves  made  by  a  predictive  parser  on  input  id  +  id  *  id 

Note  t h at  t he  sentential  forms  in  this  derivation  correspond  to  t he  input  t h at 
has  already  been  matched  (in  column  M A T C H E D)  followed  by  the  stack  contents. 
T he  matched  input  is  shown  only  to  highlight  t he  correspondence.  For  t he  same 
reason,  t he  top  of t he  stack  is  to  the  left;  when  we  consider  b o t t o m - up  parsing, 
it  will  be  more  natural  to  show  t he  top  of  t he  stack  to  t he  right.  T he  input 
• 
pointer  points  to  the  leftmost  symbol  of  the  string  in  t he  I N P UT  column. 

4.4.5  Error  Recovery  in  Predictive  Parsing 

This  discussion  of error  recovery  refers  to  t he  stack  of  a  table-driven  predictive 
parser,  since  it  makes  explicit  the  terminals  and  nonterminals  t h at  the  parser 
hopes  to  match  with  t he  remainder  of  the  input;  t he  techniques  can  also  be 
used  with  recursive-descent  parsing. 

An  error  is  detected  during  predictive  parsing  when  the  terminal  on  t op  of 
the  stack  does  not  match  the  next  input  symbol  or  when  nonterminal  A  is  on 
top  of  the  stack,  a  is  t he  next  input  symbol,  and  M[A, a]  is  error  (i.e.,  t he 
parsing-table  entry  is  empty). 

P a n ic  M o de 

Panic-mode  error  recovery  is  based  on  t he  idea  of  skipping  symbols  on  t he 
Its 
t he  input  until  a  token  in  a  selected  set  of  synchronizing  tokens  appears. 

4.4. 

TOP-DOWN  PARSING 

229 

effectiveness  depends  on  the  choice  of  synchronizing  set.  The  sets  should  be 
chosen  so  t h at  the  parser  recovers  quickly  from  errors  t h at  are  likely  to  occur 
in  practice.  Some  heuristics  are  as  follows: 

1.  As  a  starting  point,  place  all  symbols  in  FOLLOW(A)  into  the  synchro 
nizing  set  for  nonterminal  A. 
If  we  skip  tokens  until  an  element  of 
FOLLOW(A)  is  seen  and  pop  A  from  t he  stack,  it  is  likely  t h at  parsing 
can  continue. 

2.  It  is  not  enough  to  use  FOLLOW(A)  as  t he  synchronizing  set  for  A.  For 
example,  if  semicolons  terminate  statements,  as  in  C,  then  keywords  t h at 
begin  statements  may  not  appear  in  the  FOLLOW  set  of  the  nontermi 
nal  representing  expressions.  A  missing  semicolon  after  an  assignment 
may  therefore  result  in  t he  keyword  beginning  t he  next  statement  be 
ing  skipped.  Often,  there  is  a  hierarchical  structure  on  constructs  in  a 
language;  for  example,  expressions  appear  within  statements,  which  ap 
pear  within  blocks,  and  so  on.  We  can  add  to  the  synchronizing  set  of  a 
lower-level  construct  t he  symbols  t h at  begin  higher-level  constructs.  For 
example,  we  might  add  keywords  t h at  begin  statements  to  the  synchro 
nizing  sets  for  t he  nonterminals  generating  expressions. 

3.  If  we  add  symbols  in  FIRST(A)  to  t he  synchronizing  set  for  nonterminal 
A,  then  it  may  be  possible  to  resume  parsing  according  to  A  if  a  symbol 
in  FIRST  (A)  appears  in  the  input. 

4.  If  a  nonterminal  can  generate  the  empty  string,  then  the  production  de 

riving  e  can  be  used  as  a  default.  Doing  so  may  postpone  some  error 
detection,  b ut  cannot  cause  an  error  to  be  missed.  This  approach  reduces 
t he  number  of  nonterminals  t h at  have  to  be  considered  during  error  re 
covery. 

5.  If  a  terminal  on  t op  of  t he  stack  cannot  be  matched,  a  simple  idea  is  to 
pop  the  terminal,  issue  a  message  saying  t h at  the  terminal  was  inserted, 
and  continue  parsing.  In  effect,  this  approach  takes  the  synchronizing  set 
of  a  token  to  consist  of  all  other  tokens. 

E x a m p le  4 . 3 6:  Using  FIRST  and  FOLLOW  symbols  as  synchronizing  tokens 
works  reasonably  well  when  expressions  are  parsed  according  to  t he  usual  gram 
m ar  (4.28).  T he  parsing  table  for  this  g r a m m ar  in  Fig.  4.17  is  repeated  in 
indicating  synchronizing  tokens  obtained  from  the 
Fig.  4.22,  with  "synch" 
FOLLOW  set  of  the  nonterminal  in  question.  T he  FOLLOW  sets  for  t he  non 
terminals  are  obtained  from  Example  4.30. 

T he  table  in  Fig.  4.22  is  to  be  used  as  follows.  If  the  parser  looks  up  entry 
M[A,a]  and  finds  t h at  it  is  blank,  then  the  input  symbol  a  is  skipped.  If  t he 
entry  is  "synch,"  then  the  nonterminal  on  top  of  t he  stack  is  popped  in  an 
a t t e m pt  to  resume  parsing.  If  a  token  on  top  of  the  stack  does  not  m a t ch  the 
input  symbol,  then  we  pop  the  token  from  the  stack,  as  mentioned  above. 

230 

CHAPTER  4. 

SYNTAX  ANALYSIS 

N ON  -
T E R M I N AL 

E 

E' 

T 

T' 

F 

I N P UT  S Y M B OL 

id 

E 

TE' 

+ 

* 

E  -»  +TE' 

( 
E  ->  T E' 

) 
synch 

$ 

synch 

E 

e  E  -ye 

T ->  FT' 

synch 

T  -»•  F T' 

synch 

synch 

T'  - >e 

T'  -»  *FT' 

T' -*  e  T'  -v  e 

F  ->  id 

synch 

synch 

F  ->  ( F) 

synch 

synch 

Figure  4.22:  Synchronizing  tokens  added  to  the  parsing  table  of  Fig.  4.17 

On  the  erroneous  i n p u t)  id  *  + id,  the  parser  and  error  recovery  mechanism 

of  Fig.  4.22  behave  as  in  Fig.  4.23. 

• 

ST A CK 

IN P UT 

RE M A RK 

error,  skip  ) 

id 

is 

in  F I R S T ( E) 

error,  M[F,  +]  =  synch 
F  has  been  popped 

E% 
E% 
TE'% 
FT'E'  % 
id  T'E'% 
T'E'  % 
*  FT'E'  % 
FT'E'  % 
T'E'  % 
E'% 
+  TE'% 
TE'% 
FT'E'  % 
id  T'E'  % 
T'E'  % 
E'% 
$ 

)  id  *  +  id  $ 
id  *  +  id  $ 
id  *  +  id  $ 
id  *  +  id  $ 
id  *  +  id  $ 
*  +  i d$ 
*  +  i d$ 
+  i d$ 
+  i d$ 
+  i d$ 
+  i d$ 
i d$ 
i d$ 
i d$ 
$ 
$ 
$ 

Figure  4.23:  Parsing  and  error  recovery  moves  m a de  by  a  predictive  parser 

T he  above  discussion  of panic-mode  recovery  does  not  address  t he  important 
issue  of  error  messages.  T he  compiler  designer  must  supply  informative  error 
messages  t h at  not  only  describe  the  error,  they  must  draw  attention  to  where 
t he  error  was  discovered. 

4.4. 

TOP-DOWN  PARSING 

231 

P h r a s e - l e v el  R e c o v e ry 

Phrase-level  error  recovery  is  implemented  by  filling  in  the  blank  entries  in 
the  predictive  parsing  table  with  pointers  to  error  routines.  These  routines 
may  change,  insert,  or  delete  symbols  on  t he  input  and  issue  appropriate  error 
messages.  They  may  also  pop  from  the  stack.  Alteration  of stack  symbols  or  the 
pushing  of new  symbols  onto  the  stack  is  questionable  for  several  reasons.  First, 
the  steps  carried  out  by  the  parser  might  then  not  correspond  to  t he  derivation 
of  any  word  in  t he  language  at  all.  Second,  we  must  ensure  t h at  there  is  no 
possibility  of  an  infinite  loop.  Checking  t h at  any  recovery  action  eventually 
results  in  an  input  symbol  being  consumed  (or  the  stack  being  shortened  if  the 
end  of the  input  has  been  reached)  is  a  good  way  to  protect  against  such  loops. 

4.4.6  Exercises  for  Section  4.4 

E x e r c i se  4 . 4 . 1:  For  each  of the  following  grammars,  devise  predictive  parsers 
and  show  t he  parsing  tables.  You  may  left-factor  and/of  eliminate  left-recursion 
from  your  grammars  first. 

a)  T he  g r a m m ar  of  Exercise  4.2.2(a). 

b)  The  g r a m m ar  of  Exercise  4.2.2(b). 

c)  T he  grammar  of  Exercise  4.2.2(c). 

d)  T he  grammar  of  Exercise  4.2.2(d). 

e)  T he  g r a m m ar  of  Exercise  4.2.2(e). 

f)  T he  grammar  of  Exercise  4.2.2(g). 

!!  E x e r c i se  4 . 4 . 2:  Is  it  possible,  by  modifying  the  grammar  in  any  way,  to  con 

struct  a  predictive  parser  for  the  language  of  Exercise  4.2.1  (postfix  expressions 
with  operand  a)? 

E x e r c i se  4 . 4 . 3:  Compute  FIRST  and  FOLLOW  for  the  grammar  of  Exercise 
4.2.1. 

E x e r c i se  4 . 4 . 4:  Compute  FIRST  and  FOLLOW  for  each  of  the  grammars  of 
Exercise  4.2.2. 

-»  a  S  a  |  a  a  generates  all  even-length 
E x e r c i se  4 . 4 . 5:  T he  grammar  S 
strings  of  a's.  We  can  devise  a  recursive-descent  parser  with  backtrack  for  this 
grammar.  If  we  choose  to  expand  by  production  S  ->•  a  a  first,  then  we  shall 
only  recognize  the  string  aa.  Thus,  any  reasonable  recursive-descent  parser  will 
try  S 

->  a  S  a  first. 

a)  Show  t h at  this  recursive-descent  parser  recognizes  inputs  aa,  aaaa,  and 

aaaaaaaa,  but  not  aaaaaa. 

232 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

!!  b)  W h at  language  does  this  recursive-descent  parser  recognize? 

T he  following  exercises  are  useful  steps  in  the  construction  of  a  "Chomsky 
Normal  Form"  grammar  from  arbitrary  grammars,  as  defined  in  Exercise  4.4.8. 

!  E x e r c i se  4 . 4 . 6:  A  g r a m m ar  is  e-free  if  no  production  body  is  e  (called  an 

e-productiori). 

a)  Give  an  algorithm  to  convert  any  g r a m m ar  into  an  e-free  g r a m m ar  t h at 
generates  t he  same  language  (with  t he  possible  exception  of  the  empty 
string  —  no  e-free  grammar  can  generate  e). 

b)  Apply  your  algorithm  to  t he  grammar  S 

aSbS  \  bSaS  |  e.  Hint:  First 
find  all  t he  nonterminals  t h at  are  nullable,  meaning  t h at  they  generate  e, 
perhaps  by  a  long  derivation. 

!  E x e r c i se  4 . 4 . 7:  A  single  production  is  a  production  whose  body  is  a  single 

nonterminal,  i.e.,  a  production  of  t he  form  A  ->  A. 

a)  Give  an  algorithm  to  convert  any  grammar  into  an  e-free  grammar,  with 
no  single  productions,  t h at  generates  the  same  language  (with  t he  possible 
exception  of  the  empty  string)  Hint:  First  eliminate  e-productions,  and 
then  find  for  which  pairs  of  nonterminals  A  and  B  does  A  =4»  B  by  a 
sequence  of  single  productions. 

b)  Apply  your  algorithm  to  t he  g r a m m ar  (4.1)  in  Section  4.1.2. 

c)  Show  t h a t,  as  a  consequence  of  part  (a),  we  can  convert  a  g r a m m ar  into 
an  equivalent  g r a m m ar  t h at  has  no  cycles  (derivations  of  one  or  more 
steps  in  which  A  ^  A  for  some  nonterminal  A). 

!!  E x e r c i se  4 . 4 . 8:  A  g r a m m ar  is  said  to  be  in  Chomsky  Normal  Form  (CNF)  if 
every  production  is  either  of  the  form  A  ->•  BC  or  of  t he  form  A  ->•  a,  where 
A,  B,  and  C  are  nonterminals,  and  a  is  a  terminal.  Show  how  to  convert 
any  grammar  into  a  C NF  grammar  for  the  same  language  (with  the  possible 
exception  of  the  empty  string  —  no  C NF  g r a m m ar  can  generate  e). 

!  E x e r c i se  4 . 4 . 9:  Every  language  t h at  has  a  context-free  g r a m m ar  can  be  rec 
ognized  in  at  most  0 ( n3)  time  for  strings  of  length  n.  A  simple  way  to  do  so, 
called  t he  Cocke-Younger-Kasami  (or  CYK)  algorithm  is  based  on  dynamic  pro 
gramming.  T h at  is,  given  a  string  axa2  •  •  • a„,  we  construct  an  n-by-n  table  T 
such  t h at  Tij  is  the  set  of  nonterminals  t h at  generate  the  substring  a{ai+1  •••aj. 
If  the  underlying  grammar  is  in  C NF  (see  Exercise  4.4.8),  then  one  table  entry 
can  be  filled  in  in  O(n)  time,  provided  we  fill  the  entries  in  the  proper  order: 
lowest  value  ofj-i  first.  Write  an  algorithm  t h at  correctly  fills  in  the  entries 
of  the  table,  and  show  t h at  your  algorithm  takes  0 ( n3)  time.  Having  filled  in 
t he  table,  how  do  you  determine  whether  axa2  •  •  •  an  is  in  the  language? 

4.5. 

BOTTOM-UP  PARSING 

233 

!  E x e r c i se  4 . 4 . 1 0:  Show  how,  having  filled  in  the  table  as  in  Exercise  4.4.9, 
we  can  in  0(n) 
the 
table  so  it  records,  for  each  nonterminal  A  in  each  table  entry  Tij:  some  pair  of 
nonterminals  in  other  table  entries  t h at  justified  putting  A  in  Tij. 

time  recover  a  parse  tree  for  a\a2---an.  Hint:  modify 

!  E x e r c i se  4 . 4 . 1 1:  Modify  your  algorithm  of  Exercise  4.4.9  so  t h at  it  will  find, 
for  any  string,  the  smallest  number  of  insert,  delete,  and  m u t a te  errors  (each 
error  a  single  character)  needed  to  t u rn  the  string  into  a  string  in  the  language 
of  t he  underlying  grammar. 

if  e  t h en  stmt  stmtTail 

stmt 

stmtTail 

w h i le  e  do  stmt 
b e g in  list  e nd 

—>• 
| 
| 
I 
-» 
I 
—>  stmt  UstTail 

e l se  stmt 
e 

8 

list 
list  Tail  —> 
-¥ 

;  list 
e 

Figure  4.24:  A  grammar  for  certain  kinds  of  statements 

!  E x e r c i se  4 . 4 . 1 2:  In  Fig.  4.24  is  a  grammar  for  certain  statements.  You  may 
take  e  and  s  to  be  terminals  standing  for  conditional  expressions  and  "other 
statements,"  respectively. 
If  we  resolve  the  conflict  regarding  expansion  of 
t he  optional  "else"  (nonterminal  stmtTail)  by  preferring  to  consume  an  e l se 
from  t he  input  whenever  we  see  one,  we  can  build  a  predictive  parser  for  this 
grammar.  Using  the  idea  of  synchronizing  symbols  described  in  Section  4.4.5: 

a)  Build  an  error-correcting  predictive  parsing  table  for  the  grammar. 

b)  Show  the  behavior  of  your  parser  on  the  following  inputs: 

if  e  t h en  s  ;  if  e  t h en  s  e nd 

(i) 
( M)  w h i le  e  do  b e g in  s  ;  if e  t h en  s  ;  e nd 

4.5  Bottom-Up  Parsing 

A  b o t t o m - up  parse  corresponds  to  the  construction  of  a  parse  tree  for  an  input 
string  beginning  at  t he  leaves  (the  bottom)  and  working  up  towards  the  root 
(the  t o p ).  It  is  convenient  to  describe  parsing  as  the  process  of  building  parse 
trees,  although  a  front  end  may  in  fact  carry  out  a  translation  directly  without 
building  an  explicit  tree.  T he  sequence  of tree  snapshots  in  Fig.  4.25  illustrates 

234 

id  * 

id 

CHAPTER  4. 

SYNTAX  ANALYSIS 

id 

F  * 
I 
id 

id 

T  * 
I 
F 
I 
id 

T  *  F 

I  I 
id 
F 
I 
id 

T 
. / l\ 
T  *  F 
I 
F 

id 

I 

id 

Figure  4.25:  A  bottom-up  parse  for  id * id 

E 
I 
T 
/ l\ 
T  *  F 

id 

F 

id 

a  bottom-up  parse  of  the  token  stream  id  *  id,  with  respect  to  the  expression 
grammar  (4.1). 

This  section  introduces  a  general  style  of  bottom-up  parsing  known  as  shift-
reduce  parsing.  T he  largest  class  of grammars  for  which  shift-reduce  parsers  can 
be  built,  the  LR  grammars,  will  be  discussed  in  Sections  4.6  and  4.7.  Although 
it  is  too  much  work  to  build  an  LR  parser  by  hand,  tools  called  automatic  parser 
generators  make  it  easy  to  construct  efficient  LR  parsers  from  suitable  gram 
mars.  T he  concepts  in  this  section  are  helpful  for  writing  suitable  grammars 
to  make  effective  use  of  an  LR  parser  generator.  Algorithms  for  implementing 
parser  generators  appear  in  Section  4.7. 

4.5.1  Reductions 

We  can  think  of  bottom-up  parsing  as  t he  process  of  "reducing"  a  string  w  to 
the  start  symbol  of  the  grammar.  At  each  reduction  step,  a  specific  substring 
matching  the  body  of  a  production  is  replaced  by  the  nonterminal  at  the  head 
of  t h at  production. 

The  key  decisions  during  bottom-up  parsing  are  about  when  to  reduce  and 

about  what  production  to  apply,  as  the  parse  proceeds. 

E x a m p le  4 . 3 7:  T he  snapshots  in  Fig.  4.25  illustrate  a  sequence  of reductions; 
the  grammar  is  the  expression  g r a m m ar  (4.1).  The  reductions  will  be  discussed 
in  terms  of  t he  sequence  of  strings 

i d*  id,  F* i d,  T* i d,  T*F,  T,  E 

T he  strings  in  this  sequence  are  formed  from  t he  roots  of  all  the  subtrees  in  the 
snapshots.  The  sequence  starts  with  the  input  string  i d * i d.  T he  first  reduction 
produces  F*id  by  reducing  the  leftmost  id  to  F,  Using  t he  production  F  ->•  id. 
T he  second  reduction  produces  T  *  id  by  reducing  F  to  T. 

Now,  we  have  a  choice  between  reducing  the  string  T,  which  is  t he  body 
of  E  ->  T,  and  the  string  consisting  of  t he  second  id,  which  is  t he  body  of 
F  -)•  id.  Rather  t h an  reduce  T  to  E,  the  second  id  is  reduced  to  T,  resulting 
in  the  string  T  *  F.  This  string  then  reduces  to  T.  T he  parse  completes  with 
the  reduction  of  T  to  the  start  symbol  E. 

• 

4.5. 

BOTTOM-UP  PARSING 

235 

By  definition,  a  reduction  is  t he  reverse  of  a  step  in  a  derivation  (recall  t h at 
in  a  derivation,  a  nonterminal  in  a  sentential  form  is  replaced  by  the  body  of 
one  of its  productions).  T he  goal  of b o t t o m - up  parsing  is  therefore  to  construct 
a  derivation  in  reverse.  The  following  derivation  corresponds  to  the  parse  in 
Fig.  4.25: 

E  =>  T  =>•  T *  F 

T *  id  =>  F  *  id 

i d*  id 

This  derivation  is  in  fact  a  rightmost  derivation. 

4.5.2  Handle  Pruning 

Bottom-up  parsing  during  a  left-to-right  scan  of  t he  input  constructs  a  right 
most  derivation  in  reverse.  Informally,  a  "handle"  is  a  substring  t h at  matches 
the  body  of  a  production,  and  whose  reduction  represents  one  step  along  t he 
reverse  of  a  rightmost  derivation. 

For  example,  adding  subscripts  to  the  tokens  id  for  clarity,  the  handles 
during  t he  parse  of  i di  *  i d2  according  to  the  expression  g r a m m ar  (4.1)  are  as 
in  Fig.  4.26.  Although  T  is  t he  body  of  t he  production  E  -»  T,  t he  symbol  T  is 
not a handle in the sentential form T * i
would  get  t he  string  E *  i d2,  which  cannot  be  derived  from  the  start  symbol  E. 
Thus,  t he  leftmost  substring  t h at  matches  t he  body  of  some  production  need 
not  be  a  handle. 

2. If T were indeed replaced by E, we 

d

RI G HT  SE N T E N T I AL  FO RM 

HA N D LE 

RE D U C I NG  PR O D U C T I ON 

idi  *  i d2 
F  *  i d2 
T* i d2 

T  *  F 

idi 
F 
i d2 
T *F 

F- ^ id 
T ->  F 
F- » id 
E^T 

* 

F 

Figure  4.26:  Handles  during  a  parse  of  i di  *  i d2 

Formally,  if  S  =3>  aAw 

a(3w,  as  in  Fig.  4.27,  then  production  A  ->  j3 

rm 

rm 

in  the  position  following  a  is  a  handle  of  a(3w.  Alternatively,  a  handle  of  a 
right-sentential  form  7  is  a  production  A  -»  (3  and  a  position  of  7  where  the 
string  (3  may  be  found,  such  t h at  replacing  (3  at  t h at  position  by  A  produces 
the  previous  right-sentential  form  in  a  rightmost  derivation  of  7. 

Notice  t h at  the  string  w  to  the  right  of the  handle  must  contain  only  terminal 
symbols.  For  convenience,  we refer to t he body  j3  rather t h an  A  ->  j3  as  a handle. 
Note  we  say  "a  handle"  rather  t h an  "the  handle,"  because  the  g r a m m ar  could 
be  ambiguous,  with  more  t h an  one  rightmost  derivation  of  a/3w.  If  a  grammar 
is  unambiguous,  then  every  right-sentential  form  of  t he  grammar  has  exactly 
one  handle. 

A  rightmost  derivation  in  reverse  can  be  obtained  by  "handle  pruning." 
T h at  is,  we  start  with  a  string  of  terminals  w  to  be  parsed.  If  ID  is  a  sentence 

236 

CHAPTER  4. 

SYNTAX  ANALYSIS 

S 

ZA 
(3 

a 

w 

Figure  4.27:  A  handle  A  -»  j3  in  the  parse  tree  for  a(3w 

of  the  grammar  at  hand,  then  let  w  =  jn,  where  7n  is  the  n th  right-sentential 
form  of  some  as  yet  unknown  rightmost  derivation 

S  =  70  =>  71 

72 

•  •  • 

7 n -l 

In  =  W 

rm 

rm 

rm 

rm 

rm 

To  reconstruct  this  derivation  in  reverse  order,  we  locate  t he  handle  j3n  in 
7n  and  replace  (3n  by  t he  head  of  the  relevant  production  An  -»  f3n  to  obtain 
the  previous  right-sentential  form  7n_ i.  Note  t h at  we  do  not  yet  know  how 
handles  are  to  be  found,  but  we  shall  see  methods  of  doing  so  shortly. 

We  then  repeat  this  process.  T h at  is,  we  locate  t he  handle  j3n~\  in  7n_i  and 
reduce  this  handle  to  obtain  t he  right-sentential  form  ^N-2 •  If by  continuing  this 
process  we  produce  a  right-sentential  form  consisting  only  of  the  start  symbol 
S,  then  we  halt  and  announce  successful  completion  of  parsing.  T he  reverse  of 
t he  sequence  of productions  used  in  t he  reductions  is  a  rightmost  derivation  for 
the  input  string. 

4.5.3 

Shift-Reduce  Parsing 

Shift-reduce  parsing  is  a  form  of  bottom-up  parsing  in  which  a  stack  holds 
grammar  symbols  and  an  input  buffer  holds  the  rest  of  t he  string  to  be  parsed. 
As  we  shall  see,  t he  handle  always  appears  at  t he  t op  of  t he  stack  just  before 
it  is  identified  as  t he  handle. 

We  use  $  to  mark  the  b o t t om  of  t he  stack  and  also  t he  right  end  of  the 
input.  Conventionally,  when  discussing  b o t t o m - up  parsing,  we  show  t he  t op  of 
t he  stack  on  the  right,  rather  t h an  on  the  left  as  we  did  for  top-down  parsing. 
Initially,  t he  stack  is  empty,  and  t he  string  w  is  on  t he  input,  as  follows: 

ST A CK 

$ 

IN P UT 

During  a  left-to-right  scan  of  t he  input  string,  t he  parser  shifts  zero  or  more 
input  symbols  onto  t he  stack,  until  it  is  ready  to  reduce  a  string  /3  of g r a m m ar 
symbols  on  top  of  t he  stack.  It  then  reduces  (3  to  t he  head  of  t he  appropriate 
production.  T he  parser  repeats  this  cycle  until  it  has  detected  an  error  or  until 
the  stack  contains  t he  start  symbol  and  t he  input  is  empty: 

4.5. 

BOTTOM-UP  PARSING 

237 

ST A CK 
$5 

IN P UT 

$ 

Upon  entering  this  configuration,  the  parser  halts  and  announces  successful 
completion  of  parsing.  Figure  4.28  steps  through  the  actions  a  shift-reduce 
parser  might  take  in  parsing t he  input  string  i di *icl2  according to t he  expression 
g r a m m ar  (4.1). 

ST A CK 

IN P UT 

AC T I ON 

$ 
$ i di 
$F 
$T 
$ T* 
$  T  *  i d2 
$ T *F 
$T 
%E 

idi  *  i d2  $ 
*  i d2  $ 
*  i d2  $ 
*  i d2  $ 
i d2$ 

$ 
$ 
$ 
$ 

shift 
reduce  by  F  ->  id 
reduce  by  T  ->•  F 
shift 
shift 
reduce  by  F  -)•  id 
reduce  by  T  ->•  T  *  F 
reduce  by  E  ->  T 
accept 

Figure  4.28:  Configurations  of  a  shift-reduce  parser  on  input  i d i * i d2 

While  the  primary  operations  are  shift  and  reduce,  there  are  actually  four 
possible  actions  a  shift-reduce  parser  can  make:  (1)  shift,  (2)  reduce,  (3)  accept, 
and  (4)  error. 

1.  Shift.  Shift  the  next  input  symbol  onto  the  top  of  the  stack. 

2.  Reduce.  T he  right  end  of  the  string  to  be  reduced  must  be  at  the  top  of 
the  stack.  Locate  the  left  end  of  the  string  within  the  stack  and  decide 
with  what  nonterminal  to  replace  t he  string. 

3.  Accept.  Announce  successful  completion  of  parsing. 

4.  Error.  Discover  a  syntax  error  and  call  an  error  recovery  routine. 

T he  use  of  a  stack  in  shift-reduce  parsing  is  justified  by  an  important  fact: 
the  handle  will  always  eventually  appear  on  top  of t he  stack,  never  inside.  This 
fact  can  be  shown  by  considering  t he  possible  forms  of  two  successive  steps 
in  any  rightmost  derivation.  Figure  4.29  illustrates  t he  two  possible  cases.  In 
case  (1),  A  is  replaced  by  (3By,  and  then  t he  rightmost  nonterminal  B  in  t he 
body  (3By  is  replaced  by  7.  In  case  (2),  A  is  again  expanded  first,  but  this  time 
t he  body  is  a  string  y  of terminals  only.  The  next  rightmost  nonterminal  B  will 
be  somewhere  to  t he  left  of  y. 

In  other  words: 

(1) 

S 

aAz  =>  aflByz  =^  afiyyz 

rgn 

rm 
rm 
S  =>•  aBxAz  •=>  aBxyz 

(2) 

ayxyz 

a 

0 

7 

y 

z 

a 

7 

x 

y 

z 

Case  (1) 

Case  (2) 

Figure  4.29:  Cases  for  two  successive  steps  of  a  rightmost  derivation 

Consider  case  (1)  in  reverse,  where  a  shift-reduce  parser  has  just  reached  the 
configuration 

ST A CK 

$«/?7 

IN P UT 

yz% 

T he  parser  reduces  the  handle  7  to  B  to  reach  the  configuration 

%a(3B 

yz% 

T he  parser  can  now  shift  the  string  y  onto  t he  stack  by  a  sequence  of  zero  or 
more  shift  moves  to  reach  t he  configuration 

%a/3By 

z$ 

with  the  handle  f3By  on  top  of  t he  stack,  and  it  gets  reduced  to  A. 

Now  consider  case  (2).  In  configuration 

Scry 

xyz% 

the  handle  7  is  on  top  of t he  stack.  After  reducing  the  handle  7  to  B,  the  parser 
can  shift  the  string  xy  to  get  t he  next  handle  y  on  top  of  the  stack,  ready  to  be 
reduced  to  A: 

%aBxy 

z% 

In  b o th  cases,  after  making  a  reduction  t he  parser  had  to  shift  zero  or  more 
symbols  to  get  t he  next  handle  onto  the  stack.  It  never  had  to  go  into  t he  stack 
to  find  the  handle. 

4.5.4  Conflicts  During  Shift-Reduce  Parsing 

There  are  context-free  grammars  for  which  shift-reduce  parsing  cannot  be  used. 
Every  shift-reduce  parser  for  such  a  g r a m m ar  can  reach  a  configuration  in  which 
t he  parser,  knowing  the  entire  stack  contents  and  t he  next  input  symbol,  cannot 
decide  whether  to  shift  or  to  reduce  (a  shift/reduce  conflict),  or  cannot  decide 

4.5. 

BOTTOM-UP  PARSING 

239 

which  of  several  reductions  to  make  (a  reduce/reduce  conflict).  We  now  give 
some  examples  of syntactic  constructs  t h at  give  rise  to  such  grammars.  Techni 
cally,  these  grammars  are  not  in  the  LR(fc)  class  of grammars  defined  in  Section 
4.7;  we  refer  to  t h em  as  non-LR  grammars.  The  k in  LR(k)  refers  to  the  number 
of  symbols  of  lookahead  on  the  input.  G r a m m a rs  used  in  compiling  usually  fall 
in  t he  LR(1)  class,  with  one  symbol  of  lookahead  at  most. 

E x a m p le  4 . 3 8:  An  ambiguous  grammar  can  never  be  LR.  For  example,  con 
sider  the  dangling-else  grammar  (4.14)  of  Section  4.3: 

stmt 

-» 
| 
I 

if  expr  t h en  stmt 
if  expr  t h en  stmt  e l se  stmt 

o t h er 

If  we  have  a  shift-reduce  parser  in  configuration 

ST A CK 
•  •  •  if expr t h en  stmt 

IN P UT 
e l se  •  • $ 

we  cannot  tell  whether  if  expr  t h en  stmt  is  the  handle,  no  m a t t er  what  appears 
below  it  on  the  stack.  Here  there  is  a  shift/reduce  conflict.  Depending  on  what 
follows  t he  e l se  on  t he  input,  it  might  be  correct  to  reduce  if  expr  t h en  stmt 
to  stmt,  or  it  might  be  correct  to  shift  e l se  and  then  to  look  for  another  stmt 
to  complete  the  alternative  if  expr  t h en  stmt  e l se  stmt. 

Note  t h at  shift-reduce  parsing  can  be  adapted  to  parse  certain  ambigu 
If  we  resolve  the 
ous  grammars,  such  as  the  if-then-else  grammar  above. 
shift/reduce  conflict  on  e l se  in  favor  of  shifting,  t he  parser  will  behave  as  we 
expect,  associating  each  e l se  with  the  previous  unmatched  t h e n.  We  discuss 
parsers  for  such  ambiguous  grammars  in  Section  4.8. 

• 

Another  common  setting  for  conflicts  occurs  when  we  know  we  have  a  han 
dle,  but  the  stack  contents  and  the  next  input  symbol  are  insufficient  to  de 
termine  which  production  should  be  used  in  a  reduction.  T he  next  example 
illustrates  this  situation. 

E x a m p le  4 . 3 9:  Suppose  we  have  a  lexical  analyzer  t h at  returns  the  token 
name  id  for  all  names,  regardless  of  their  type.  Suppose  also  t h at  our  lan 
guage  invokes  procedures  by  giving  their  names,  with  parameters  surrounded 
by  parentheses,  and  t h at  arrays  are  referenced  by  the  same  syntax.  Since  the 
translation  of  indices  in  array  references  and  parameters  in  procedure  calls 
are  different,  we  want  to  use  different  productions  to  generate  lists  of  actual 
parameters  and  indices.  Our  grammar  might  therefore  have  (among  others) 
productions  such  as  those  in  Fig.  4.30. 

A  statement  beginning  with  p ( i , j)  would  appear  as  t he  token  stream 
i d ( i d, i d)  to  the  parser.  After  shifting  the  first  three  tokens  onto  t he  stack, 
a  shift-reduce  parser  would  be  in  configuration 

240 

CHAPTER  4. 

SYNTAX  ANALYSIS 

parameterJist) 

, 

parameter 

(1) 
(2) 
(3) 
(4) 
(5) 
(6) 
(?) 
(8) 
(9) 

stmt 
stmt 

parameter-list 
parameter-list 
parameter 
expr 
expr 
exprJist 
exprJist 

-> 

-> 

-> 

( 

id 
expr  :=  errpr 
parameterJist 
parameter 
id 
id 
id 
exprJist 
expr 

( 

, 

exprJist) 

expr 

Figure  4.30:  Productions  involving  procedure  calls  and  array  references 

ST A CK 
•  •  •  id  (  id 

IN P UT 
,  id  )  • • • 

It  is  evident  t h at  the  id  on  top  of  the  stack  must  be  reduced,  but  by  which 
production?  The  correct  choice  is  production  (5)  if  p  is  a  procedure,  but  pro 
duction  (7)  if  p  is  an  array.  The  stack  does  not  tell  which;  information  in  t he 
symbol  table  obtained  from  t he  declaration  of p  must  be  used. 

One  solution  is  to  change  t he  token  id  in  production  (1)  to  p r o c id  and  to 
use  a  more  sophisticated  lexical  analyzer  t h at  returns  t he  token  name  p r o c id 
when  it  recognizes  a  lexeme  t h at  is  t he  name  of  a  procedure.  Doing  so  would 
require  t he  lexical  analyzer  to  consult  the  symbol  table  before  returning  a  token. 
If  we  made  this  modification,  then  on  processing  p ( i , j)  the  parser  would 

be  either  in  the  configuration 

ST A CK 
• •  •  p r o c id  ( id 

IN P UT 
,  id  )  •  • 

or  in  the  configuration  above. 
In  the  former  case,  we  choose  reduction  by 
production  (5);  in  the  latter  case  by  production  (7).  Notice  how  t he  symbol 
third  from  the  top  of  the  stack  determines  the  reduction  to  be  made,  even 
though  it  is  not  involved  in  t he  reduction.  Shift-reduce  parsing  can  utilize 
information  far  down  in  the  stack  to  guide  t he  parse. 

• 

4.5.5  Exercises  for  Section  4.5 

E x e r c i se  4 . 5 . 1:  For  the  grammar  5 
indicate  the  handle  in  each  of  t he  following  right-sentential  forms: 

0 5 1 | 0 1 of  Exercise  4.2.2(a), 

-> 

a)  000111. 

b)  0 0 5 1 1. 

E x e r c i se  4 . 5 . 2:  Repeat  Exercise 4.5.1  for t he  g r a m m ar S  -»  5  5  +  |  5  5  *  |  a 
of  Exercise  4.2.1  and  the  following  right-sentential  forms: 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

241 

a)  SSS  +  a*+. 

b)  SS  +  a*a+. 

c)  aaa * a + +. 

E x e r c i se  4 . 5 . 3:  Give  bottom-up  parses  for  the  following  input  strings  and 
grammars: 

a)  T he  input  000111  according  to  the  grammar  of  Exercise  4.5.1. 

b)  T he  input  aaa  *  a  +  +  according  to  the  grammar  of  Exercise  4.5.2. 

4.6 

Introduction  to  LR  Parsing:  Simple  LR 

The  most  prevalent  type  of bottom-up  parser  today  is  based  on  a  concept  called 
LR(fc)  parsing;  t he  "L"  is  for  left-to-right  scanning  of  t he  input,  t he  "R"  for 
constructing  a  rightmost  derivation  in  reverse,  and  the  k  for  the  number  of 
input  symbols  of  lookahead  t h at  are  used  in  making  parsing  decisions.  T he 
cases  k  =  0  or  k  =  1  are  of  practical  interest,  and  we  shall  only  consider  LR 
parsers  with  k  <  1  here.  W h en  (k)  is  omitted,  k  is  assumed  to  be  1. 

This  section  introduces  the  basic  concepts  of  LR  parsing  and  the  easiest 
method  for  constructing  shift-reduce  parsers,  called  "simple  LR"  (or  SLR,  for 
short).  Some  familiarity  with  the  basic  concepts  is  helpful  even  if  the  LR 
parser  itself  is  constructed  using  an  automatic  parser  generator.  We  begin  with 
"items"  and  "parser  states;"  the  diagnostic  o u t p ut  from  an  LR  parser  generator 
typically  includes  parser  states,  which  can  be  used  to  isolate  the  sources  of 
parsing  conflicts. 

Section  4.7  introduces  two,  more  complex  methods  —  canonical-LR  and 

LALR  —  t h at  are  used  in  the  majority  of  LR  parsers. 

4.6.1  Why  LR  Parsers? 

LR  parsers  are  table-driven,  much  like  the  nonrecursive  LL  parsers  of  Sec 
tion  4.4.4.  A  grammar  for  which  we  can  construct  a  parsing  table  using  one  of 
t he  methods  in  this  section  and  the  next  is  said  to  be  an  LR  grammar. 
itively,  for  a  grammar  to  be  LR  it  is  sufficient  t h at  a  left-to-right  shift-reduce 
parser  be  able  to  recognize  handles  of  right-sentential  forms  when  they  appear 
on  t op  of  t he  stack. 

Intu 

LR  parsing  is  attractive  for  a  variety  of  reasons: 

•  LR  parsers  can  be  constructed  to  recognize  virtually  all  programming-
language  constructs  for  which  context-free  grammars  can  be  written.  Non-
LR  context-free  grammars  exist,  but  these  can  generally  be  avoided  for 
typical  programming-language  constructs. 

242 

CHAPTER  4. 

SYNTAX  ANALYSIS 

•  T he  LR-parsing  method  is  the  most  general  nonbacktracking  shift-reduce 
parsing  method  known,  yet  it  can  be  implemented  as  efficiently  as  other, 
more  primitive  shift-reduce  methods  (see  the  bibliographic  notes). 

•  An  LR  parser  can  detect  a  syntactic  error  as  soon  as  it  is  possible  to  do 

so  on  a  left-to-right  scan  of  the  input. 

•  The  class  of  grammars  t h at  can  be  parsed  using  LR  methods  is  a  proper 
superset  of  the  class  of  grammars  t h at  can  be  parsed  with  predictive  or 
LL  methods.  For  a  grammar  to  be  LR(fc),  we  must  be  able  to  recognize 
the  occurrence  of t he  right  side  of  a  production  in  a  right-sentential  form, 
with  k  input  symbols  of  lookahead.  This  requirement  is  far  less  stringent 
t h an  t h at  for  LL(ife)  grammars  where  we  must  be  able  to  recognize  the 
use  of  a  production  seeing  only  the  first  k  symbols  of  what  its  right  side 
derives.  Thus,  it  should  not  be  surprising  t h at  LR  grammars  can  describe 
more  languages  t h an  LL  grammars. 

T he  principal  drawback  of  t he  LR  method  is  t h at  it  is  too  much  work  to 

construct  an  LR  parser  by  hand  for  a  typical  programming-language  grammar. 
A  specialized  tool,  an  LR  parser  generator,  is  needed.  Fortunately,  many  such 
generators  are  available,  and  we  shall  discuss  one  of  the  most  commonly  used 
ones,  Yacc,  in  Section  4.9.  Such  a  generator  takes  a  context-free  g r a m m ar  and 
automatically  produces  a  parser  for  t h at  grammar. 
If  the  g r a m m ar  contains 
ambiguities  or  other  constructs  t h at  are  difficult  to  parse  in  a  left-to-right  scan 
of  the  input,  then  the  parser  generator  locates  these  constructs  and  provides 
detailed  diagnostic  messages. 

4.6.2 

Items  and  the  LR(O)  Automaton 

How  does  a  shift-reduce  parser  know  when  to  shift  and  when  to  reduce?  For 
example,  with  stack  contents  $ T  and  next  input  symbol  *  in  Fig.  4.28,  how 
does  t he  parser  know  t h at  T  on  the  top  of  t he  stack  is  not  a  handle,  so  t he 
appropriate  action  is  to  shift  and  not  to  reduce  TtoEP. 

An  LR  parser  makes  shift-reduce  decisions  by  maintaining  states  to  keep 
track  of  where  we  are  in  a  parse.  States  represent  sets  of  "items."  An  LR(0) 
item  (item  for  short)  of  a  g r a m m ar  G  is  a  production  of  G  with  a  dot  at  some 
position  of  the  body.  Thus,  production  A 

XYZ yields  the  four  items 

-XYZ 
A 
A  -+  XYZ 
A  ->  XYZ 
XYZ-
A 

T he  production  A  ->•  e  generates  only  one  item,  A 

•  . 

Intuitively,  an  item  indicates  how  much  of  a  production  we  have  seen  at  a 
given  point  in  the  parsing  process.  For  example,  t he  item  A  -»  XYZ  indicates 
Item 
t h at  we  hope  to  see  a  string  derivable  from  XYZ  next  on  the  input. 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

243 

Representing  Item  Sets 

A  parser  generator  t h at  produces  a  b o t t o m - up  parser  may  need  to  rep 
resent  items  and  sets  of  items  conveniently.  Note  t h at  an  item  can  be 
represented  by  a  pair  of  integers,  the  first  of  which  is  the  number  of  one 
of  t he  productions  of  the  underlying  grammar,  and  the  second  of  which  is 
t he  position  of  t he  dot.  Sets  of  items  can  be  represented  by  a  list  of  these 
pairs.  However,  as  we  shall  see,  the  necessary  sets  of  items  often  include 
"closure"  items,  where  the  dot  is  at  the  beginning  of  the  body.  These  can 
always  be  reconstructed  from  t he  other  items  in  the  set,  and  we  do  not 
have  to  include  t h em  in  t he  list. 

A  -»  XYZ  indicates  t h at  we  have  just  seen  on  the  input  a  string  derivable  from 
X  and  t h at  we  hope  next  to  see  a  string  derivable  from  YZ.  Item  A  —>  XYZ-
indicates  t h at  we  have  seen  t he  body  XYZ  and  t h at  it  may  be  time  to  reduce 
XYZ 

to  A. 

One  collection  of  sets  of  LR(0)  items,  called  the  canonical  LR(0)  collection, 
provides  the  basis  for  constructing  a  deterministic  finite  a u t o m a t on  t h at  is  used 
to  make  parsing  decisions.  Such  an  a u t o m a t on  is  called  an  LR(0)  automaton.3 
In  particular,  each  state  of  the  LR(0)  a u t o m a t on  represents  a  set  of  items  in 
t he  canonical  LR(0)  collection.  The  a u t o m a t on  for  t he  expression  g r a m m ar 
(4.1),  shown  in  Fig.  4.31,  will  serve  as  the  running  example  for  discussing  the 
canonical  LR(0)  collection  for  a  grammar. 

To  construct  the  canonical  LR(0)  collection  for  a  grammar,  we  define  an 
augmented  g r a m m ar  a nd  two  functions,  CLOSURE  and  G O T O.  If G  is  a  g r a m m ar 
with  start  symbol  S,  then  G',  the  augmented  grammar  for  G,  is  G  with  a  new 
start  symbol  5"  and  production  S'  —>  S.  The  purpose  of  this  new  starting 
production  is  to  indicate  to  the  parser  when  it  should  stop  parsing  and  announce 
acceptance  of  the  input.  T h at  is,  acceptance  occurs  when  and  only  when  the 
parser  is  about  to  reduce  by  S'  -»  S. 

C l o s u re  of  I t em  S e ts 

If  I  is  a  set  of  items  for  a  g r a m m ar  G,  then  CLOSURE(I)  is  the  set  of  items 
constructed  from  /  by  the  two  rules: 

1.  Initially,  add  every  item  in  /  to  CLOSURE(Z). 

2.  If  A  -»  a-B/3  is  in  CLOSURE(J)  and  B  ->•  7  is  a  production,  then  add  the 
-7  to  CLOSURE(7),  if  it  is  not  already  there.  Apply  this  rule 

item  B 
until  no  more  new  items  can  be  added  to  CLOSURE(J). 

3  Technically,  the  automaton  misses  being  deterministic  according  to  the  definition  of  Sec 
tion  3.6.4,  because  we  do  not  have  a dead  state,  corresponding  to  the  empty  set  of items.  As 
a  result,  there  are  some  state-input  pairs  for  which  no  next  state  exists. 

244 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

+ 

h 
\E'-*E-
E->E-+T 

- 7-

accept 

+ 

F - >F  +  -7 
T - > . T *F 
T-+F 
F^-(E) 
F- > id 

id 

/9 
F- 4F  +  T-
T- -»T •  * F 

h 
>T*F 

F->.(E) 
F - + id 
id 
id 

IT 
^ 

ho 
>T*F-

+ 

E 

h 

E^E-+T 
F - >(  F •  ) 

hi 
F->(  E 

h 

E-
T- +  T *F 

h 
•id-

id 

I 4 
F- + (  • F) 
•E-
r 
E-r 
T->T*F 
T-
F 
F- HE) 
F- +  id 

h 

T^F-

Figure  4.31:  LR(O)  a u t o m a t on  for  t he  expression  g r a m m ar  (4.1) 

Intuitively,  A  —»•  a-B/3  in  CLOSURE(Z)  indicates  t h a t,  at  some  point  in  t he 
parsing  process,  we  think  we  might  next  see  a  substring  derivable  from  B(3 
as  input.  T he  substring  derivable  from  B(5  will  have  a  prefix  derivable  from 
B  by  applying  one  of  t he  .^-productions.  We  therefore  add  items  for  all  the 
.^-productions;  t h at  is,  if  B  -¥  7  is  a  production,  we  also  include  B  ->•  -7  in 
CLOSURE(J). 

E x a m p le  4 . 4 0:  Consider  the  augmented  expression  grammar: 

E' 
E 
T 
E 

-¥ 

-+ 

E 
E  + T  I  T 
T*F  I  F 
(E)  I 

id 

If  I  is  the  set  of  one  item  {[E'  -»•  -E]},  then  CLOSURE(J)  contains  t he  set 

of  items  I0  in  Fig.  4.31. 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

245 

To  see  how  the  closure  is  computed,  E'  -»•  E  is  put  in  C L O S U R E( J)  by 
rule  (1).  Since  there  is  an  E  immediately  to  t he  right  of  a  dot,  we  add  t he 
E-productions  with  dots  at  the  left  ends:  E 
-E  + T  and  E  ->•  T.  Now  there 
is  a  T  immediately  to  t he  right  of  a  dot  in  t he  latter  item,  so  we  add  T  -¥  T*F 
and  T  ->  F.  Next,  t he  F  to  t he  right  of  a  dot  forces  us  to  add  F  ->•  -(E)  and 
F  -»  -id,  but  no  other  items  need  to  be  added. 

• 

T he  closure  can  be  computed  as  in  Fig.  4.32.  A  convenient  way  to  imple 
ment  t he  function  closure  is  to  keep  a  boolean  array  added,  indexed  by  t he 
nonterminals  of  G,  such  t h at  added[B]  is  set  to  t r ue  if  and  when  we  add  the 
item  B 

-7  for  each  ^ - p r o d u c t i on  B  —>•  7. 

SetOfltems  C L O S U RE  (J)  { 

J  =  I\ 
r e p e at 

for  (  each  item  A  —\  a-Bf3  in  J  ) 

for  (  each  production  B  —>  7  of G  ) 
if  (  B  ->  -7  is  not  in  J  ) 
add  B  -¥  -7  to  J; 

u n t il  no  more  items  are  added  to  J  on  one  round; 
r e t u rn  J; 

} 

Figure  4.32:  Computation  of  C L O S U RE 

Note  t h at  if one  ^ - p r o d u c t i on  is  added  to  the  closure  of /  with  t he  dot  at  t he 
left  end,  then  all  £?-productions  will  be  similarly  added  to  t he  closure.  Hence, 
7 
it  is  not  necessary  in  some  circumstances  actually  to  list  t he  items  B  —> 
added  to  I  by  C L O S U R E.  A  list  of  t he  nonterminals  B  whose  productions  were 
so  added  will  suffice.  We  divide  all  the  sets  of items  of interest  into  two  classes: 

1.  Kernel  items:  the  initial  item,  S'  ->  -S,  and  all  items  whose  dots  are  not 

at  the  left  end. 

2.  Nonkernel  items: 

all  items  with  their  dots  at  the  left  end,  except  for 

S' 

-S. 

Moreover,  each  set  of  items  of  interest  is  formed  by  taking  t he  closure  of  a  set 
of  kernel  items;  t he  items  added  in  the  closure  can  never  be  kernel  items,  of 
course.  Thus,  we  can  represent  the  sets  of  items  we  are  really  interested  in 
with  very  little  storage  if we  throw  away  all  nonkernel  items,  knowing  t h at  they 
could  be  regenerated  by  the  closure  process.  In  Fig.  4.31,  nonkernel  items  are 
in  t he  shaded  p a rt  of  t he  box  for  a  state. 

246 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

T he  F u n c t i on  G O TO 

The  second  useful  function  is  GOTO (I,  X)  where  I  is  a  set  of  items  and  X  is  a 
g r a m m ar  symbol.  GOTO (I, X)  is  defined  to  be  the  closure  of t he  set  of all  items 
Intuitively,  t he  GOTO  function 
[A  ->  aX-fi]  such  t h at  [A  ->  a  •  X(3]  is  in  I. 
is  used  to  define  the  transitions  in  the  LR(0)  a u t o m a t on  for  a  g r a m m a r.  T he 
states  of  the  a u t o m a t on  correspond  to  sets  of  items,  and  G O T O ( 7 , X)  specifies 
the  transition  from  t he  state  for  I  under  input  X. 

E x a m p le  4 . 4 1:  If  I  is  the  set  of  two  items  {[E'  -»£?•],  [E  -»•  E-  +  T]},  then 
GOTO(7,  +)  contains  the  items 

E  -¥  E  +-T 
T  -»• 
-T*F 
T 
-+.F 
F  ->  -(E) 
F  -* 

id 

We  computed  GOTO (I,  +)  by  examining  I  for  items  with  +  immediately  to 
t he  right  of  the  dot.  E'  -»  E-  is  not  such  an  item,  b ut  E  -»  E-  +  T  is.  We 
moved  t he  dot  over  the  +  to  get  E  ->•  E  +  T  and  then  took  t he  closure  of  this 
singleton  set. 

• 

We  are  now  ready  for  t he  algorithm  to  construct  C,  the  canonical  collection 
of  sets  of  LR(0)  items  for  an  augmented  g r a m m ar  G'  —  t he  algorithm  is  shown 
in  Fig.  4.33. 

v o id 

{ 

items(G') 
C = CLOSURE({[5' -> •£]}); 
r e p e at 

for  (  each  set  of  items  I  in  C  ) 

for  (  each  g r a m m ar  symbol  X  ) 

if  (  GOTO (I,  X)  is  not  empty  and  not  in  C  ) 

add  GOTO(7,  X) 

to  C; 

u n t il  no  new  sets  of  items  are  added  to  C  on  a  round; 

} 

Figure  4.33:  Computation  of  the  canonical  collection  of  sets  of  LR(0)  items 

E x a m p le  4 . 42  :  T he  canonical  collection  of  sets  of  LR(0)  items  for  g r a m m ar 
(4.1)  and  the  GOTO  function  are  shown  in  Fig.  4.31.  GOTO  is  encoded  by  the 
transitions  in  the 

figure. 

• 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

247 

U se  of  t he  LR(O)  A u t o m a t on 

T he  central  idea  behind  "Simple  LR,"  or  SLR,  parsing  is  the  construction  from 
the  grammar  of  t he  LR(0)  automaton.  The  states  of  this  a u t o m a t on  are  t he 
sets  of  items  from  the  canonical  LR(0)  collection,  and  the  transitions  are  given 
by  the  G O TO  function.  T he  LR(0)  a u t o m a t on  for  the  expression  grammar  (4.1) 
appeared  earlier  in  Fig.  4.31. 

T he  start  state  of the  LR(0)  automaton  is  C L O S U R E( { [ 5'  ->•  -5]}),  where  S' 
is  t he  start  symbol  of the  augmented  grammar.  All  states  are  accepting  states. 
We  say  "state  j"  to  refer  to  the  state  corresponding  to  the  set  of  items  Ij. 

How  can  LR(0)  a u t o m a ta  help  with  shift-reduce  decisions?  Shift-reduce 
decisions  can  be  made  as  follows.  Suppose  t h at  the  string  7  of grammar  symbols 
takes  the  LR(0)  a u t o m a t on  from  the  start  state  0  to  some  state  j.  Then,  shift 
on  next  input  symbol  a  if  state  j  has  a  transition  on  a.  Otherwise,  we  choose 
to  reduce;  t he  items  in  state  j  will  tell  us  which  production  to  use. 

T he  LR-parsing  algorithm  to  be  introduced  in  Section  4.6.3  uses  its  stack  to 
keep  track  of  states  as  well  as  grammar  symbols;  in  fact,  the  grammar  symbol 
can  be  recovered  from  t he  state,  so  t he  stack  holds  states.  T he  next  example 
gives  a  preview  of  how  an  LR(0)  a u t o m a t on  and  a  stack  of  states  can  be  used 
to  make  shift-reduce  parsing  decisions. 

E x a m p le  4 . 4 3:  Figure  4.34  illustrates  the  actions  of  a  shift-reduce  parser  on 
input  id  *  id,  using  the  LR(0)  a u t o m a t on  in  Fig.  4.31.  We  use  a  stack  to  hold 
states;  for  clarity,  the  grammar  symbols  corresponding  to  t he  states  on  the 
stack  appear  in  column  S Y M B O L S.  At  line  (1),  the  stack  holds  the  start  state  0 
of  the  automaton;  the  corresponding  symbol  is  t he  bottom-of-stack  marker  $. 

LI NE 

ST A CK 

SY M B O LS 

IN P UT 

AC T I ON 

(1) 
(2) 
(3) 
(4) 
(5) 
(6) 
(?) 
(8) 
(9) 

0 
05 
03 
02 
0 27 
0 2 75 
02  7 10 
02 
01 

$ 
$ id 
$F 
$T 
$ T* 
$ T* id 
$ T *F 
$T 
$E 

id  *  id  $ 
* i d$ 
* i d$ 
* i d$ 
i d$ 
$ 
$ 
$ 
$ 

shift  to  5 
reduce  by  F  —>  id 
reduce  by  T  ->•  F 
shift  to  7 
shift  to  5 
reduce  by  F  —>  id 
reduce  by  T  -+  T  *  F 
reduce  by  E  ->•  T 
accept 

Figure  4.34:  T he  parse  of  id  *  id 

T he  next  input  symbol  is  id  and  state  0  has  a  transition  on  id  to  state  5. 
We  therefore  shift.  At  line  (2),  state  5  (symbol  id)  has  been  pushed  onto  t he 
stack.  There  is  no  transition  from  state  5  on  input  *,  so  we  reduce.  From  item 
[F  -»  id-]  in  state  5,  the  reduction  is  by  production  F  ->•  id. 

248 

CHAPTER  4. 

SYNTAX  ANALYSIS 

With  symbols,  a  reduction  is  implemented  by  popping  the  body  of  the  pro 
duction  from  the  stack  (on  line  (2),  the  body  is  id)  and  pushing  the  head  of 
the  production  (in  this  case,  F).  With  states,  we  pop  state  5  for  symbol  id, 
which  brings  state  0  to  the  top  and  look  for  a  transition  on  F,  the  head  of  the 
production.  In  Fig.  4.31,  state  0  has  a  transition  on  F  to  state  3,  so  we  push 
state  3,  with  corresponding  symbol  F;  see  line  (3). 

As  another  example,  consider  line  (5),  with  state  7  (symbol  *)  on  top  of the 
stack.  This  state  has  a  transition  to  state  5  on  input  id,  so  we  push  state  5 
(symbol  id).  State  5  has  no  transitions,  so  we  reduce  by  F  —>  id.  When  we 
pop  state  5  for  the  body  id,  state  7  comes  to  the  top  of the  stack.  Since  state  7 
has  a  transition  on  F  to  state  10,  we  push  state  10  (symbol  F). 

• 

4.6.3  The  LR-Parsing  Algorithm 

A  schematic  of  an  LR  parser  is  shown  in  Fig.  4.35. 
It  consists  of  an  input, 
an  output,  a  stack,  a  driver  program,  and  a  parsing  table  t h at  has  two  parts 
(ACTION  and  GOTO).  The  driver  program  is  the  same  for  all  LR  parsers;  only 
the  parsing  table  changes  from  one  parser  to  another.  T he  parsing  program 
reads  characters  from  an  input  buffer  one  at  a  time.  Where  a  shift-reduce  parser 
would  shift  a  symbol,  an  LR  parser  shifts  a  state.  Each  state  summarizes  the 
information  contained  in  the  stack  below  it. 

Input 

ai 

ai 

an 

$ 

Stack 

S M -1 

LR 
Parsing 
Program 

Output 

ACTION 

GOTO 

Figure  4.35:  Model  of  an  LR  parser 

T he  stack  holds  a  sequence  of  states,  so^i  •  •  •  sm,  where  sm  is  on  t o p.  In  the 
SLR  method,  the  stack  holds  states  from  the  LR(0)  automaton;  the  canonical-
LR  and  LALR  methods  are  similar.  By  construction,  each  state  has  a  corre 
sponding  grammar  symbol.  Recall  t h at  states  correspond  to  sets  of  items,  and 
t h at  there  is  a  transition  from  state  i  to  state  j  if  GOTO(Ii,X)  =  Ij.  All  t r a n 
sitions  to  state  j  must  be  for  the  same  grammar  symbol  X.  Thus,  each  state, 
except  the  start  state  0,  has  a  unique  grammar  symbol  associated  with  i t .4 

4T he  converse  need  not  hold;  that  is,  more  than  one  state  may  have  the  same  grammar 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

249 

S t r u c t u re  of  t he  LR  P a r s i ng  T a b le 

T he  parsing  table  consists  of  two  parts:  a  parsing-action  function  ACTION  and 
a  goto  function  GOTO. 

1.  T he  ACTION  function  takes  as  arguments  a  state  i  and  a  terminal  a  (or 
$,  the  input  endmarker).  The  value  of  ACTION[i,a]  can  have  one  of four 
forms: 

(a)  Shift  j,  where  j  is  a  state.  T he  action  taken  by  t he  parser  effectively 

shifts  input  a  to  t he  stack,  but  uses  state  j  to  represent  a. 

(b)  Reduce  A-+  (3.  T he  action  of the  parser  effectively  reduces  (3  on  t he 

top  of  the  stack  to  head  A. 

(c)  Accept.  T he  parser  accepts  the  input  and  finishes  parsing. 

(d)  Error.  T he  parser  discovers  an  error  in  its  input  and  takes  some 
corrective  action.  We  shall  have  more  to  say  about  how  such  error-
recovery  routines  work  in  Sections  4.8.3  and  4.9.4. 

2.  We  extend  t he  GOTO  function,  defined  on  sets  of  items,  to  states: 

if 
G O T O [ / i, A]  =  Ij,  then  GOTO  also  maps  a  state  i  and  a  nonterminal  A  to 
state  j. 

L R - P a r s er  C o n f i g u r a t i o ns 

To  describe  t he  behavior  of  an  LR  parser,  it  helps  to  have  a  notation  repre 
senting  the  complete  state  of  the  parser:  its  stack  and  t he  remaining  input.  A 
configuration  of  ah  LR  parser  is  a  pair: 

[sosi  •  •  -Sm,  aiOi+i  •  •  - an$) 

where  t he  first  component  is  t he  stack  contents  (top  on  the  right),  and  the 
second  component  is  the  remaining  input.  This  configuration  represents  the 
right-sentential  form 

X1X2  •  •  •  XmdiCLi+i  •  •  •  an 

in  essentially  t he  same  way  as  a  shift-reduce  parser  would;  t he  only  difference  is 
t h at  instead  of  grammar  symbols,  the  stack  holds  states  from  which  g r a m m ar 
symbols  can  be  recovered.  T h at  is,  X{  is  t he  grammar  symbol  represented 
by  state  Si.  Note  t h at  s0,  the  start  state  of  the  parser,  does  not  represent  a 
grammar  symbol,  and  serves  as  a  bottom-of-stack  marker,  as  well  as  playing  an 
important  role  in  the  parse. 

symbol.  See  for  example  states  1  and  8  in  the  LR(0)  automaton  in  Fig.  4.31,  which  are  both 
entered  by  transitions  on  E,  or  states  2  and  9,  which  are  both  entered  by  transitions  on  T. 

250 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

B e h a v i or  of  t he  LR  P a r s er 

T he  next  move  of  t he  parser  from  t he  configuration  above  is  determined  by 
reading a*,  the  current  input  symbol,  and  sm,  the  state  on  top  of  the  stack, 
and  then  consulting  the  entry  A C T I O N [ sm, a*]  in  the  parsing  action  table.  T he 
configurations  resulting  after  each  of  the  four  types  of  move  are  as  follows 

1.  If A C T I O N [ sm, O i]  =  shift  s,  the  parser  executes  a  shift  move;  it  shifts  the 

next  state  s  onto  t he  stack,  entering  t he  configuration 

(s08i  •  •  -sms,  ai +1  • • -on$) 

T he  symbol  di  need  not  be  held  on  the  stack,  since  it  can  be  recovered 
from  s,  if needed  (which  in  practice  it  never  is).  T he  current  input  symbol 

is 

now  O j + i. 

2.  If  ACTION [sm,  ai]  =  reduce  A  ->  /3,  then  the  parser  executes  a  reduce 

move,  entering  the  configuration 

(sosi  •  •  •  sm-rs,  didi+i  •  •  •  an%) 

where  r  is  the  length  of  0,  and  s  =  GOTO[sm-r,  A].  Here  the  parser 
first  popped  r  state  symbols  off  t he  stack,  exposing  s t a te  sT O_r.  T he 
parser  then  pushed  s,  the  entry  for  G O T O [ sm_r, A],  onto  the  stack.  T he 
current  input  symbol  is  not  changed  in  a  reduce  move.  For  the  LR  parsers 
we 
symbols 
the 
corresponding  to  the  states  popped  off  the  stack,  will  always  match  (3, 
the  right  side  of  t he  reducing  production. 

sequence  of  g r a m m ar 

construct,  Xm-r+i-'Xm, 

shall 

T he  o u t p ut  of  an  LR  parser  is  generated  after  a  reduce  move  by  executing 
the  semantic  action  associated  with  the  reducing  production.  For  the  time 
being,  we  shall  assume  the  o u t p ut  consists  of  just  printing  t he  reducing 
production. 

3.  If A C T l O N [ sm, ai\  =  accept,  parsing  is  completed. 

4.  If  A C T l O N [ sm, ai\  =  error,  t he  parser  has  discovered  an  error  and  calls  an 

error  recovery  routine. 

T he  LR-parsing  algorithm  is  summarized  below.  All  LR  parsers  behave 
in  this  fashion;  the  only  difference  between  one  LR  parser  and  another  is  the 
information  in  t he  ACTION  and  GOTO  fields  of  the  parsing  table. 

A l g o r i t hm  4 . 4 4:  LR-parsing  algorithm. 

I N P U T:  An  input  string  w  and  an  LR-parsing  table  with  functions  ACTION  and 
GOTO  for  a  g r a m m ar  G. 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

251 

O U T P U T:  If  w  is  in  L(G),  the  reduction  steps  of  a  bottom-up  parse  for  w; 
otherwise,  an  error  indication. 

M E T H O D:  Initially,  the  parser  has  s0  on  its  stack,  where  s0  is  t he  initial  state, 
and  w$  in  t he  input  buffer.  T he  parser  then  executes  t he  program  in  Fig.  4.36. 
• 

let  a  be  t he  first  symbol  of  w$; 
w h i l e( 1)  {  /*  repeat  forever  */ 

let  s  be  the  state  on  top  of the  stack; 
if  (  ACTION[s, a]  =  shift  t  )  { 

push  t  onto  t he  stack; 
let  a  be  the  next  input  symbol; 
}  e l se  if  (  ACTION  [s,  a]  =  reduce  A  (3  )  { 
p op  \{31  symbols  off t he  stack; 
let  state  t  now  be  on  top  of  the  stack; 
push  GOTOft, A]  onto  the  stack; 
output  the  production  A  -»  /?; 

}  e l se  if  (  ACTION[s,a]  =  accept  )  break;  /*  parsing  is  done  */ 
e l se  call  error-recovery  routine; 

} 

Figure  4.36:  LR-parsing  program 

E x a m p le  4 . 4 5:  Figure  4.37  shows  the  ACTION  and  GOTO  functions  of  an 
LR-parsing  table  for  the  expression  grammar  (4.1),  repeated  here  with  t he 
productions  numbered: 

(1)  E^E  +  T 
(2)  E^T 
(3)  T^T*F 

T-^F 
F->(E) 

(4) 
(5) 
(6)  F^ id 

T he  codes  for  the  actions  are: 

1.  si  means  shift  and  stack  state  z, 

2.  rj  means  reduce  by  the  production  numbered  j, 

3.  acc  means  accept, 

4.  blank  means  error. 

Note  t h at  the  value  of  GOTO[s,  a]  for  terminal  a  is  found  in  the  ACTION 
field  connected  with  the  shift  action  on  input  a  for  state  s.  The  GOTO  field 
gives  GOTOJs,  A]  for  nonterminals  A.  Although  we  have  not  yet  explained  how 
the  entries  for  Fig.  4.37  were  selected,  we  shall  deal  with  this  issue  shortly. 

252 

CHAPTER  4. 

SYNTAX  ANALYSIS 

ST A TE 
ST A TE 

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 

A C T I ON 

G O TO 

id 

s5 

s5 

s5 
s5 

+ 

* 

s6 
r2 
r4 

s7 
r4 

r6 

r6 

s6 
rl 
r3 
r5 

s7 
r3 
r5 

( 

s4 

s4 

s4 
s4 

) 

$ 

acc 
r2 
r4 

r2 
r4 

r6 

r6 

s ll 
rl 
r3 
r5 

rl 
r3 
r5 

E 

1 

8 

T 

2 

2 

9 

F 

3 

3 

3 
10 

Figure  4.37:  Parsing  table  for  expression  g r a m m ar 

On  input  id  *  id  +  id,  the  sequence  of  stack  and  input  contents  is  shown 
in  Fig.  4.38.  Also  shown  for  clarity,  are  t he  sequences  of  g r a m m ar  symbols 
corresponding  to  the  states  held  on  t he  stack.  For  example,  at  line  (1)  the  LR 
parser  is  in  state  0,  the  initial  state  with  no  grammar  symbol,  and  with  id  t he 
first  input  symbol.  T he  action  in  row  0  and  column  id  of  the  action  field  of 
Fig.  4.37  is  s5,  meaning  shift  by  pushing  state  5.  T h at  is  what  has  happened  at 
line  (2):  t he  state  symbol  5  has  been  pushed  onto  t he  stack,  and  id  has  been 
removed  from  the  input. 

Then,  *  becomes  t he  current  input  symbol,  and  the  action  of state  5  on  input 
id.  One  state  symbol  is  popped  off  the  stack.  State  0 
*  is  to  reduce  by  F 
is  then  exposed.  Since  the  goto  of  state  0  on  F is  3,  state  3  is  pushed  onto  t he 
stack.  We  now  have  t he  configuration  in  line  (3).  Each  of t he  remaining  moves 
is  determined  similarly. 

• 

4.6.4  Constructing  SLR-Parsing  Tables 

T he  SLR  method  for  constructing  parsing  tables  is  a  good  starting  point  for 
studying  LR  parsing.  We  shall  refer  to  t he  parsing  table  constructed  by  this 
method  as  an  SLR  table,  and  to  an  LR  parser  using  an  SLR-parsing  table  as  an 
SLR  parser.  T he  other  two  methods  augment  the  SLR  m e t h od  with  lookahead 
information. 

T he  SLR  method  begins  with  LR(0)  items  and  LR(0)  a u t o m a t a,  introduced 
in  Section  4.5.  T h at  is,  given  a  grammar,  G,  we  augment  G  to  produce  G', 
with  a  new  start  symbol  S'.  From  G',  we  construct  C,  the  canonical  collection 
of  sets  of  items  for  G'  together  with  the  G O TO  function. 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

253 

ST A CK 

SY M B O LS 

IN P UT 

A C T I ON 

(1) 
(2) 
(3) 
(4) 
(5) 
(6) 
(?) 
(8) 
(9) 
(10) 

(11) 
(12) 
(13) 

(14) 

0 
id 
0  5 
F 
0  3 
T 
0  2 
T* 
0  2  7 
T* id 
0  2  7  5 
0  2  7  10  T *F 
02 
0  1 
0  1  6 
0  16  5 
0  16  3 
0  16  9 
0  1 

T 
E 
E  + 
E  +  id 
E  +  F 
E  +  T 
E 

id  *  id  +  id $ 
*  id  +  id $ 
*  id  -1-  id $ 
*  id  +  id $ 
id  +  i d$ 
+  i d$ 
+  i d$ 
+  i d$ 
+  i d$ 
i d$ 
$ 
$ 
$ 
$ 

shift 
reduce  by  F  —>  id 
reduce  by  T  -+  F 
shift 
shift 
reduce  by  F  -»  id 
reduce  by  T  ->•  T  *  F 
reduce  by  E  -¥  T 
shift 
shift 
reduce  by  F  —>  id 
reduce  by  T  -»  F 
reduce  by  E  ->  E  +  T 
accept 

Figure  4.38:  Moves  of  an  LR  parser  on  id  *  id  +  id 

T he  ACTION  and  GOTO  entries  in  the  parsing  table  are  then  constructed 
It  requires  us  to  know  FOLLOW(A)  for  each 

using  the  following  algorithm. 
nonterminal  A  of  a  g r a m m ar  (see  Section  4.4). 

A l g o r i t hm  4 . 4 6:  Constructing  an  SLR-parsing  table. 

I N P U T:  An  augmented  grammar  G'. 

O U T P U T:  T he  SLR-parsing  table  functions  ACTION  and  GOTO  for  G'. 

M E T H O D: 

1.  Construct  C  =  {Io,h,... 

,In}, 

t he  collection  of  sets  of  LR(0) 

items  for 

G'. 

2.  State  i  is  constructed  from 

T he  parsing  actions  for  state  i  are  deter 

mined  as  follows: 

(a)  If  [A  -»  a-a/3]  is  in  Ii  and  G O T O ( / j,  a)  =  Ij,  then  set  ACTlON[z,  a]  to 

"shift  j ."  Here  a  must  be  a  terminal. 

(b)  If  [A  -y  a-]  is  in  Ii,  then  set  ACTION[i,a]  to  "reduce  A  ->•  a"  for  all 

a  in  FOLLOW(vl);  here  A  may  not  be  S'. 

(c)  If  [S'  -t  S-]  is  in  h,  then  set  ACTION[z',$]  to  "accept." 

If  any  conflicting  actions  result  from  the  above  rules,  we  say  the  g r a m m ar 
is  not  S L R ( l ).  T he  algorithm  fails  to  produce  a  parser  in  this  case. 

254 

CHAPTER  4. 

SYNTAX  ANALYSIS 

3.  T he  goto  transitions  for  state  i  are  constructed  for  all  nonterminals  A 

using  the  rule:  If  GOTO(Ii,A)  =  Ij,  then  GOTO[i,  A]  =  j. 

4.  All  entries  not  defined  by  rules  (2)  and  (3)  are  made  "error." 

5.  T he  initial  state  of t he  parser  is  the  one  constructed  from  t he  set  of items 

containing  [S'  ->•  -S]. 

• 

The  parsing  table  consisting of the  ACTION  and  G O TO  functions  determined 
by  Algorithm  4.46  is  called  t he  SLR(l)  table  for  G.  An  LR  parser  using  t he 
S L R ( l)  table  for  G  is  called  the  S L R ( l)  parser  for  G,  and  a  g r a m m ar  having  an 
S L R ( l)  parsing  table  is  said  to  be  SLR(l).  We  usually  omit  the  "(1)"  after  t he 
"SLR,"  since  we  shall  not  deal  here  with  parsers  having  more  t h an  one  symbol 
of  lookahead. 

E x a m p le  4 . 4 7:  Let  us  construct  the  SLR  table  for  the  augmented  expression 
grammar.  T he  canonical  collection  of  sets  of  LR(0)  items  for  the  g r a m m ar  was 
shown  in  Fig.  4.31.  First  consider  the  set  of  items  Io: 

E 

E' 
E-> -E + T 
E->-T 
T -> -T * F 
F 
T 
F 
-(E) 
F -»•  id 

T he  item  F 

-(E)  gives  rise  to  t he  entry  ACTION[0,  (]  =  shift  4,  and  the 
item  F  ->  -id  to  the  entry  ACTION[0, id]  =  shift  5.  Other  items  in  J0  yield  no 
actions.  Now  consider  Ix: 

E' -> E¬ 
E-* E- + T 

T he first item yields ACTION[1, $]  =  accept,  and the  second yields ACTION[1, +] 
=  shift  6.  Next  consider  I2: 

E  -¥T-
T-+T-*F 

Since  FOLLOW(E)  =  {$, + , ) },  t he  first  item  makes 

ACTION[2,  $]  =  ACTION[2,  +]  =  ACTION[2,)]  =  reduce  E  ->  T 

T he  second  item  makes  ACTION[2, *]  =  shift  7.  Continuing  in  this  fashion  we 
obtain  t he  ACTION  and  GOTO  tables  t h at  were  shown  in  Fig.  4.31. 
In  t h at 
figure,  t he  numbers  of  productions  in  reduce  actions  are  the  same  as  t he  order 
in  which  they  appear  in  t he  original  g r a m m ar  (4.1).  T h at  is,  E  ->  E  +  T  is 
number  1,  E  -4-  T  is  2,  and  so  on. 

• 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

2 55 

E x a m p le  4 . 4 8:  Every  S L R ( l)  g r a m m ar  is  unambiguous,  but  there  are  many 
unambiguous  grammars  t h at  are  not  S L R ( l ).  Consider  t he  g r a m m ar  with  pro 
ductions 

S 
L 
R 

->  L  =  R  |  R 
-> 
| 
*R 
-)•  L 

id 

(4.49) 

Think  of  L  and  R  as  standing  for  /-value  and  r-value,  respectively,  and  *  as  an 
operator  indicating  "contents  of."5  T he  canonical  collection  of  sets  of  LR(0) 
items  for  grammar  (4.49)  is  shown  in  Fig.  4.39. 

I5: 

L- > i d-

I6: 

S->L=R 
-L 

R-^ 
L-t 
L  -> 

*R 
id 

lr. 

L-+*R-

I8:  R  -+  L-

h: 

S-+L  =  R-

I0: 

S'-*-S 
S  ->  L  =  R 
S^-R 
L  ->  •  * R 
L  ->•  id 
R-+-L 

h: 

S'-+S- 

I2: 

h: 

h: 

S-*L-  =  R 
R^L-

S-+R-

L->*-R 

R^-L 
L -> 
L 

*R 
id 

Figure  4.39:  Canonical  LR(0)  collection  for  g r a m m ar  (4.49) 

Consider  the  set  of  items  I2.  The  first  item  in  this  set  makes  A C T I O N [ 2 , =] 
be  "shift  6."  Since  F O L L O W (J R)  contains  =  (to  see  why,  consider  the  derivation 
S 
*R  -  R),  t he  second item  sets  ACTlON[2,  =]  to  "reduce  R  ->  L." 
Since  there  is  both  a  shift  and  a  reduce  entry  in  A C T I O N [ 2 , = ],  state  2  has  a 
shift/reduce  conflict  on  input  symbol  =. 

L  =  R 

G r a m m ar  (4.49)  is  not  ambiguous.  This  shift/reduce  conflict  arises  from 
t he  fact  t h at  the  SLR  parser  construction  method  is  not  powerful  enough  to 
remember  enough  left  context  to  decide  what  action  t he  parser  should  take  on 
input  =,  having  seen  a  string  reducible  to  L.  T he  canonical  and  LALR  methods, 
to  be  discussed  next,  will  succeed  on  a  larger  collection  of  grammars,  including 

5As  in  Section  2.8.3,  an  /-value  designates  a  location  and  an  r-value  is  a  value  that  can  be 

stored  in  a  location. 

256 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

g r a m m ar  (4.49).  Note,  however,  t h at  there  are  unambiguous  g r a m m a rs  for 
which  every  LR  parser  construction  method  will  produce  a  parsing  action  table 
with  parsing  action  conflicts.  Fortunately,  such  grammars  can  generally  be 
avoided  in  programming  language  applications. 

• 

4.6.5  Viable  Prefixes 

Why  can  LR(0)  a u t o m a ta  be  used  to  make  shift-reduce  decisions?  T he  LR(0) 
automaton  for  a  grammar  characterizes  t he  strings  of  g r a m m ar  symbols  t h at 
can  appear  on  t he  stack  of  a  shift-reduce  parser  for  the  grammar.  T he  stack 
contents  must  be  a  prefix  of  a  right-sentential  form. 
If  the  stack  holds  a  and 
t he  rest  of  t he  input  is  x,  then  a  sequence  of  reductions  will  take  ax  to  S.  In 
terms  of  derivations,  S 

ax. 

rm 

Not  all  prefixes  of  right-sentential  forms  can  appear  on  the  stack,  however, 

since  t he  parser  must  not  shift  past  the  handle.  For  example,  suppose 

#4 

F*id=> 

(E)*id 

rm 

rm 

Then,  at  various  times  during  t he  parse,  t he  stack  will  hold  (,  (E,  and  (E),  but 
it  must  not  hold  (E)*,  since  (E)  is  a  handle,  which  t he  parser  must  reduce  to 
F  before  shifting  *. 

The  prefixes  of right  sentential  forms  t h at  can  appear  on  t he  stack  of a  shift-

reduce  parser  are  called  viable  prefixes.  They  are  defined  as  follows:  a  viable 
prefix  is  a  prefix  of  a  right-sentential  form  t h at  does  not  continue  past  t he  right 
end  of  t he  rightmost  handle  of  t h at  sentential  form.  By  this  definition,  it  is 
always  possible  to  add  terminal  symbols  to  the  end  of  a  viable  prefix  to  obtain 
a  right-sentential  form. 

SLR  parsing  is  based  on  the  fact  t h at  LR(0)  a u t o m a ta  recognize  viable 
is  valid  for  a  viable  prefix  a  fa  if  there  is  a 
prefixes.  We  say  item  A  -» 
derivation  S'  a  Aw  =>  afafaw.  In  general,  an  item  will  be  valid  for  many 

fa-fa 

rm 
viable  prefixes. 

rm 

fa-fa 

T he  fact  t h at  A  -» 

is  valid  for  a  fa  tells  us  a  lot  about  whether  to 
shift  or  reduce  when  we  find  a  fa  on  the  parsing  stack.  In  particular,  if  fa  ^  e, 
then  it  suggests  t h at  we  have  not  yet  shifted  t he  handle  onto  t he  stack,  so  shift 
is  our  move.  If  fa  =• e,  then  it  looks  as  if  A  ->•  fa  is  t he  handle,  and  we  should 
reduce  by  this  production.  Of course,  two  valid  items  may  tell  us  to  do  different 
things  for  the  same  viable  prefix.  Some  of  these  conflicts  can  be  resolved  by 
looking  at  t he  next  input  symbol,  and  others  can  be  resolved  by  the  methods 
of  Section  4.8,  but  we  should  not  suppose  t h at  all  parsing  action  conflicts  can 
be  resolved  if  t he  LR  method  is  applied  to  an  arbitrary  grammar. 

We  can  easily  compute  the  set  of  valid  items  for  each  viable  prefix  t h at 
can  appear  on  t he  stack  of  an  LR  parser. 
In  fact,  it  is  a  central  theorem  of 
LR-parsing  theory  t h at  the  set  of  valid  items  for  a  viable  prefix  7  is  exactly 
the  set  of  items  reached  from  the  initial  state  along  the  p a th  labeled  7  in  t he 
LR(0)  a u t o m a t on  for  the  grammar.  In  essence,  the  set  of  valid  items  embodies 

4.6. 

INTRODUCTION  TO  LR  PARSING:  SIMPLE  LR 

257 

Items  as  States  of an  NFA 

A  nondeterministic  finite  a u t o m a t on  N  for  recognizing  viable  prefixes  can 
be  constructed  by  treating  the  items  themselves  as  states.  There  is  a 
transition  from  A  -+  a-X/3  to  A 
-+  aX-j3  labeled  X,  and  there  is  a 
transition  from  A  ->  a-Bj3  to  B  -+  -7  labeled  e.  T h en  CLOSURE(J)  for 
set  of  items  (states  of  N)  I  is  exactly  the  e-closure  of  a  set  of  NFA  states 
defined  in  Section  3.7.1.  Thus,  GOTO (I, X)  gives  the  transition  from  I 
on  symbol  X  in  the  DFA  constructed  from  N  by  the  subset  construction. 
Viewed  in  this  way,  the  procedure  items(G')  in  Fig.  4.33  is  just  the  subset 
construction  itself  applied  to  t he  NFA  N  with  items  as  states. 

all  the  useful  information  t h at  can  be  gleaned  from  t he  stack.  While  we  shall 
not  prove  this  theorem  here,  we  shall  give  an  example. 

E x a m p le  4 . 5 0:  Let  us  consider  the  augmented  expression  g r a m m ar  again, 
whose  sets  of  items  and  GOTO  function  are  exhibited  in  Fig.  4.31.  Clearly,  t he 
string  E  +  T*  is  a  viable  prefix  of  the  grammar.  The  a u t o m a t on  of  Fig.  4.31 
will  be  in  state  7  after  having  read  E  +  T*.  State  7  contains  the  items 

T  -+  T*  -F 
F  ->  -(E) 
F-> 

id 

which  are  precisely  the  items  valid  for  E+T*.  To  see  why,  consider  t he  following 
three  rightmost  derivations 

E' 

E 

E' 

E 

E' 

E 

rm 

rm 

rm 

E+T 

E  +  T  *F 

rm 

rm 

rm 

E  + T 

E  +  T*F 

rm 
=>  E  + T 
rm 

E  +  T*F 

rm 
rm 

The  first  derivation  shows  the  validity  of  T  ->•  T  *  -F,  t he  second  t he  validity 
of  F  ->  -(E),  and  t he  third  the  validity  of  F  -+ 
id.  It  can  be  shown  t h at  there 
are  no  other  valid  items  for  E +  T*,  although  we  shall  not  prove  t h at  fact  here. 
• 

E  +  T*(E) 

E  +  T*id 

4.6.6  Exercises  for  Section  4.6 

E x e r c i se  4 . 6 . 1:  Describe  all  the  viable  prefixes  for  t he  following  grammars: 

a)  T he  g r a m m ar  S 

0 5 1 | 0 1 of  Exercise  4.2.2(a). 

258 

CHAPTER  4. 

SYNTAX  ANALYSIS 

I  b)  The  grammar  S - > S S + \ S S * \a  of  Exercise  4.2.1. 

!  c)  The  grammar  S 

S  (  S  )  |  e  of Exercise  4.2.2(c). 

E x e r c i se  4 . 6 . 2:  Construct  t he  SLR  sets  of items  for  the  (augmented)  grammar 
of  Exercise  4;2.1.  Compute  the  GOTO  function  for  these  sets  of  items.  Show 
the  parsing  table  for  this  grammar.  Is  t he  grammar  SLR? 

E x e r c i se  4 . 6 . 3:  Show  t he  actions  of your  parsing  table  from  Exercise  4.6.2  on 
the  input  aa  *  a+. 

E x e r c i se  4 . 6 . 4:  For  each  of  the  (augmented)  grammars  of  Exercise  4.2.2(a)-

(g): 

a)  Construct  t he  SLR  sets  of  items  and  their  GOTO  function. 

b)  Indicate  any  action  conflicts  in  your  sets  of  items. 

c)  Construct  the  SLR-parsing  table,  if  one  exists. 

E x e r c i se  4 . 6 . 5:  Show  t h at  t he  following  grammar: 

S 
A 
B 

-» 
-»• 
-> 

Aa  Ab  \  B  b  B  a 

e 
e 

is  LL(1)  but  not  S L R ( l ). 

E x e r c i se  4 . 6 . 6:  Show  t h at  the  following  grammar: 

S 
A 

S  A  |  A 
a 

-)• 

is  SLR(l)  but  not  LL(1). 

!!  E x e r c i se  4 . 6 . 7:  Consider  t he  family  of  grammars  Gn  defined  by: 

5 

-» 

Ai  bi 

for  1  <  i  <  n 

Ai 

-> 

aj  Ai  |  aj 

for  1  <  i,j  <  n  and  i  ^  j 

Show  t h a t: 

a)  Gn  has  2 n2  -  n  productions. 
b)  Gn  has  2n  +  n2  +  n  sets  of  LR(0)  items. 

c)  Gn  is  S L R ( l ). 

W h at  does  this  analysis  say  about  how  large  LR  parsers  can  get? 

4.7. 

MORE  POWERFUL  LR  PARSERS 

259 

!  E x e r c i se  4 . 6 . 8:  We  suggested  t h at  individual  items  could  be  regarded  as 
states  of  a  nondeterministic  finite  automaton,  while  sets  of  valid  items  are  the 
states  of  a  deterministic  finite  a u t o m a t on  (see  the  box  on  "Items  as  States  of 
an  NFA"  in  Section  4.6.5).  For  t he  grammar  S 
\  a  of 
Exercise  4.2.1: 

\  S  S  * 

S  S  + 

a)  Draw  the  transition  diagram  (NFA)  for  the  valid  items  of  this  g r a m m ar 

according  to  t he  rule  given  in  t he  box  cited  above. 

b)  Apply  t he  subset  construction  (Algorithm  3.20)  to  your  NFA  from  part 
(a).  How  does  the  resulting  DFA  compare  to  the  set  of  LR(0)  items  for 
the  grammar? 

!!  c)  Show  t h at  in  all  cases,  the  subset  construction  applied  to  t he  NFA  t h at 
comes  from  t he  valid  items  for  a  grammar  produces  t he  LR(0)  sets  of 
items. 

!  E x e r c i se  4 . 6 . 9:  T he  following  is  an  ambiguous  grammar: 

S 
A 

AS  \  b 
S  A\a 

-¥ 

Construct  for  this  grammar  its  collection  of  sets  of  LR(0)  items.  If  we  try  to 
build  an  LR-parsing  table  for  the  grammar,  there  are  certain  conflicting  actions. 
W h at  are  they?  Suppose  we  tried  to  use  the  parsing  table  by  nondeterminis-
tically  choosing  a  possible  action  whenever  there  is  a  conflict.  Show  all  the 
possible  sequences  of  actions  on  input  abab. 

4.7  More  Powerful  LR  Parsers 

In  this  section,  we  shall  extend  the  previous  LR  parsing  techniques  to  use  one 
symbol  of  lookahead  on  the  input.  There  are  two  different  methods: 

1.  T he  "canonical-LR"  or  just  "LR"  method,  which  makes  full  use  of  the 
lookahead  symbol(s).  This  method  uses  a  large  set  of  items,  called  t he 
LR(1)  items. 

2.  T he  "lookahead-LR"  or  "LALR"  method,  which  is  based  on  the  LR(0) 
sets  of items,  and  has  many  fewer  states  t h an  typical  parsers  based  on  the 
LR(1)  items.  By  carefully  introducing  lookaheads  into  t he  LR(0)  items, 
we  can  handle  many  more  grammars  with  the  LALR  method  t h an  with 
t he  SLR  method,  and  build  parsing  tables  t h at  are  no  bigger  t h an  t he 
SLR  tables.  LALR  is  the  method  of  choice  in  most  situations. 

After  introducing  b o th  these  methods,  we  conclude  with  a  discussion  of  how  to 
compact  LR  parsing  tables  for  environments  with  limited  memory. 

260 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

4.7.1  Canonical  LR(1)  Items 

We  shall  now  present  the  most  general  technique  for  constructing  an  LR  parsing 
table  from  a grammar.  Recall  t h at  in  t he  SLR method,  state  i  calls  for  reduction 
by  A  -»  a  if the  set  of items  I*  contains  item  [A  -¥  a-]  and  a  is  in  FOLLOW(A). 
In  some  situations,  however,  when  s t a te  i  appears  on  top  of  t he  stack,  t he 
viable  prefix  /3a  on  the  stack  is  such  t h at  (3A  cannot  be  followed  by  a  in  any 
right-sentential  form.  Thus,  t he  reduction  by  A  ->  a  should  be  invalid  on  input 
a. 

E x a m p le  4 . 5 1:  Let  us  reconsider  Example  4.48,  where  in  s t a te  2  we  had  item 
R  -»  I T,  which  could  correspond  to  A  —>  a  above,  and  a  could  be  the  =  sign, 
L 
which  is  in  F O L L O W ( E ).  Thus,  the  SLR  parser  calls  for  reduction  by  R 
in  state  2  with  =  as  t he  next  input  (the  shift  action  is  also  called  for,  because 
of  item  S  -»  L=R  in  state  2).  However,  there  is  no  right-sentential  form  of  t he 
grammar  in  Example  4.48  t h at  begins  R  =  ••• 
.  Thus  s t a te  2,  which  is  t he 
state  corresponding  to  viable  prefix  L  only,  should  not  really  call  for  reduction 
of  t h at  L  to  R. 

• 

It  is  possible  to  carry  more  information  in  t he  s t a te  t h at  will  allow  us  to 
rule  out  some  of  these  invalid  reductions  by  A  —»•  a.  By  splitting  states  when 
necessary,  we  can  arrange  to  have  each  state  of  an  LR  parser  indicate  exactly 
which  input  symbols  can  follow  a handle  a  for  which  there  is  a  possible  reduction 
to  A. 

T he  extra  information  is  incorporated  into  t he  s t a te  by  redefining  items  to 
include  a  terminal  symbol  as  a  second  component.  The  general  form  of an  item 
becomes  [A  ->•  a  •  /3,a],  where  A  ~»  a(3  is  a  production  and  a  is  a  terminal  or 
the  right  endmarker  $.  We  call  such  an  object  an  LR(1)  item.  T he  1  refers 
to  the  length  of  t he  second  component,  called  t he  lookahead  of  the  i t e m .6  T he 
a-(3, a],  where  ft  is  not  e, 
lookahead  has  no  effect  in  an  item  of  t he  form  [A 
b ut  an  item  of  the  form  [A  ->•  a-, a]  calls  for  a  reduction  by  A  -»  a  only  if  t he 
next  input  symbol  is  a.  Thus,  we  are  compelled  to  reduce  by  A  -»  a  only  on 
those  input  symbols  a  for  which  [A  -»  a-, a]  is  an  LR(1)  item  in  t he  state  on 
top  of  the  stack.  T he  set  of  such  a's  will  always  be  a  subset  of  FOLLOW(A), 
b ut  it  could  be  a  proper  subset,  as  in  Example  4.51. 

Formally,  we  say  LR(1)  item  [A  ->•  a-(3, a]  is  valid  for  a  viable  prefix  7  if 

there  is  a  derivation  S  ^>  6Aw 

5a0w,  where 

rm 

rm 

1.  7  =  Sa,  and 

2.  Either  a  is  t he  first  symbol  of  w,  or  w  is  e  and  a  is  $. 

E x a m p le  4 . 5 2:  Let  us  consider  t he  g r a m m ar 

6Lookaheads  that  are  strings  of  length  greater  than  one  are  possible,  of  course,  but  we 

shall  not  consider  such  lookaheads  here. 

4.7. 

MORE  POWERFUL  LR  PARSERS 

261 

S-+B 
B-^aB 

B 
| 

b 

There is  a rightmost  derivation  S  =>>  aaBab 

aaaBab.  We see t h at item  [J5  -> 

a-B,  a]  is  valid  for  a  viable  prefix  7  =  aaa  by  letting  5  =  aa,  A  =  B,  w  =  ab, 
=  5  in  t he  above  definition.  There  is  also  a  rightmost  derivation 
a  =  a,  and 
a-.B,$]  is 
BaB 
S 

BaaB.  From  this  derivation  we  see  t h at  item  [B 

rm 

rm 

rm 

rm 
valid  for  viable  prefix  Baa. 

• 

4.7.2  Constructing  LR(1)  Sets  of Items 

T he  m e t h od  for  building  t he  collection  of  sets  of valid  LR(1)  items  is  essentially 
t he  same  as  t he  one  for  building  the  canonical  collection  of  sets  of  LR(0)  items. 
We  need  only  to  modify  the  two  procedures  CLOSURE  and  G O T O. 

SetOfltems  CLOSURE(J)  { 

r e p e at 

for  (  each  item  [A  -»•  a-B(3, a]  in  I  ) 

for  (  each  production  B  ->  7  in  G'  ) 

for  (  each  terminal  6  in  FIRST(/3a)  ) 
add  [B  -»  -7,  b]  to  set  I; 

u n t il  no  more  items  are  added  to  I; 
r e t u rn  I; 

} 

SetOfltems  GOTO(Z,  X)  { 

initialize  J  to  be  t he  empty  set; 
for  (  each  item  [A  ->  a-X(3,  a]  in  /  ) 

add  item  [A  ->  aX-(3,  a]  to  set  J; 

r e t u rn  CLOSURE(J); 

} 

v o id 

} 

{ 

items(G') 
initialize  C to  CLOSURE({[5' ->• -5,$]}); 
r e p e at 

for  (  each  set  of  items  I  m  C  ) 

for  (  each  g r a m m ar  symbol  X  ) 

if  (  G O T O ( / , X)  is  not  empty  and  not  in  C  ) 

add  G O T O ( J,  X) 
u n t il  no  new  sets  of  items  are  added  to  C; 

to  C; 

Figure  4.40:  Sets-of-LR(l)-items  construction  for  grammar  G' 

2 62 

CHAPTER  4. 

SYNTAX  ANALYSIS 

To  appreciate  t he  new  definition  of  t he  CLOSURE  operation,  in  particular, 
why  b  must  be  in  FIRST(/3a),  consider  an  item  of the  form  [A  -»  a-B ft, a)  in  the 
set  of items  valid  for  some  viable  prefix  7.  T h en  t h e re  is  a  rightmost  derivation 
S  =£•  8Aax  =>•  SaBflax,  where  7  =  8a.  Suppose 

flax  derives  terminal  string 

rm 

rm 

by.  Then  for  each  production  of t he  form  B  -»  r\  for  some  rj,  we  have  derivation 
"fBby  =>  ynby.  Thus,  [B  -»  -n, b]  is  valid  for  7.  Note  t h at  b  can  be  t he 
S 

rm 

rm 

first  terminal  derived  from  ft,  or  it  is  possible  t h at  ft  derives  e  in  t he  derivation 
flax  by,  and  6  can  therefore  be  a.  To  summarize  b o th  possibilities  we  say 

rm 

t h at  b  can  be  any  terminal  in  FIRST  (Pax),  where  FIRST  is  t he  function  from 
Section  4.4.  Note  t h at  x  cannot  contain  t he  first  terminal  of  by,  so  FIRST  (Pax) 
=  F I R S T ( ^ a ).  We  now  give  the  LR(1)  sets  of items  construction. 

Io 

S'^-S,$ 
S^-CC,% 
C-y-cC,  c/d 
C-y-d, c/d 

S'->S-

h 
5 - > C - C ,! 
C  ->-cC,$ 
C->-d,$ 

h 
C- + c • C,c/d 
c-
-cC,  c/d 
C- + -d, c/d 

r d 
h 
c- + d-, c/d 

C 

h 
C-*CC;\ 

P 

C 

h 

S-*CC-,% 

h 
c^c-c; 
C->-cC,$ 
C-»-d,$ 

d 

C-*d-

C 

C->cC-,c/d 

Figure  4.41:  T he  G O TO  graph  for  g r a m m ar  (4.55) 

A l g o r i t hm  4 . 5 3:  Construction  of  t he  sets  of  LR(1)  items. 

I N P U T:  An  augmented  grammar  G'. 

O U T P U T:  T he  sets  of  LR(1)  items  t h at  are  t he  set  of  items  valid  for  one  or 
more  viable  prefixes  of  G'. 

4.7. 

MORE  POWERFUL  LR  PARSERS 

263 

M E T H O D:  T he  procedures  C L O S U RE  and  G O TO  and  the  main  routine  items 
for  constructing  t he  sets  of  items  were  shown  in  Fig.  4.40. 

• 

E x a m p le  4 . 5 4:  Consider  the  following  augmented  grammar. 

S' 
S 
C 

S 
CC 
cC 

-> 

|  d 

(4.55) 

We  begin  by  computing  t he  closure  of  {[S'  ->•  -5,$]}.  To  close,  we  match 
t he  item  [S' 
-S, $]  with  the  item  [A  ->  a-Bj3, a]  in  the  procedure  C L O S U R E. 
T h at  is,  A  =  S',  a  =  e,  5  =  S,  /5  =  e,  and  a  =  $.  Function  C L O S U RE  tells  us 
to  add  [B  ->•  -7,6]  for  each  production  B  ->  7  and  terminal  &  in  F I R ST  (/3a).  In 
terms  of  t he  present  grammar,  B  -y  7  must  be  5  -»•  C C,  and  since 
is  e  and 
a  is  $,  b  may  only  be  $.  Thus  we  add  [S  -+  -CC, $]. 

We  continue  to  compute  the  closure  by  adding  all  items  [C  -»  -7,6]  for  6 
a],  we  have 
in  F I R S T( C $ ).  T h at  is,  matching  [S  -»  -CC, $]  against  [A  ->• 
A  =  S,  a  =  e,  B  —  C,  /3  =  C,  and  a  =  $.  Since  C  does  not  derive  the  empty 
string,  F I R S T( C $)  =  F I R S T( C ).  Since  F I R S T ( C)  contains  terminals  c  and  d,  we 
add  items  [C  -y  -cC,c],  [C  ->  -cC, d],  [C  ->•  -d, c]  and  [C  -y  -d, d].  None  of  the 
new  items  has  a  nonterminal  immediately  to  the  right  of  the  dot,  so  we  have 
completed  our  first  set  of  LR(1)  items.  The  initial  set  of  items  is 

IQ  :  S —y  -S, $ 

S  -+  -CC,  $ 
C  ->  -cC,  c/d 
C  ->  -d,  c/d 

T he  brackets  have  been  omitted  for  notational  convenience,  and  we  use  t he 
-cC,  c/d]  as  a  shorthand  for  the  two  items  [C  -y  -cC,  c]  and 
notation  [C 
[C 

-cC,  d]. 

Now  we  compute  G O T O( J0, X)  for  the  various  values  of  X.  For  X  =  S  we 

must  close  t he  item  [S'  ->•  5-,  $].  No  additional  closure  is  possible,  since  t he 
dot  is  at  the  right  end.  Thus  we  have  the  next  set  of items 

h: 

S1  ->  5-,  $ 

For  X  =  C  we  close  [5  ->•  C-C,  $].  We  add  the  C-productions  with  second 
component  $  and  then  can  add  no  more,  yielding 

h: 

S-+  C-C,  $ 
C  -+  -cC,  $ 
C->-d,  $ 

Next,  let  X  =  c.  We  must  close  {[C  ->•  c-C,  c/d]}.  We  add  the  C-productions 
with  second  component  c/d,  yielding 

264 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

h: 

C 
c-C,  c/d 
C  ->•  -cC,  c/d 
C  ->  -d,  c/d 

Finally,  let  X  =  d,  and  we  wind  up  with  t he  set  of  items 

h  •*  C  ~»  d-,  c/d 

We  have  finished  considering  GOTO  on  I0.  We  get  no  new  sets  from  I1}  but  h 
has  goto's  on  C,  c,  and  d.  For  G O T O ( 72,  C)  we  get 

/5: 

S - + C C - ,$ 

no  closure  being  needed.  To  compute  G O T O( l 2,  c)  we  take  t he  closure  of 
{[C 

c-C,  $]},  to  obtain 

J6  :  C 
C 
C  ->  -d,  $ 

c-C,  $ 
-cC,  $ 

Note  t h at  16  differs  from  ^3  only  in  second  components.  We  shall  see  t h at  it 
is  common  for  several  sets  of  LR(1)  items  for  a  g r a m m ar  to  have  t he  same 
first  components  and  differ  in  their  second  components.  W h en  we  construct 
the  collection  of  sets  of  LR(0)  items  for  t he  same  grammar,  each  set  of  LR(0) 
items  will  coincide  with  the  set  of  first  components  of one  or  more  sets  of LR(1) 
items.  We  shall  have  more  to  say  about  this  phenomenon  when  we  discuss 
LALR  parsing. 

Continuing  with  the  GOTO  function  for  J2,  G O T O ( I2, d)  is  seen  to  be 

h  : 

C  -+d;  $ 

Turning  now  to  73,  t he  G O T O 's  of  I3  on  c  and  d  are  I3  and  h,  respectively,  and 
G O T O ( 73, C ) is 

Is: 

C 

cC-,  c /d 

74  and  h  have  no  G O T O ' s,  since  all  items  have  their  dots  at  the  right  end.  T he 
GOTO's  of  Ie  on  c  and  d  are  I6  and  I7,  respectively,  and  GOTO(76,  C)  is 

79  : 

C  ->  cO;  $ 

T he  remaining  sets  of  items  yield  no  G O T O ' s,  so  we  are  done.  Figure  4.41 

shows  t he  ten  sets  of  items  with  their  goto's. 

• 

4.7. 

MORE  POWERFUL  LR  PARSERS 

265 

4.7.3  Canonical  LR(1)  Parsing  Tables 

We  now  give  t he  rules  for  constructing  t he  LR(1)  ACTION  and  GOTO  functions 
from  t he  sets  of  LR(1)  items.  These  functions  are  represented  by  a  table,  as 
before.  T he  only  difference  is  in  the  values  of  the  entries. 

A l g o r i t hm  4 . 5 6:  Construction  of  canonical-LR  parsing  tables. 

I N P U T:  An  augmented  grammar  G'. 

O U T P U T:  T he  canonical-LR  parsing  table  functions  ACTION  and  GOTO  for  G'. 

M E T H O D: 

1.  Construct  C'  =  {Iq,  h,  •  •  •  ,  In},  t he  collection  of  sets  of  LR(1)  items  for 

G' 

2.  State  i  of  t he  parser  is  constructed  from  I;.  T he  parsing  action  for  state 

i  is  determined  as  follows. 

(a)  If  [A  ->  a-a(3,b]  is  in  I{  and  GOTO(2~;,a)  =  Ij,  then  set  ACTION[i,  a] 

to  "shift  j ."  Here  a  must  be  a  terminal. 

(b)  If  [A  ->•  a-,  a]  is  in  Ii,  A  ^  S',  then  set  ACTI0N[«,  a]  to  "reduce 

A  ->  a." 

(c)  If  [S'  -+  S-,  $]  is  in  h,  then  set  ACTION^',  $]  to  "accept." 

If  any  conflicting  actions  result  from  the  above  rules,  we  say  the  g r a m m ar 
is  not  LR(1).  T he  algorithm  fails  to  produce  a  parser  in  this  case. 

3.  T he  goto  transitions  for  state  i  are  constructed  for  all  nonterminals  A 

using  the  rule:  If  G O T O ( i j,  A)  =  Ij,  then  GOTO[z,  A]  =  j. 

4.  All  entries  not  defined  by  rules  (2)  and  (3)  are  m a de  "error." 

5.  The  initial  state  of the  parser  is  the  one  constructed  from  t he  set  of  items 

containing  [S'  ->•  -S,  $]. 

• 

T he  table  formed  from  the  parsing  action  and  goto  functions  produced  by 
Algorithm  4.44  is  called  the  canonical  LR(1)  parsing  table.  An  LR  parser  using 
this  table  is  called  a  canonical-LR(l)  parser. 
If  the  parsing  action  function 
has  no  multiply  defined  entries,  then  the  given  grammar  is  called  an  LR(1) 
grammar.  As  before,  we  omit  the  "(1)"  if  it  is  understood-

E x a m p le  4 . 5 7:  The  canonical  parsing  table  for  g r a m m ar  (4.55)  is  shown  in 
Pig.  4.42.  Productions  1,  2,  and  3  are  5  ^  CC,  C  ->  cC,  and  C  ->  d, 
respectively. 

• 

Every  S L R ( l)  g r a m m ar  is  an  LR(1)  grammar,  but  for  an  S L R ( l)  g r a m m ar 
t he  canonical  LR  parser  may  have  more  states  t h an  the  SLR  parser  for  the 
same  grammar.  The  g r a m m ar  of the  previous  examples  is  SLR  and  has  an  SLR 
parser  with  seven  states,  compared  with  the  ten  of  Fig.  4.42. 

266 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

ST A TE 
ST A TE 

A C T I ON 

G O TO 

S 

1 

C 

2 

5 
8 

9 

C 

D 

$ 

s3 

s4 

s6 
s3 
r3 

s7 
s4 
r3 

s6 

s7 

r2 

r2 

acc 

rl 

r3 

r2 

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 

Figure  4.42:  Canonical  parsing  table  for  g r a m m ar  (4.55) 

4.7.4  Constructing  LALR  Parsing  Tables 

We  now  introduce  our  last  parser  construction  method,  the  L A LR  (lookahead-
L R)  technique.  This  method  is  often  used  in  practice,  because  the  tables  ob 
tained  by  it  are  considerably  smaller  t h an  the  canonical  LR  tables,  yet  most 
common  syntactic  constructs  of  programming  languages  can  be  expressed  con 
veniently  by  an  L A LR  grammar.  T he  same  is  almost  t r ue  for  S LR  grammars, 
but  there  are  a  few  constructs  t h at  cannot  be  conveniently  handled  by  S LR 
techniques  (see  Example  4.48,  for  example). 

For  a  comparison  of  parser  size,  the  S LR  and  L A LR  tables  for  a  grammar 
always  have  t he  same  number  of  states,  and  this  number  is  typically  several 
hundred  states  for  a  language  like  C.  The  canonical  LR  table  would  typically 
have  several  thousand  states  for  t he  same-size  language.  Thus,  it  is  much  easier 
and  more  economical  to  construct  S LR  and  L A LR  tables  t h an  the  canonical 
LR  tables. 

By  way  of introduction,  let  us  again  consider  grammar  (4.55),  whose  sets  of 
L R ( 1)  items  were  shown  in  Fig.  4.41.  Take  a pair  of similar  looking  states,  such 
as I4  and  I 7.  Each  of these  states  has  only  items  with  first  component  C  ->  d-. 
In  I 4,  the  lookaheads  are  c  or  d;  in  I 7,  $  is  t he  only  lookahead. 

To  see  the  difference  between  the  roles  of  I±  and  I7  in  t he  parser,  note  t h at 
the  grammar  generates  t he  regular  language  c*dc*d.  When  reading  an  input 
cc • •  • cdcc • •  - cd,  t he  parser  shifts  t he  first  group  of  c's  and  their  following  d 
onto  t he  stack,  entering  state  4  after  reading  t he  d.  T he  parser  then  calls  for  a 
reduction  by  C  -»  d,  provided  t he  next  input  symbol  is  c  or  d.  T he  requirement 
t h at  c  or  d  follow  makes  sense,  since  these  are  t he  symbols  t h at  could  begin 
strings  in  c*d.  If  $  follows  t he  first  d,  we  have  an  input  like  ccd,  which  is  not 
in  the  language,  and  state  4  correctly  declares  an  error  if  $  is  t he  next  input. 

T he  parser  enters  state  7  after  reading  the  second  d.  Then,  the  parser  must 

4.7. 

MORE  POWERFUL  LR  PARSERS 

267 

see  $  on  the  input,  or  it  started  with  a  string  not  of  t he  form  c*dc*d.  It  thus 
makes  sense  t h at  state  7  should  reduce  by  C  -»  d  on  input  $  and  declare  error 
on  inputs  c  or  d. 

Let  us  now  replace  I4  and  Ij  by  J47,  the  union  of  I4  and  Ij,  consisting  of 
t he  set  of three  items  represented  by  [C  ->•  d-,  c/d/%].  T he  goto's  on  d  to  I4  or 
Ij  from  J0,  h,  h,  and 
any  input.  T he  revised  parser  behaves  essentially  like  the  original,  although  it 
might  reduce  d  to  C  in  circumstances  where  the  original  would  declare  error, 
for  example,  on  input  like  ccd  or  cdcdc.  The  error  will  eventually  be  caught;  in 
fact,  it  will  be  caught  before  any  more  input  symbols  are  shifted. 

i6  now  enter  J4 7.  T he  action  of  state  47  is  to  reduce  on 

More  generally,  we  can  look  for  sets  of  LR(1)  items  having  the  same  core, 
t h at  is,  set  of  first  components,  and  we  may  merge  these  sets  with  common 
cores  into  one  set  of  items.  For  example,  in  Fig.  4.41,  I4  and  Ij  form  such  a 
pair,  with  core  {C  -t  d-}.  Similarly,  73  and  IQ  form  another  pair,  with  core 
{C  —>•  c-C,  C  ->  -cC,  C  -»  -d}.  There  is  one  more pair,  78  and  IQ,  with  common 
core  {C  ->•  cC-}.  Note  t h a t,  in  general,  a  core  is  a  set  of  LR(0)  items  for  the 
grammar  at  hand,  and  t h at  an  LR(1)  g r a m m ar  may  produce  more  t h an  two 
sets  of  items  with  the  same  core. 

Since  the  core  of  GOTO(I,X)  depends  only  on  the  core  of  /,  the  goto's  of 
merged  sets  can  themselves  be  merged.  Thus,  there  is  no  problem  revising  t he 
goto  function  as  we  merge  sets  of  items.  The  action  functions  are  modified  to 
reflect  the  non-error  actions  of  all  sets  of  items  in  the  merger. 

Suppose  we  have  an  LR(1)  grammar,  t h at  is,  one  whose  sets  of LR(1)  items 
produce  no  parsing-action  conflicts.  If we  replace  all  states  having the  same  core 
with  their  union,  it  is  possible  t h at  the  resulting  union  will  have  a  conflict,  but 
it  is  unlikely  for  the  following  reason:  Suppose  in  the  union  there  is  a  conflict 
on  lookahead  a  because  there  is  an  item  [A  ->•  a-, a]  calling  for  a  reduction  by 
A  -»  a,  and  there  is  another  item  [B  -»  0-aj,  b]  calling  for  a  shift.  Then  some 
set  of  items  from  which  the  union  was  formed  has  item  [A  -»  a-, a],  and  since 
t he  cores  of  all  these  states  are  the  same,  it  must  have  an  item  [B  ->  /3-aj,c] 
for  some  c.  But  then  this  state  has  the  same  shift/reduce  conflict  on  a,  and 
t he  grammar  was  not  LR(1)  as  we  assumed.  Thus,  the  merging  of  states  with 
common  cores  can  never  produce  a  shift/reduce  conflict  t h at  was  not  present 
in  one  of  t he  original  states,  because  shift  actions  depend  only  on  the  core,  not 
t he  lookahead. 

It  is  possible,  however,  t h at  a  merger  will  produce  a  reduce/reduce  conflict, 

as  the  following  example  shows. 

E x a m p le  4 . 5 8:  Consider  the  grammar 

S' 
S 
A 
B 

S 
a  Ad 
c 
c 

-» 

j  b  B  d 

\  a  B  e 

|  b  Ae 

which  generates  the  four  strings  acd,  ace,  bed,  and  bee.  The  reader  can  check 
t h at  t he  g r a m m ar  is  LR(1)  by  constructing  the  sets  of  items.  Upon  doing  so, 

268 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

we  find  t he  set  of items  {[A-tc-,  d],  [B 
c-,  e]}  valid  for  viable  prefix  ac  and 
{[A-+c-,e],  [B  ->  c-,  d]}  valid  for  6c.  Neither  of  these  sets  has  a  conflict,  and 
their  cores  are  the  same.  However,  their  union,  which  is 

A  ->•  c-,  d/e 
B  -¥  c-,  d /e 

generates  a  reduce/reduce  conflict,  since  reductions  by  b o th  A  ->  c  and  B  ->  c 
are  called  for  on  inputs  d  and  e. 

• 

We  are  now  prepared  to  give  the  first  of  two  LALR  table-construction  al 
gorithms.  T he  general  idea  is  to  construct  t he  sets  of  LR(1)  items,  and  if  no 
conflicts  arise,  merge  sets  with  common  cores.  We  then  construct  t he  parsing 
table  from  the  collection  of  merged  sets  of  items.  T he  method  we  are  a b o ut  to 
describe  serves  primarily  as  a  definition  of  L A L R ( l)  g r a m m a r s.  Constructing 
the  entire  collection  of  LR(1)  sets  of items  requires  too  much  space  and  time  to 
be  useful  in  practice. 

A l g o r i t hm  4 . 5 9:  An  easy,  b ut  space-consuming  LALR  table  construction. 

I N P U T:  An  augmented  grammar  G'. 

O U T P U T:  T he  LALR  parsing-table  functions  ACTION  and  GOTO  for  G'. 

M E T H O D: 

1.  Construct  C  =  {IQ,  h,... 

,  7n},  t he  collection  of  sets  of  LR(1)  items. 

2.  For  each  core  present  among  the  set  of  LR(1)  items,  find  all  sets  having 

t h at  core,  and  replace  these  sets  by  their  union. 

3.  Let  C  = 

,Jm}  be 

{Jo,Ji,... 

T he 
parsing  actions  for  state  i  are  constructed  from  Ji  in  the  same  m a n n er  as 
in  Algorithm  4.56.  If there  is  a  parsing  action  conflict,  the  algorithm  fails 
to  produce  a  parser,  and  the  g r a m m ar  is  said  not  to  be  L A L R ( l ). 

the  resulting  sets  of  LR(1) 

items. 

4.  T he  GOTO  table  is  constructed  as  follows. 

If  J  is  the  union  of  one  or 
more  sets  of  LR(1)  items,  t h at  is,  J  =  h  n  h  n  • • •  n  h,  then  t he 
cores  of  G O T O ( I i,  X),  G O T O ( J2,  X),... 
,  G O T O ( If c,  X)  are  t he  same,  since 
J i,  J2, . ..  ,h  all  have  t he  same  core.  Let  K  be  t he  union  of  all  sets  of 
items  having  t he  same  core  as  G O T O ( J i , X ).  T h en  G O T O ( J , X)  =  K. 

a 

T he  table  produced  by  Algorithm  4.59  is  called  t he  LALR  parsing  table  for 
G.  If  there  are  no  parsing  action  conflicts,  then  t he  given  g r a m m ar  is  said  to 
be  an  LALR(l)  grammar.  T he  collection  of  sets  of  items  constructed  in  step 
(3) 

is  called  the  LALR(l)  collection. 

4.7. 

MORE  POWERFUL  LR  PARSERS 

269 

E x a m p le  4 . 6 0:  Again  consider  g r a m m ar  (4.55)  whose  GOTO  graph  was  shown 
in  Fig.  4.41.  As  we  mentioned,  there  are  three  pairs  of  sets  of  items  t h at  can 
be  merged.  I3  and  IQ  are  replaced  by  their  union: 

73 a: 

C-^c-C,  c/d/% 
C  ->  -cC,  c/d/% 
C 

-d,  c/d/% 

h  and  I7  are  replaced  by  their  union: 

J4 7: 

C  ->  d-,  c/d/% 

and  Is  and  IQ  are  replaced  by  their  union: 

I8 9: 

C 

cC-,  c/d/% 

T he  LALR  action  and  goto  functions  for  the  condensed  sets  of items  are  shown 
in  Fig.  4.43. 

ST A TE 
ST A TE 

0 
1 
2 
36 
47 
5 
89 

A C T I ON 

G O TO 

c 
2 

5 
89 

C 

d 

$ 

s36 

s47 

S 
1 

s36 
s36 
r3 

s47 
s47 
r3 

r2 

r2 

acc 

r3 
rl 
r2 

Figure  4.43:  LALR  parsing  table  for  t he  grammar  of  Example  4.54 

To  see  how  t he  GOTO's  are  computed,  consider  GOTO(73 6,  C).  In  the  original 
set  of  LR(1)  items,  GOTO(73,  C)  =  h,  and  Is  is  now  p a rt  of  789,  so  we  make 
GOTO(J36,C)  be  789-  We  could  have  arrived  at  the  same  conclusion  if  we 
considered  76,  the  other  p a rt  of  73g.  T h at  is,  GOTO(76, C)  =  7g,  and  IQ  is 
now  p a rt  of  7g9.  For  another  example,  consider  GOTO(72,c),  an  entry  t h at  is 
exercised  after  the  shift  action  of  I2  on  input  c. 
In  t he  original  sets  of  LR(1) 
items,  GOTO(72,c)  =  76.  Since  76  is  now  p a rt  of  736,  GOTO(72,c)  becomes  736. 
Thus,  the  entry  in  Fig.  4.43  for  state  2  and  input  c  is  made  s36,  meaning  shift 
and  push  s t a te  36  onto  t he  stack. 

• 

W h en  presented  with  a  string  from  the  language  c*dc*d,  both  the  LR  parser 
of  Fig.  4.42  and  t he  LALR  parser  of  Fig.  4.43  make  exactly  the  same  sequence 
of  shifts  and  reductions,  although  t he  names  of  t he  states  on  the  stack  may 
differ.  For  instance,  if  the  LR  parser  puts  73  or  76  on  t he  stack,  t he  LALR 

270 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

parser  will  put  I36  on  the  stack.  This  relationship  holds  in  general  for  an  LALR 
grammar.  The  LR  and  LALR  parsers  will  mimic  one  another  on  correct  inputs. 
When  presented  with  erroneous  input,  t he  LALR  parser  may  proceed  to  do 
some  reductions  after  the  LR  parser  has  declared  an  error.  However,  the  LALR 
parser  will  never  shift  another  symbol  after  t he  LR  parser  declares  an  error. 
For  example,  on  input  ccd  followed  by  $,  the  LR  parser  of  Fig.  4.42  will  put 

0  3  3  4 

on  the  stack,  and  in  state  4  will  discover  an  error,  because  $  is  t he  next  input 
symbol  and  state  4  has  action  error  on  $.  In  contrast,  t he  LALR  parser  of  Fig. 
4.43  will  make  the  corresponding  moves,  putting 

0  36  36  47 

on  the  stack.  But  state  47  on  input  $  has  action  reduce  C  —>•  d.  T he  LALR 
parser  will  thus  change  its  stack  to 

Now  t he  action  of  state  89  on  input  $  is  reduce  C  -»•  cC.  T he  stack  becomes 

0  36  36  89 

whereupon  a  similar  reduction  is  called  for,  obtaining  stack 

0  36  89 

0  2 

Finally,  state  2  has  action  error  on  input  $,  so  t he  error  is  now  discovered. 

4.7.5  Efficient  Construction  of  LALR  Parsing  Tables 

There  are  several  modifications  we  can  make  to  Algorithm  4.59  to  avoid  con 
structing  t he  full  collection  of  sets  of  LR(1)  items  in  the  process  of  creating  an 
L A L R ( l)  parsing  table. 

•  First,  we  can  represent  any  set  of  LR(0)  or  LR(1)  items  I  by  its  kernel, 
t h at  is,  by  those  items  t h at  are  either  t he  initial  item  —  [S' 
-S]  or 
[S'  ->•  -5,  $]  — or  t h at  have the  dot  somewhere  other t h an  at  the  beginning 
of  the  production  body. 

•  We  can  construct  t he  LALR(l)-item  kernels  from  t he  LR(0)-item  kernels 
by  a  process  of  propagation  and  spontaneous  generation  of  lookaheads, 
t h at  we  shall  describe  shortly. 

•  If  we  have  the  L A L R ( l)  kernels,  we  can  generate  t he  L A L R ( l)  parsing 
table  by  closing  each  kernel,  using t he function  CLOSURE  of Fig.  4.40,  and 
then  computing  table  entries  by  Algorithm  4.56,  as  if  t he  L A L R ( l)  sets 
of  items  were  canonical  LR(1)  sets  of  items. 

4.7. 

MORE  POWERFUL  LR  PARSERS 

271 

E x a m p le  4 . 6 1:  We  shall  use  as  an  example  of  the  efficient  L A L R ( l)  table-
construction  m e t h od  t he  non-SLR  g r a m m ar  from  Example  4.48,  which  we  re 
produce  below  in  its  augmented  form: 

S' 
S 
L 
R 

-> 
-> 
-> 
-> 

S 
L  =  R 
*R 
L 

| 

j  R 

id 

T he  complete  sets  of  LR(0)  items  for  this  grammar  were  shown  in  Fig.  4.39. 
T he  kernels  of  these  items  are  shown  in  Fig.  4.44. 

• 

l o: 

S'->-S 

Ii: 

S'-+S-

h: 

h: 

h: 

S^L-  =  R 
R->L-

S-+R-

L  -»  *R 

h: 

h: 

h: 

h: 

h: 

L  ->•  id-

S-^L  = 

-R 

L  -»•  *R-

R^L-

S-+L  =  R-

Figure  4.44:  Kernels  of  the  sets  of  LR(0)  items  for  g r a m m ar  (4.49) 

Now  we  must  attach  the  proper  lookaheads  to  the  LR(0)  items  in  the  kernels, 
to  create  t he  kernels  of  t he  sets  of  L A L R ( l)  items.  T h e re  are  two  ways  a 
lookahead  b  can  get  attached  to  an  LR(0)  item  B  -»•  j-8  in  some  set  of L A L R ( l) 
items  J: 

1.  There  is  a  set  of  items  7,  with  a  kernel  item  A  —>  a-/3, a,  and  J  = 

G O T O( 7 , X ),  and  the  construction  of 

GOTO(cLOSURE({[A 

-»  a-/3,a]}),X) 

as  given  in  Fig.  4.40,  contains  [B  ->  7-5,6],  regardless  of  a.  Such  a  looka 
head  b  is  said  to  be  generated  spontaneously  for  B  ->  ^-8. 

2.  As  a  special  case,  lookahead  $  is  generated  spontaneously  for  the  item 

S'  ->  -S  in  t he  initial  set  of  items. 

3.  All  is  as  in  (1),  but  a  =  6,  and  G O T o ( c L O S U R E ( { [^ 

& ] } ) ,X ),  as 
given  in  Fig.  4.40,  contains  [73  —>  7-6, b]  only  because  A  —>•  a-(3  has  b  as 
one  of  its  associated  lookaheads.  In  such  a  case,  we  say  t h at  lookaheads 
propagate  from  A  —>  a-/3  in  t he  kernel  of  7  to  73  —»  j-8  in  the  kernel  of 
J.  Note  t h at  propagation  does  not  depend  on  the  particular  lookahead 
symbol;  either  all  lookaheads  propagate  from  one  item  to  another,  or  none 
do. 

272 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

We  need  to  determine  the  spontaneously  generated  lookaheads  for  each  set 
of  LR(0)  items,  and  also  to  determine  which  items  propagate  lookaheads  from 
which.  T he  test  is  actually  quite  simple.  Let  #  be  a  symbol  not  in  the  g r a m m ar 
at  hand.  Let  A  -y  a-(3  be  a  kernel  LR(0)  item  in  set  I.  Compute,  for  each  X, 
J  -  GOTo(CLOSURE({[A 
For  each  kernel  item  in  J,  we 
examine  its  set  of  lookaheads.  If  #  is  a  lookahead,  then  lookaheads  propagate 
to  t h at  item  from  A  -y  a-(3.  Any  other  lookahead  is  spontaneously  generated. 
These  ideas  are  made  precise  in  the  following  algorithm,  which  also  makes  use 
of  the  fact  t h at  the  only  kernel  items  in  J  must  have  X  immediately  to  t he  left 
of  the  dot;  t h at  is,  they  must  be  of  t he  form  B  -y  jX-6. 

->  a-p,#]}),X). 

A l g o r i t hm  4 . 6 2:  Determining  lookaheads. 

I N P U T:  T he  kernel  K  of  a  set  of  LR(0)  items  /  and  a  g r a m m ar  symbol  X. 

O U T P U T:  T he  lookaheads  spontaneously  generated  by  items  in  I  for  kernel 
items  in  G O T O ( I , X)  and  the  items  in  i"  from  which  lookaheads  are  propagated 
to  kernel  items  in  G O T O ( / , X ). 

M E T H O D:  T he  algorithm  is  given  in  Fig.  4.45. 

• 

for  (  each  item  A  —y  a-(3  in  K  )  { 

J  :=  C L O S U R E ( { [^  -y  a-/3,#]}  ); 
if  (  [B  -y  j-XS,  a]  is  in  J,  and  a  is  not  #  ) 

conclude  t h at  lookahead  a  is  generated  spontaneously  for  item 

in  GOTO(7,  X); 

-y 
B 
[B-yrX6,#] 
conclude  t h at  lookaheads  propagate  from  A  -y  a-(3  in  I  to 

jX-S 
is 

in  J  ) 

B 

-y 

jX-S 

in  G O T O ( 7 , X ); 

if  ( 

} 

Figure  4.45:  Discovering  propagated  and  spontaneous  lookaheads 

We  are  now  ready  to  attach  lookaheads  to  t he  kernels  of  the  sets  of  LR(0) 
items  to  form  the  sets  of  L A L R ( l)  items.  First,  we  know  t h at  $  is  a  looka 
head  for  S'  -y  -S  in  the  initial  set  of  LR(0)  items.  Algorithm  4.62  gives  us  all 
the  lookaheads  generated  spontaneously.  After  listing  all  those  lookaheads,  we 
must  allow  t h em  to  propagate  until  no  further  propagation  is  possible.  There 
are  many  different  approaches,  all  of  which  in  some  sense  keep  track  of  "new" 
lookaheads  t h at  have  propagated  into  an  item  b ut  which  have  not  yet  propa 
gated  out.  T he  next  algorithm  describes  one  technique  to  propagate  lookaheads 
to  all  items. 

A l g o r i t hm  4 . 6 3:  Efficient  computation  of  the  kernels  of  t he  L A L R ( l)  collec 
tion  of  sets  of  items. 

I N P U T:  An  augmented  grammar  G'. 

4.7. 

MORE  POWERFUL  LR  PARSERS 

273 

O U T P U T:  T he  kernels  of  the  L A L R ( l)  collection  of  sets  of  items  for  G'. 

M E T H O D: 

1.  Construct  t he  kernels  of  the  sets  of  LR(0)  items  for  G.  If  space  is  not  at 
a  premium,  t he  simplest  way  is  to  construct  t he  LR(0)  sets  of items,  as  in 
Section  4.6.2,  and  then  remove  the  nonkernel  items.  If  space  is  severely 
constrained,  we  may  wish  instead  to  store  only  the  kernel  items  for  each 
set,  and  compute  GOTO  for  a  set  of items  I  by  first  computing  the  closure 
o f /. 

2.  Apply  Algorithm  4.62  to  the  kernel  of  each  set  of  LR(0)  items  and  gram 
m ar  symbol  X  to  determine  which  lookaheads  are  spontaneously  gener 
ated  for  kernel  items  in  G O T O ( J,  X),  and  from  which  items  in  I  lookaheads 
are  propagated  to  kernel  items  in  G O T O ( / , X ). 

3.  Initialize  a  table  t h at  gives,  for  each  kernel  item  in  each  set  of  items,  the 
Initially,  each  item  has  associated  with  it  only 
associated  lookaheads. 
those  lookaheads  t h at  we  determined  in  step  (2)  were  generated  sponta 
neously. 

4.  Make  repeated  passes  over  the  kernel  items  in  all  sets.  W h en  we  visit  an 
item  i,  we  look  up  the  kernel  items  to  which  i  propagates  its  lookaheads, 
using  information  tabulated  in  step  (2).  T he  current  set  of  lookaheads 
for  i  is  added  to  those  already  associated  with  each  of  the  items  to  which 
i  propagates  its  lookaheads.  We  continue  making  passes  over  the  kernel 
items  until  no  more  new  lookaheads  are  propagated. 

• 

E x a m p le  4 . 6 4:  Let  us  construct  t he  kernels  of  t he  L A L R ( l)  items  for  the 
g r a m m ar  of  Example  4.61.  The  kernels  of  the  LR(0)  items  were  shown  in 
Fig.  4.44.  W h en  we  apply  Algorithm  4.62  to  the  kernel  of  set  of  items  Io,  we 
first  compute  CLOSURE({[S"  ->>  -5, # ] } ),  which  is 

S'^-S,  # 
S  ->-L  =  R,  # 
S^-R,  # 

L ->  • . £ , . #/  = 
L  ->  -id,  #/  = 
R-+-L, 

# 

Among  the  items  in  the  closure,  we  see  two  where  the  lookahead  =  has  been 
generated  spontaneously.  The  first  of  these  is  L  ->•  •  *  R.  This  item,  with  *  to 
the  right  of  the  dot,  gives  rise  to  [L  ->•  * • # , = ]•  T h at  is,  =  is  a  spontaneously 
generated  lookahead  for  L  ->  *-R,  which  is  in  set  of  items  J4.  Similarly,  [L  ->• 
•id,  =]  tells  us  t h at  =  is  a  spontaneously  generated  lookahead  for  L  ->•  id-  in 
h¬ 

As  #  is  a  lookahead  for  all  six  items  in  the  closure,  we  determine  t h at  the 

item  S'  ->  -S  in  J0  propagates  lookaheads  to  the  following  six  items: 

274 

CHAPTER 

4, 

SYNTAX  ANALYSIS 

S'  ->  S-  in  ii 
£  ->•  L-  =  R  in  72 
5  ->  i2-  in  i3 

in  i4 
L  -> 
L 
id-  in  i5 
R-+  L-  in  i2 

FR OM 

i0: 

5" 

-5 

i2: 

i4: 

S^L-  =  R 

L  -*  *R 

i6: 

S-+L  =  -R 

To 

i i: 
S ' - ^ S-
i2: 
S-+L-  =  R 
i2: 
R-+  L-
i3: 
S - » i 2-
i4:  x -» 
L  -+  id-
i5: 

i6: 

i4: 
i5: 
i7: 
i8: 

i4: 
i5: 
i s: 
i9: 

S ^L  =  -R 

L  ->  *-i? 
L  -»  id-
L 
*E-
i ? - + L-

L  ->  *-i? 
£  -»  id-

S  ->L  =  R-

Figure  4.46:  Propagation  of  lookaheads 

In  Fig.  4.47,  we  show  steps  (3)  and  (4)  of  Algorithm  4.63.  T he  column 
labeled  INIT  shows  t he  spontaneously  generated  lookaheads  for  each  kernel  item. 
These  are  only  the  two  occurrences  of  =  discussed  earlier,  and  t he  spontaneous 
- 5. 
lookahead  $  for  the  initial  item  S' 

On  t he  first  pass,  t he  lookahead  $  propagates  from  S'  —>•  S  in  IQ  to  t he 
six  items  listed  in  Fig.  4.46.  T he  lookahead  =  propagates  from  L  ->  *-R  in  i4 
to  items  L  -»  *  R-  in  I?  and  R  ->  L-  in  Is-  It  also  propagates  to  itself  and  to 
L  —»• id •  in  I5,  but  these  lookaheads  are already present.  In  the  second  and  third 
passes,  the  only  new  lookahead  propagated  is  $,  discovered  for  t he  successors  of 
i2  and  i4  on  pass  2  and  for  the  successor  of IQ  on  pass  3.  No  new  lookaheads  are 
propagated  on  pass  4,  so  t he  final  set  of  lookaheads  is  shown  in  t he  rightmost 
column  of Fig.  4.47. 

Note  t h at  the  shift/reduce  conflict  found  in  Example  4.48  using  t he  SLR 
method  has  disappeared  with  the  LALR  technique.  T he  reason  is  t h at  only 
lookahead  $  is  associated  with  R  -»  L-  in  i2,  so  there  is  no  conflict  with  t he 
parsing  action  of  shift  on  =  generated  by  item  5  -»  L=R  in  i2. 

• 

4.7. 

MORE  POWERFUL  LR  PARSERS 

2 75 

SET 
SET 

IT EM 
IT EM 

LO O K A H E A DS 

IN IT 

PA SS 

1 

PA SS 

2 

PA SS 

3 

Jo: 

S' 

-5 

$ 

h: 

h: 

is: 

J4: 

I5: 

h: 

It-

IS: 

h: 

= 

S ^ L- 
R^tL-

S^R-

L  -» 

L- M d-

S - +L 

= 

L 

R^L-

= 

= 

$ 

$ 

$ 
$ 

$ 

= /$ 

=/$ 

= 

= 

$ 

$ 

$ 
$ 

$ 

$ 

$ 

$ 
$ 

$ 

=/$  =1% 

=/$ 

=/$ 

$ 

=/$ 

= /$ 

$ 

=/$ 

=/$ 

$ 

Figure  4 . 4 7:  Computation  of lookaheads 

4.7.6  Compaction  of  LR  Parsing  Tables 

A  typical  programming  language  grammar  with  50  to  1 00  terminals  and  1 00 
productions  may  have  an  L A LR  parsing  table  with  several  hundred  states.  T he 
action  function  may  easily  have  2 0 , 0 00  entries,  each  requiring  at  least  8  bits 
to  encode.  On  small  devices,  a  more  efficient  encoding  t h an  a  two-dimensional 
array  may  be  important.  We  shall  mention  briefly  a  few  techniques  t h at  have 
been  used  to  compress  t he  A C T I ON  and  G O TO  fields  of  an  LR  parsing  table. 

One  useful  technique  for  compacting  the  action  field  is  to  recognize  t h at 
usually  many  rows  of the  action  table  are  identical.  For  example,  in  Fig.  4 . 4 2, 
states  0  and  3  have  identical  action  entries,  and  so  do  2  and  6.  We  can  therefore 
save  considerable  space,  at  little  cost  in  time,  if  we  create  a  pointer  for  each 
state  into  a  one-dimensional  array.  Pointers  for  states  with  the  same  actions 
point  to  t he  same  location.  To  access  information  from  this  array,  we  assign 
each  terminal  a  number  from  zero  to  one  less  t h an  the  number  of  terminals, 
and  we  use  this  integer  as  an  offset  from  the  pointer  value  for  each  state. 
In 
a  given  state,  the  parsing  action  for  the  i th  terminal  will  be  found  i  locations 
past  the  pointer  value  for  t h at  state. 

Further  space  efficiency  can  be  achieved  at  the  expense  of a  somewhat  slower 
parser  by  creating  a  list  for  the  actions  of  each  state.  T he  list  consists  of 
(terminal-symbol,  action)  pairs.  The  most  frequent  action  for  a  state  can  be 

276 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

placed  at  the  end  of the  list,  and  in  place  of a  terminal  we  may  use  the  notation 
" a n y ,"  meaning  t h at  if  the  current  input  symbol  has  not  been  found  so  far  on 
t he  list,  we  should  do  t h at  action  no  m a t t er  what  t he  input  is.  Moreover,  error 
entries  can  safely  be  replaced  by  reduce  actions,  for  further  uniformity  along  a 
row.  The  errors  will  be  detected  later,  before  a  shift  move. 

E x a m p le  4 . 6 5:  Consider  t he  parsing  table  of  Fig.  4.37.  First,  note  t h at  t he 
actions  for  states  0,  4,  6,  and  7  agree.  We  can  represent  t h em  all  by  t he  list 

State  1  has  a  similar  list: 

SY M B OL 
id 

( 
a ny 

AC T I ON 
s5 
s4 
error 

+ 

a ny 

s6 
acc 
error 

In  state  2,  we  can  replace  the  error  entries  by  r2,  so  reduction  by  production  2 
will  occur  on  any  input  but  *.  Thus  t he  list  for  state  2  is 

a ny 

s7 
r2 

State  3  has  only  error  and  r4  entries.  We  can  replace  t he  former  by  t he 
latter,  so  the  list  for  state  3  consists  of  only  the  pair  (any,  r4).  States  5,  10, 
and  11  can  be  treated  similarly.  T he  list  for  state  8  is 

+ 

a ny 

a ny 

s6 
s ll 
error 

s7 
s ll 
rl 

and  for  state  9 

• 

We  can  also  encode  the  G O TO  table  by  a  list,  but  here  it  appears  more 
efficient  to  make  a  list  of  pairs  for  each  nonterminal  A.  Each  pair  on  t he  list 
for  A 

(currentState,nextState), 

indicating 

is  of  t he 

form 

G O TO  [currentState,  A]  =  next  State 

4.7. 

MORE  POWERFUL  LR  PARSERS 

277 

This  technique  is  useful  because  there  tend  to  be  rather  few  states  in  any  one 
column  of  t he  GOTO  table.  T he  reason  is  t h at  t he  GOTO  on  nonterminal  A 
can  only  be  a  state  derivable  from  a  set  of  items  in  which  some  items  have  A 
immediately  to  t he  left  of  a  dot.  No  set  has  items  with  X  and  Y  immediately 
to  t he  left  of  a  dot  if  X  ^  Y.  Thus,  each  state  appears  in  at  most  one  GOTO 
column. 

For  more  space  reduction,  we  note  t h at  the  error  entries  in  t he  goto  table  are 
never  consulted.  We  can  therefore  replace  each  error  entry  by  the  most  common 
non-error  entry  in  its  column.  This  entry  becomes  t he  default;  it  is  represented 
in  the  list  for  each  column  by  one  pair  with  a ny  in  place  of  currentState. 

E x a m p le  4 . 6 6:  Consider  Fig.  4.37  again.  T he  column  for  F  has  entry  10  for 
state  7,  and  all  other  entries  are  either  3  or  error.  We  may  replace  error  by  3 
and  create  for  column  F  the  list 

CURRENTSTATE 
7 
a ny 

NEXTSTATE 
10 
3 

Similarly,  a  suitable  list  for  column  T  is 

6 
a ny 

9 
2 

For  column  E  we  may  choose  either  1  or  8  to  be  the  default;  two  entries  are 
necessary  in  either  case.  For  example,  we  might  create  for  column  E  t he  list 

4 
a ny 

8 
1 

• 

This  space  savings  in  these  small  examples  may  be  misleading,  because  the 
total  number  of entries  in  the  lists  created  in  this  example  and  the  previous  one 
together  with  the  pointers  from  states  to  action  lists  and  from  nonterminals 
to  next-state  lists,  result  in  unimpressive  space  savings  over  the  m a t r ix  imple 
mentation  of  Fig.  4.37.  For  practical  grammars,  the  space  needed  for  the  list 
representation  is  typically  less  t h an  ten  percent  of  t h at  needed  for  t he  matrix 
representation.  The  table-compression  methods  for  finite  a u t o m a ta  t h at  were 
discussed  in  Section  3.9.8  can  also  be  used  to  represent  LR  parsing  tables. 

4.7.7  Exercises  for  Section  4.7 

E x e r c i se  4 . 7 . 1:  Construct  the 

a)  canonical  LR,  and 

b)  LALR 

278 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

sets  of  items 

for 

t he  grammar  S-+SS 

+ 

\SS*\aof  Exercise  4.2.1. 

E x e r c i se  4 . 7 . 2:  Repeat  Exercise  4.7.1  for  each  of  the  (augmented)  g r a m m a rs 
of  Exercise  4.2.2(a)-(g). 

!  E x e r c i se  4 . 7 . 3:  For  the  grammar  of  Exercise  4.7.1,  use  Algorithm  4.63  to 
compute  the  collection  of LALR  sets  of items  from  t he  kernels  of the  LR(0)  sets 
of  items. 

!  E x e r c i se  4 . 7 . 4:  Show  t h at  t he  following  g r a m m ar 

5  -> 
A 

d 

A  a\b  A  c  |  d  c\b  d  a 

is  L A L R ( l)  but  not  S L R ( l ). 

!  E x e r c i se  4 . 7 . 5:  Show  t h at  the  following  g r a m m ar 

S 
A 
B 

-> 

Aa\b  Ac  \  B  c\b  B  a 

-+ 

d 
d 

is  LR(1)  but  not  L A L R ( l ). 

4.8  Using  Ambiguous  Grammars 

It  is  a  fact  t h at  every  ambiguous  grammar  fails  to  be  LR  and  thus  is  not  in 
any  of  the  classes  of  grammars  discussed  in  t he  previous  two  sections.  How 
ever,  certain  types  of  ambiguous  grammars  are  quite  useful  in  t he  specification 
and  implementation  of  languages.  For  language  constructs  like  expressions,  an 
ambiguous  grammar  provides  a  shorter,  more  natural  specification  t h an  any 
equivalent  unambiguous  grammar.  Another  use  of  ambiguous  grammars  is  in 
isolating  commonly  occurring  syntactic  constructs  for  special-case  optimiza 
tion.  W i th  an  ambiguous  grammar,  we  can  specify  the  special-case  constructs 
by  carefully  adding  new  productions  to  the  grammar. 

Although  the  grammars  we  use  are  ambiguous,  in  all  cases  we  specify  dis 
ambiguating  rules  t h at  allow  only  one  parse  tree  for  each  sentence.  In  this  way, 
the  overall  language  specification  becomes  unambiguous,  and  sometimes  it  be 
comes  possible  to  design  an  LR  parser  t h at  follows  the  same  ambiguity-resolving 
choices.  We  stress  t h at  ambiguous  constructs  should  be  used  sparingly  and  in 
a  strictly  controlled  fashion;  otherwise,  there  can  be  no  guarantee  as  to  what 
language  is  recognized  by  a  parser. 

4.8. 

USING  AMBIGUOUS  GRAMMARS 

2 79 

4.8.1  Precedence  and  Associativity  to  Resolve  Conflicts 

Consider  t he  ambiguous  grammar  ( 4 . 3)  for  expressions  with  operators  +  and 
*,  repeated  here  for  convenience: 

E^E  +  E\  E*E 

\ 

(E)  I 

id 

This  g r a m m ar  is  ambiguous  because  it  does  not  specify  t he  associativity  or 
precedence  of  the  operators  +  and  *.  The  unambiguous  grammar  ( 4 . 1 ),  which 
includes  productions  E 
E  +  T  and  T  -+T*F,  generates  the  same  language, 
but  gives  +  lower  precedence  t h an  *,  and  makes  b o th  operators  left  associative. 
There  are  two  reasons  why  we  might  prefer  to  use  t he  ambiguous  grammar. 
First,  as  we  shall  see,  we  can  easily  change  the  associativity  and  precedence 
of  the  operators  +  and  *  without  disturbing  t he  productions  of  ( 4 . 3)  or  the 
number  of  states  in  t he  resulting  parser.  Second,  the  parser  for  t he  unam 
biguous  grammar  will  spend  a  substantial  fraction  of  its  time  reducing  by  the 
productions  E  -+  T  and  T  -+  F,  whose  sole  function  is  to  enforce  associativity 
and  precedence.  T he  parser  for  the  ambiguous  grammar  ( 4 . 3)  will  not  waste 
time  reducing  by  these  single  productions  (productions  whose  body  consists  of 
a  single  nonterminal). 

T he  sets  of  L R ( 0)  items  for  the  ambiguous  expression  grammar  ( 4 . 3)  aug 
mented  by  E'  ->  E  are  shown  in  Fig.  4 . 4 8.  Since  grammar  ( 4 . 3)  is  ambiguous, 
there  will  be  parsing-action  conflicts  when  we  try  to  produce  an  LR  parsing 
table  from  the  sets  of  items.  The  states  corresponding  to  sets  of  items  Ij  and 
Is  generate  these  conflicts.  Suppose  we  use  t he  SLR  approach  to  constructing 
t he  parsing  action  table.  T he  conflict  generated  by  I7  between  reduction  by 
E  -+  E  +  E  and  shift  on  +  or  *  cannot  be  resolved,  because  +  and  *  are  each 
in  F O L L O W ( £ ' ).  Thus  both  actions  would  be  called  for  on  inputs  +  and  *.  A 
similar  conflict  is  generated  by  Is,  between  reduction  by  E  -+  E  *  E  and  shift 
on  inputs  +  and  *.  In  fact,  each  of  our  LR  parsing  table-construction  methods 
will  generate  these  conflicts. 

However,  these  problems  can  be  resolved  using  t he  precedence  and  associa 
tivity  information  for  +  and  *.  Consider  the  input  id  +  id  *  id,  which  causes  a 
parser  based  on  Fig.  4 . 48  to  enter  state  7  after  processing  id + id;  in  particular 
t he  parser  reaches  a  configuration 

PR E F IX 
E  +  E 

ST A CK 

0  14  7 

IN P UT 
* i d$ 

For  convenience,  the  symbols  corresponding  to  the  states  1,  4,  and  7  are  also 
shown  under  P R E F I X. 

If  *  takes  precedence  over  +,  we  know  the  parser  should  shift  *  onto  the 
stack,  preparing to  reduce t he  *  and its  surrounding  id  symbols to  an expression. 
This  choice  was  made  by  the  SLR  parser  of Fig.  4 . 3 7,  based  on  an  unambiguous 
g r a m m ar  for  the  same  language.  On  t he  other  hand,  if  +  takes  precedence  over 
*,  we  know  the  parser  should  reduce  E  +  E  to  E.  Thus  the  relative  precedence 

280 

io: 

£7 

-E  +  E 

E' 
E-> 
E^-E*E 
E 
E -4 

-(E) 
id 

h: 

£ 7'  ->•  £ 7-

£7 
E-> 

£ 7-  +  E 
E-*E 

h: 

h: 

h: 

( - £ 7) 

E 
E  ^  -E  +  E 
E  -» 
E-+iE) 
E 

-£7  *  £7 

id 

£7  ->•  id-

£7 

£7 

E+  -£7 

-£7  +  £7 

-£7  *  £7 

£7  -» 
E -4  -(E) 
£7  ->•  id 

CHAPTER  4. 

SYNTAX  ANALYSIS 

£7  -->•  £7  *  - £7 

£7 
E 
E 
E 

-£7  +  £7 
-E*E 

- ( £ 7) 
id 

h: 

£7 

( £ 7 -) 

£7 -4  £ 7-  +  £7 

£7  ->•  £ 7-  * £7 

Ir. 

£7  —>•  £7  +  £ 7-

£7  ->  £ 7-  +  £7 

£7  ->•  £ 7-  *  £7 

E-+E*E-
E  -4  £ 7-  +  £7 

£7  ->  £ 7-  *  £7 

£7 

( £ 7 )-

Figure  4.48:  Sets  of  LR(0)  items  for  an  augmented  expression  grammar 

of  +  followed  by  *  uniquely  determines  how  the  parsing  action  conflict  between 
reducing  £7  ->  £7 + £7  and  shifting  on  *  in  state  7  should  be  resolved. 

If  the  input  had  been  id  +  id  +  id  instead,  the  parser  would  still  reach  a 
configuration  in  which  it  had  stack  0  14  7  after  processing  input  id  +  id.  On 
input  +  there  is  again  a  shift/reduce  conflict  in  state  7.  Now,  however,  t he 
associativity  of  the  +  operator  determines  how  this  conflict  should  be  resolved. 
If  +  is  left  associative,  t he  correct  action  is  to  reduce  by  £7  —y  E +  E.  T h at  is, 
t he  id  symbols  surrounding  t he  first  +  must  be  grouped  first.  Again  this  choice 
coincides  with  what  the  SLR  parser  for  t he  unambiguous  g r a m m ar  would  do. 

In  summary,  assuming  +  is  left  associative,  the  action  of  state  7  on  input 
+  should  be  to  reduce  by  £7  —y  E +  £ 7,  and  assuming  t h at  *  takes  precedence 
over  +,  t he  action  of  state  7  on  input  *  should  be  to  shift.  Similarly,  assuming 
t h at  *  is  left  associative  and  takes  precedence  over  +,  we  can  argue  t h at  state 
8,  which  can  appear  on  top  of  t he  stack  only  when  E  *  E  are  the  top  three 
g r a m m ar  symbols,  should  have  the  action  reduce  £7  -y  E  *  E  on  both  +  and  * 
inputs.  In  the  case  of  input  +,  t he  reason  is  t h at  *  takes  precedence  over  +, 
while  in  t he  case  of  input  *,  the  rationale  is  t h at  *  is  left  associative. 

4.8. 

USING  AMBIGUOUS  GRAMMARS 

281 

Proceeding  in  this  way,  we  obtain  the  LR  parsing  table  shown  in  Fig.  4.49. 

Productions  1  through  4  are  E  -t  E  +  E,  E  ->•  E  *  E,  ->•  (E),  and  E  -» 
id,  respectively.  It  is  interesting  t h at  a  similar  parsing  action  table  would  be 
produced  by  eliminating  the  reductions  by  the  single  productions  E  -»  T  and 
T  —»•  F  from  t he  SLR  table  for  t he  unambiguous  expression  g r a m m ar  (4.1) 
shown  in  Fig.  4.37.  Ambiguous  grammars  like  t he  one  for  expressions  can  be 
handled  in  a  similar  way  in  the  context  of  LALR  and  canonical  LR  parsing. 

ST A TE 
ST A TE 
ST A TE 

A C T I ON 

G O TO 

E 

1 

6 

7 
8 

id  + 
s3 

* 

s4 

s5 

s3 

s3 
s3 

r4 

r4 

s4 
rl 
r2 
r3 

s5 
s5 
r2 
r3 

( 
s2 

s2 

s2 
s2 

) 

$ 

acc 

r4 

r4 

s9 
rl 
r2 
r3 

rl 
r2 
r3 

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 

Figure  4.49:  Parsing  table  for  grammar  (4.3) 

4.8.2  The  "Dangling-Else"  Ambiguity 

Consider  again  the  following  grammar  for  conditional  statements: 

stmt  —> 

| 
| 

if  expr  t h en  stmt  e l se  stmt 
if  expr  t h en  stmt 
o t h er 

As  we  noted  in  Section  4.3.2,  this  grammar  is  ambiguous  because  it  does  not 
resolve  the  dangling-else  ambiguity.  To  simplify  the  discussion,  let  us  consider 
an  abstraction  of  this  grammar,  where  i  stands  for  if  expr  t h e n,  e  stands  for 
else,  and  a  stands  for  "all  other  productions."  We  can  then  write  the  grammar, 
with  augmenting  production  S' 

S,  as 

S 

-» 

iSeS 

| 

iS 

|  a 

(4-67) 

The  sets  of  LR(0)  items  for  grammar  (4.67)  are  shown  in  Fig.  4.50.  T he  ambi 
guity  in  (4.67)  gives  rise  to  a  shift/reduce  conflict  in  I4.  There,  S  ->•  iS-eS  calls 
for  a  shift  of e  and,  since  F O L L O W( 5)  =  {e, $},  item  S  ->•  iS-  calls  for  reduction 
by  5  ->  iS  on  input  e. 

Translating  back  to  the  if-then-else  terminology,  given 

282 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

S' 
-+-S 
S  ->  -iSeS 
S-y-iS 

S  ->  -a 

h: 

S' 

-+S-

S  -+  i-SeS 
-I  i-S 
S 
S  -» 
S^-iS 
S^-a 

-iSeS 

h: 

h: 

h: 

S 

->a-

S  ->  iS-eS 

S  ->  iSe-S 
S  -+  -iSeS 
S^-iS 
S  -»•  -a 

S 

-t 

iSeS-

Figure  4.50:  LR(0)  states  for  augmented  g r a m m ar  (4.67) 

if  expr  t h en  stmt 

on  the  stack  and  e l se  as  the  first  input  symbol,  should  we  shift  e l se  onto  t he 
stack  (i.e.,  shift  e)  or  reduce  if  expr  t h en  stmt  (i.e,  reduce  by  S  —>  iS)?  T he 
answer  is  t h at  we  should  shift  else,  because  it  is  "associated"  with  the  previous 
t h e n.  In  the  terminology  of  grammar  (4.67),  the  e  on  t he  input,  standing  for 
else,  can  only  form  part  of  the  body  beginning  with  the  iS  now  on  t he  top  of 
the  stack.  If  what  follows  e  on  the  input  cannot  be  parsed  as  an  5,  completing 
body  iSeS,  then  it  can  be  shown  t h at  there  is  no  other  parse  possible. 

We  conclude  t h at  the  shift/reduce  conflict  in J4  should  be  resolved  in  favor 
of  shift  on  input  e.  T he  SLR  parsing  table  constructed  from  t he  sets  of  items 
of  Fig.  4.48,  using  this  resolution  of  t he  parsing-action  conflict  in  I4  on  input 
e,  is  shown  in  Fig.  4.51.  Productions  1  through  3  are  S  ->  iSeS,  S  ->•  iS,  and 
S  -)•  a,  respectively. 

ST A TE 
ST A TE 

A C T I ON 

G O TO 

i 

s2 

s2 

s2 

e 

r3 
s5 

rl 

a 

s3 

s3 

s3 

$ 

acc 

r3 
r2 

rl 

S 

1 

4 

6 

0 
1 
2 
3 
4 
5 
6 

Figure  4.51:  LR  parsing  table  for  t he  "dangling-else"  grammar 

4.8. 

USING  AMBIGUOUS  GRAMMARS 

2 83 

For  example,  on  input  iiaea,  the  parser  makes  the  moves  shown  in  Fig.  4 . 5 2, 
corresponding to  the  correct  resolution  of the  "dangling-else."  At  line  ( 5 ),  state 
4 selects  the  shift  action on input  e,  whereas at  line  ( 9 ),  state 4 calls for reduction 
by  S  ->•  iS  on  input  $. 

ST A CK 

SY M B O LS 

IN P UT 

AC T I ON 

( 1) 

( 2) 

( 3) 

( 4) 

( 5) 

( 6) 

( 7) 

( 8) 

( 9) 
( 1 0) 

0 

0  2 

0  2  2 

0  2  2  4 

0  2  2  3 

i 
i  i 
ii  a 
as 
USe 
iiSea 
0  2  2  4  5  3 
0  2  2  4  5  6  USeS 
0  2  4 

0  2  2  4  5 

iS 
S 

0  1 

iiaea$ 
iaea$ 

aea% 
ea% 
ea% 
a% 
$ 
$ 
$ 
$ 

shift 
shift 
shift 
shift 
reduce by S —>• a 
shift 
reduce  by  S —>  a 
reduce  by  S  —>•  iSeS 
reduce  by  S  ->  iS 
accept 

Figure  4 . 5 2:  Parsing  actions  on  input  iiaea 

By  way  of  comparison,  if  we  are  unable  to  use  an  ambiguous  grammar  to 
specify  conditional  statements,  then  we  would  have  to  use  a  bulkier  grammar 
along  the  lines  of  Example  4.16. 

4.8.3  Error  Recovery  in  LR  Parsing 

An  LR  parser  will  detect  an  error  when  it  consults  t he  parsing  action  table  and 
finds  an  error  entry.  Errors  are  never  detected  by  consulting  the  goto  table.  An 
LR  parser  will  announce  an  error  as  soon  as  there  is  no  valid  continuation  for 
t he  portion  of the  input  thus  far  scanned.  A  canonical  LR  parser  will  not  make 
even  a  single  reduction  before  announcing  an  error.  SLR  and  LALR  parsers 
may  make  several  reductions  before  announcing  an  error,  but  they  will  never 
shift  an  erroneous  input  symbol  onto  the  stack. 

In  LR  parsing,  we  can  implement  panic-mode  error  recovery  as  follows.  We 
scan  down  t he  stack  until  a  state  s  with  a  goto  on  a  particular  nonterminal 
A  is  found.  Zero  or  more  input  symbols  are  then  discarded  until  a  symbol 
a  is  found  t h at  can  legitimately  follow  A.  T he  parser  then  stacks  the  state 
G O T O ( s, A)  and  resumes  normal  parsing.  There  might  be  more  t h an  one  choice 
for  the  nonterminal  A.  Normally  these  would  be  nonterminals  representing 
major  program  pieces,  such  as  an  expression,  statement,  or  block.  For  example, 
if  A  is  t he  nonterminal  stmt,  a  might  be  semicolon  or  },  which  marks  t he  end 
of  a  statement  sequence. 

This  m e t h od  of  recovery  a t t e m p ts  to  eliminate  the  phrase  containing  t he 
syntactic  error.  T he  parser  determines  t h at  a  string  derivable  from  A  contains 
an  error.  P a rt  of  t h at  string  has  already  been  processed,  and  the  result  of  this 

284 

CHAPTER  4. 

SYNTAX  ANALYSIS 

processing  is  a  sequence  of  states  on  top  of  the  stack.  T he  remainder  of  the 
string  is  still  in  the  input,  and  t he  parser  a t t e m p ts  to  skip  over  t he  remainder 
of  this  string  by  looking  for  a  symbol  on  the  input  t h at  can  legitimately  follow 
A.  By  removing  states  from  the  stack,  skipping  over  the  input,  and  pushing 
G O T O ( s, A)  on  the  stack,  the  parser  pretends  t h at  it  has  found  an  instance  of 
A  and  resumes  normal  parsing. 

Phrase-level  recovery  is  implemented  by  examining  each  error  entry  in  t he 
LR  parsing  table  and  deciding  on  the  basis  of  language  usage  the  most  likely 
programmer  error  t h at  would  give  rise  to  t h at  error.  An  appropriate  recovery 
procedure  can  then  be  constructed;  presumably  the  top  of t he  stack  a n d / or  first 
input  symbols  would  be  modified  in  a  way  deemed  appropriate  for  each  error 
entry. 

In  designing  specific  error-handling  routines  for  an  LR  parser,  we  can  fill  in 
each  blank  entry  in  the  action  field  with  a  pointer  to  an  error  routine  t h at  will 
take  the  appropriate  action  selected  by  the  compiler  designer.  T he  actions  may 
include  insertion  or  deletion  of  symbols  from  t he  stack  or  the  input  or  both, 
or  alteration  and  transposition  of  input  symbols.  We  must  make  our  choices 
so  t h at  the  LR  parser  will  not  get  into  an  infinite  loop.  A  safe  strategy  will 
assure  t h at  at  least  one  input  symbol  will  be  removed  or  shifted  eventually,  or 
t h at  the  stack  will  eventually  shrink  if  the  end  of  t he  input  has  been  reached. 
Popping  a  stack  state  t h at  covers  a  nonterminal  should  be  avoided,  because 
this  modification  eliminates  from  the  stack  a  construct  t h at  has  already  been 
successfully  parsed. 

E x a m p le  4 . 6 8:  Consider  again  the  expression  g r a m m ar 

E  -4  E  +  E  |  E  *  E  |  (E)  |  id 

Figure  4.53  shows  t he  LR  parsing  table  from  Fig.  4.49  for  this  grammar, 
modified  for  error  detection  and  recovery.  We  have  changed  each  state  t h at 
calls  for  a  particular  reduction  on  some  input  symbols  by  replacing  error  entries 
in  t h at  state  by  the  reduction.  This  change  has  the  effect  of  postponing  t he 
error  detection  until  one  or  more  reductions  are  made,  but  t he  error  will  still 
be  caught  before  any  shift  move  takes  place.  T he  remaining  blank  entries  from 
Fig.  4.49  have  been  replaced  by  calls  to  error  routines. 

The  error  routines  are  as  follows. 

e l:  This  routine  is  called  from  states  0,  2,  4  and  5,  all  of  which  expect  the 
beginning  of an  operand,  either  an  id  or  a  left  parenthesis.  Instead,  +,  *, 
or  t he  end  of  the  input  was  found. 

push  state  3  (the  goto  of  states  0,  2,  4  and  5  on  i d ); 
issue  diagnostic  "missing  operand." 

e 2:  Called  from  states  0,  1,  2,  4  and  5  on  finding  a  right  parenthesis. 

remove  the  right  parenthesis  from  the  input; 
issue  diagnostic  "unbalanced  right  parenthesis." 

4.8. 

USING  AMBIGUOUS  GRAMMARS 

285 

ST A TE 
ST A TE 

A C T I ON 

G O TO 

E 

1 

6 

7 
8 

id 

s3 
e3 
s3 
r4 
s3 
s3 
e3 
rl 
r2 
r3 

+ 
el 
s4 
el 
r4 
el 
el 
s4 
rl 
r2 
r3 

* 

el 

s5 
el 
r4 
el 
el 
s5 
s5 
r2 
r3 

( 
s2 

e3 
s2 
r4 
s2 
s2 
e3 
rl 
r2 
r3 

) 
e2 

e2 
e2 
r4 
e2 
e2 
s9 
rl 
r2 
r3 

$ 

el 

acc 
el 
r4 
el 
el 
e4 
rl 
r2 
r3 

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 

Figure  4.53:  LR  parsing  table  with  error  routines 

e 3:  Called  from  states  1  or  6  when  expecting  an  operator,  and  an  id  or  right 

parenthesis  is  found. 

push  state  4  (corresponding  to  symbol  +)  onto  t he  stack; 
issue  diagnostic  "missing  operator." 

e 4:  Called  from  state  6  when  t he  end  of  the  input  is  found. 

push  state  9  (for  a  right  parenthesis)  onto  the  stack; 
issue  diagnostic  "missing  right  parenthesis." 

On  the  erroneous  input  id  + ),  the  sequence  of  configurations  entered  by  the 

parser  is  shown  in  Fig.  4.54. 

• 

4.8.4  Exercises  for  Section  4.8 

!  E x e r c i se  4 . 8 . 1:  T he  following  is  an  ambiguous  grammar  for  expressions  with 

n  binary,  infix  operators,  at  n  different  levels  of  precedence: 

E  -»  E  0!  E  |  E  02  E  |  •  •  •  E  6n  E  |  (  E  )  |  id 

a)  As  a  function  of  n,  what  are  the  SLR  sets  of  items? 

b)  How  would  you  resolve  the  conflicts  in  the  SLR  items  so  t h at  all  oper 
ators  are  left  associative,  and  6\  takes  precedence  over  02,  which  takes 
precedence  over  #3,  and  so  on? 

c)  Show  the  SLR  parsing  table  t h at  results  from  your  decisions  in  part  (b). 

286 

CHAPTER  4. 

SYNTAX  ANALYSIS 

ST A CK 

SY M B O LS 

IN P UT 

AC T I ON 

0 
0  3 
0  1 
0  1  4 

id 
E 
E  + 

0  1  4 

E  + 

0  14  3 
0  14  7 
0  1 

E  +  id 
E  + 
E  + 

id  +  )$ 
+  )$ 
+  )$ 

)$ 

$ 

$ 
$ 
$ 

"unbalanced  right  parenthesis" 
e2  removes  right  parenthesis 
"missing  operand" 
el  pushes  state  3  onto  stack 

Figure  4.54:  Parsing  and  error  recovery  moves  made  by  an  LR  parser 

d)  Repeat  parts  (a)  and  (c)  for  t he  unambiguous  grammar,  which  defines 

t he  same  set  of  expressions,  shown  in  Fig.  4.55. 

e)  How  do  the  counts  of the  number  of sets  of items  and  t he  sizes  of the  tables 
for  t he  two  (ambiguous  and  unambiguous)  grammars  compare?  W h at 
does  t h at  comparison  tell  you  about  t he  use  of  ambiguous  expression 
grammars? 

Ex 
E2 

En 
En+i 

-+ 

-> 
-> 

Ei  9  E2 
|  E2 
E2  9  E3  I  E3 

En  9  En+i 
{El)\id 

I  En+i 

Figure  4.55:  Unambiguous  grammar  for  n  operators 

!  E x e r c i se  4 . 8 . 2:  In  Fig.  4.56  is  a  g r a m m ar  for  certain  statements,  similar  to 
t h at  discussed  in  Exercise  4.4.12.  Again,  e  and  s  are  terminals  standing  for 
conditional  expressions  and  "other  statements,"  respectively. 

a)  Build  an  LR  parsing  table  for  this  grammar,  resolving  conflicts  in  t he 

usual  way  for  the  dangling-else  problem. 

b)  Implement  error  correction  by  filling  in  t he  blank  entries  in  t he  parsing 

table  with  extra  reduce-actions  or  suitable  error-recovery  routines. 

c)  Show  t he  behavior  of  your  parser  on  the  following  inputs: 

if  e  t h en  s  ;  if  e  t h en  s  e nd 

(i) 
(ii)  w h i le  e  do  b e g in  s  ;  if  e  t h en  s  ;  e nd 

4.9. 

PARSER  GENERATORS 

287 

stmt 

-» 
j 
| 
| 
I 
list  —>• 

| 

if  e  t h en  stmt 
if  e  t h en  stmt  e l se  stmt 
w h i le  e  do  stmt 
b e g in  list  e nd 
s 

;  stmt 

fet 
stmt 

Figure  4.56:  A  grammar  for  certain  kinds  of  statements 

4.9  Parser  Generators 

This  section  shows  how  a  parser  generator  can  be  used  to  facilitate  t he  construc 
tion  of  t he  front  end  of  a  compiler.  We  shall  use  the  LALR  parser  generator 
Yacc  as  the  basis  of  our  discussion,  since  it  implements  many  of  the  concepts 
discussed  in  the  previous  two  sections  and  it  is  widely  available. Yacc  stands  for 
"yet  another  compiler-compiler,"  reflecting  the  popularity  of  parser  generators 
in  t he  early  1970s  when  the  first  version  of Yacc  was  created  by  S.  C.  Johnson. 
Yacc  is  available  as  a  command  on  t he  UNIX  system,  and  has  been  used  to  help 
implement  many  production  compilers. 

4.9.1  The  Parser  Generator  Yacc 

A  translator  can  be  constructed  using Yacc  in  the  manner  illustrated  in  Fig. 
4.57.  First,  a  file,  say translate.y,  containing  a Yacc  specification  of  the 
translator  is  prepared.  The  UNIX  system  command 

yacc  translate.y 

transforms  t he  file translate.y  into  a  C  program  called y.tab.c  using  t he 
LALR  method  outlined  in  Algorithm  4.63.  T he  program y.tab.c  is  a  repre 
sentation  of  an  LALR  parser  written  in  C,  along  with  other  C  routines  t h at  t he 
user  may  have  prepared.  The  LALR  parsing  table  is  compacted  as  described 
in  Section  4.7.  By  compiling y.tab.c  along  with  the ly  library  t h at  contains 
the  LR  parsing  program  using  the  command 

cc  y.tab.c  -ly 

we  obtain  t he  desired  object  program a.  o ut  t h at  performs  t he  translation  spec 
ified  by  the  original Yacc  p r o g r a m .7  If  other  procedures  are  needed,  they  can 
be  compiled  or  loaded  with y.tab.c,  just  as  with  any  C  program. 

A Yacc  source  program  has  three  parts: 

7T he  name ly  is  system  dependent. 

288 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

Yacc 
specification-
t r a ns l a t e,  y 

y . t a b .c 

Yacc 
compiler 

c 
compiler 

y . t a b .c 

a.  out 

input 

a.  out 
a.  out 

— 

1* 

output 

Figure  4.57:  Creating  an  i n p u t / o u t p ut  translator  with  Yacc 

declarations 
n 
translation  rules 
n 
supporting  C  routines 
E x a m p le  4 . 6 9:  Tti  illustrate  how  to  prepare  a  Yacc  source  program,  let  us 
construct  a  simple  desk  calculator  t h at  reads  an  arithmetic  expression,  evaluates 
it,  and  then  prints  its  numeric  value.  We  shall  build  t he  desk  calculator  starting 
with  the  with  the  following  grammar  for  arithmetic  expressions: 

E 
T 
F 

-> 

-»• 

E  +  T 
|  T 
|  F 
T  *  F 
( £ 7 )|  d i g it 

T he  token  digit  is  a  single  digit  between  0  and  9.  A  Yacc  desk  calculator 
program  derived  from  this  grammar  is  shown  in  Fig.  4.58. 

• 

T he  D e c l a r a t i o ns  P a rt 

There  are  two  sections  in  t he  declarations  part  of  a  Yacc  program;  b o th  are 
optional.  In  the  first  section,  we  put  ordinary  C  declarations,  delimited  by .'/.{ 
and  '/,}.  Here  we  place  declarations  of  any  temporaries  used  by  t he  translation 
rules  or  procedures  of  t he  second  and  third  sections.  In  Fig.  4.58,  this  section 
contains  only  the  include-statement 

# i n c l u de  < c t y p e. h> 

t h at  causes  the  C  preprocessor  to  include  t he  standard  header  file  < c t y p e. h> 
t h at  contains  the  predicate  i s d i g i t. 

Also  in  the  declarations  part  are  declarations  of  g r a m m ar  tokens. 

In  Fig. 

4.58,  the  statement 

%token  DIGIT 

4.9. 

PARSER  GENERATORS 

289 

#include  <ctype.h> 

'/.token  DIGIT 

U 
line 

:  expr  '\n' 

{ printf ("°/.d\n", $ 1 ); } 

expr 

:  expr  »+'  term 

{  $$ = $1  + $3;  } 

I term 

> 

term 

:  term  '*>  factor  {  $$ = $1  *  $3;  > 

{ $$ = $2;  } 

I  factor 

> 

factor  :  '('  expr  » )' 
I  DIGIT 
> 

11 
y y l e xQ  { 

int  c; 
c = getchar () ; 
if  (isdigit(c))  { 

yylval  =  c-'O'; 
return  DIGIT; 

} 
return  c; 

} 

Figure  4.58: Yacc  specification  of  a  simple  desk  calculator 

declares  DIGIT  to  be  a  token.  Tokens  declared  in  this  section  can  then  be 
used  in  the  second  and  third  p a r ts  of  the Yacc  specification. 
If Lex  is  used 
to  create  t he  lexical  analyzer  t h at  passes  token  to  the Yacc  parser,  then  these 
token  declarations  are  also  made  available  to  the  analyzer  generated  by Lex,  as 
discussed  in  Section  3.5.2. 

T he  T r a n s l a t i on  R u l es  P a rt 

In t he  part  of the Yacc  specification  after the  first  %% pair,  we put  t he translation 
rules.  Each  rule  consists  of  a  g r a m m ar  production  and  the  associated  semantic 
action.  A  set  of  productions  t h at  we  have  been  writing: 

(head) 

-> 

( b o d y )! 

|  <body)2 

|  •••  | 

( b o d y )n 

would  be  written  in Yacc  as 

2 90 

CHAPTER  4. 

SYNTAX  ANALYSIS 

(head) 

(body)i 

: 
{  (semantic  action) i  } 
I  (body)  2  {  (semantic  action)  2  } 

I 

( b o d y )n 

{  (semantic  a c t i o n )n  } 

In  a  Yacc  production,  unquoted  strings  of letters  and  digits  not  declared  to 
' c ', 
be  tokens  are  taken  to  be  nonterminals.  A  quoted  single  character,  e.g. 
is  taken  to  be  the  terminal  symbol  c,  as  well  as  the  integer  code  for  the  token 
represented  by  t h at  character  (i.e.,  Lex  would  return  t he  character  code  for  ' c' 
to  t he  parser,  as  an  integer).  Alternative  bodies  can  be  separated  by  a  vertical 
bar,  and  a  semicolon  follows  each  head  with  its  alternatives  and  their  semantic 
actions.  T he  first  head  is  taken  to  be  t he  start  symbol. 

A  Yacc  semantic  action  is  a  sequence  of  C  statements.  In  a  semantic  action, 
t he  symbol  $$  refers  to  t he  a t t r i b u te  value  associated  with  t he  nonterminal  of 
the  head,  while  $i  refers  to  t he  value  associated  with  t he  ith  g r a m m ar  symbol 
(terminal  or  nonterminal)  of the  body.  T he  semantic  action  is  performed  when 
ever  we  reduce  by  t he  associated  production,  so  normally  the  semantic  action 
computes  a  value  for  $$  in  terms  of the  $i's.  In  the  Yacc  specification,  we  have 
written 

two  E-productions 

t he 

E-+E  +  T  I  T 

and  their  associated  semantic  actions  as: 

expr  :  expr  >+>  term 

{  $$  =  $1  +  $ 3;  } 

I  term 

Note  t h at  the  nonterminal  term  in  t he  first  production  is  t he  third  g r a m m ar 
symbol  of the  body,  while  +  is  the  second.  T he  semantic  action  associated  with 
the  first  production  adds  the  value  of  t he  expr  and  t he  term  of  t he  body  and 
assigns  the  result  as  t he  value  for  the  nonterminal  expr  of  t he  head.  We  have 
omitted  the  semantic  action  for  t he  second  production  altogether,  since  copying 
the  value  is  the  default  action  for  productions  with  a  single  g r a m m ar  symbol 
in  t he  body.  In  general,  {  $$  =  $ 1;  }  is  the  default  semantic  action. 

Notice  t h at  we  have  added  a  new  starting  production 

l i ne 

:  e x pr  > \ n' 

{  p r i n tf 0 7 . d \ n ",  $ 1 );  } 

to  t he  Yacc  specification.  This  production  says  t h at  an  input  to  the  desk 
calculator  is  to  be  an  expression  followed  by  a  newline  character.  T he  semantic 
action  associated  with  this  production  prints  the  decimal  value  of the  expression 
followed  by  a  newline  character. 

4.9. 

PARSER  GENERATORS 

291 

T he  S u p p o r t i ng  C - R o u t i n es  P a rt 

T he  third  p a rt  of  a Yacc  specification  consists  of  supporting  C-routines.  A 
lexical  analyzer  by  t he  n a me  y y l e xO  must  be  provided.  Using  Lex  to  produce 
y y l e xO  is  a  common  choice;  see  Section  4.9.3.  Other  procedures  such  as  error 
recovery  routines  may  be  added  as  necessary. 

The  lexical  analyzer  y y l e xO  produces  tokens  consisting  of  a  token  name 
and  its  associated  a t t r i b u te  value.  If  a  token  name  such  as DIGIT  is  returned, 
t he  token  name  must  be  declared  in  the  first  section  of  the Yacc  specification. 
T he  a t t r i b u te  value  associated  with  a  token  is  communicated  to  the  parser 
through  a Yacc-defined  variable  y y l v a l. 

T he  lexical  analyzer  in  Fig.  4.58  is  very  crude. 

It  reads  input  characters 
one  at  a  time  using  the  C-function  g et c h ar ( ).  If  t he  character  is  a  digit,  t he 
value  of  the  digit  is  stored  in  the  variable  y y l v a l,  and  t he  token  n a me DIGIT 
is  returned.  Otherwise,  the  character  itself  is  returned  as  t he  token  name. 

4.9.2  Using  Yacc  with  Ambiguous  Grammars 

Let  us  now  modify  t he Yacc  specification  so  t h at  t he  resulting  desk  calculator 
becomes  more  useful.  First,  we  shall  allow  t he  desk  calculator  to  evaluate  a 
sequence  of  expressions,  one  to  a  line.  We  shall  also  allow  blank  lines  between 
expressions.  We  do  so  by  changing  the  first  rule  to 

l i n es 

: 
I 
I 

' \ n' 

l i n es  e x pr 
l i n es 
' \ n' 
/*  empty  */ 

{  p r i n tf ("°/,g\n",  $ 2 );  } 

In Yacc,  an  empty  alternative,  as  t he  third  line  is,  denotes  e. 

Second,  we  shall  enlarge  the  class  of  expressions  to  include  numbers  instead 
of  single  digits  and  to  include  t he  arithmetic  operators  +,  —,  (both  binary  and 
unary),  *,  and  /.  T he  easiest  way  to  specify  this  class  of  expressions  is  to  use 
t he  ambiguous  g r a m m ar 

E ^E  +  E\  E-  E\  E * E \ E /E 

\ 

-  E 

\ 

n u m b er 

T he  resulting Yacc  specification  is  shown  in  Fig.  4.59. 

Since  t he  grammar  in  t he Yacc  specification  in  Fig.  4.59  is  ambiguous,  the 
LALR  algorithm  will  generate  parsing-action  conflicts.  Yacc  reports  t he  num 
ber  of  parsing-action  conflicts  t h at  are  generated.  A  description  of  the  sets  of 
items  and  t he  parsing-action  conflicts  can  be  obtained  by  invoking Yacc  with  a 
-v  option.  This  option  generates  an  additional  file  y . o u t p ut  t h at  contains  the 
kernels  of  t he  sets  of  items  found  for  the  grammar,  a  description  of  the  parsing 
action  conflicts  generated  by  the  LALR  algorithm,  and  a  readable  represen 
tation  of  t he  LR  parsing  table  showing  how  the  parsing  action  conflicts  were 
resolved.  Whenever Yacc  reports  t h at  it  has  found  parsing-action  conflicts,  it 

CHAPTER  4. 

SYNTAX  ANALYSIS 

%i 
#include  <ctype.h> 
#include  <stdio.h> 

#define  YYSTYPE double  /* double type for Yacc stack */ 

%} 
'/.token NUMBER 

•/.left » + » 

'/.left  '*'  '/' 

•/.right  UMINUS 

lines 

lines  expr  '\n' 

{ printf 07,g\n",  $ 2 );  } 

lines  '\n' 

/*  empty  */ 

expr 

expr  '+' 
expr 
i _ > 
expr  '-'  expr 
expr  '*'  expr 
expr  '/'  expr 
' (' expr ' )' 
'-'  expr  V.prec UMINUS  { 

=  $1  +  $ 3; 

=  $1 

-  $ 3; 

=  $1  *  $ 3; 

=  $1 

=  $ 2; 

/  $ 3; 

} 

} 

} 

} 

} 

$ 2; 

} 

NUMBER 

y y l e xO  { 

int c; 

while  (  ( c = g e t c h a rO  )  ==  '  '  ); 

if  (  (c = = ' . ')  II  (isdigit(c))  )  { 

unget c(c, stdin); 
scanf ('"/.If", ftyylval) ; 
return  NUMBER; 

} 
return  c; 

Figure  4.59:  Yacc  specification  for  a  more  advanced  desk  calculator. 

4.9.  PARSER  GENERATORS 

293 

is  wise  to  create  and  consult  t he  file y. o u t p ut  to  see  why  t he  parsing-action 
conflicts  were  generated  and  to  see  whether  they  were  resolved  correctly. 

Unless  otherwise  instructed Yacc  will  resolve  all  parsing  action  conflicts 

using  the  following  two  rules: 

1. A  reduce/reduce  conflict  is  resolved  by  choosing the  conflicting  production 

listed  first  in  the Yacc  specification. 

2. A  shift/reduce  conflict  is  resolved  in  favor  of  shift.  This  rule  resolves  the 
shift  /reduce  conflict  arising  from  the  dangling-else  ambiguity  correctly. 

Since  these  default  rules  may  not  always  be  what  the  compiler  writer  wants, 
Yacc  provides  a  general  mechanism  for  resolving  shift/reduce  conflicts.  In  the 
declarations  portion,  we  can  assign  precedences  and  associativities  to  terminals. 
The  declaration 

'/.left ' + ' 

makes  +  and  -  be  of t he  same  precedence  and  be  left  associative.  We  can  declare 
an  operator  to  be  right  associative  by  writing 

'/.right 

and  we  can  force  an  operator  to  be  a  nonassociative  binary  operator  (i.e.,  two 
occurrences  of  the  operator  cannot  be  combined  at  all)  by  writing 

°/0nonassoc 

' <' 

T he  tokens  are  given  precedences  in  the  order  in  which  they  appear  in  the 
declarations  part,  lowest  first.  Tokens  in  the  same  declaration  have  the  same 
precedence.  Thus,  the  declaration 

'/.right  UMINUS 

in  Fig. 4.59  gives  the  token UMINUS  a  precedence  level  higher  t h an  t h at  of  the 
five  preceding  terminals. 

Yacc  resolves  shift/reduce  conflicts  by  attaching  a  precedence  and  associa 
tivity  to  each  production  involved  in  a  conflict,  as  well  as  to  each  terminal 
involved  in  a  conflict.  If it  must  choose  between  shifting  input  symbol  a  and  re 
ducing  by  production  A  ->•  a, Yacc  reduces  if  the  precedence  of t he  production 
is  greater  t h an  t h at  of a,  or  if the  precedences  are  t he  same  and  t he  associativity 
of the  production  is left.  Otherwise,  shift  is  t he  chosen  action. 

Normally,  t he  precedence  of  a  production  is  taken  to  be  the  same  as  t h at  of 
its  rightmost  terminal.  This  is  t he  sensible  decision  in  most  cases.  For  example, 
given  productions 

E  ->•  E  + E 

|  E+E 

294 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

we  would  prefer  to  reduce  by  E  -^-E+E  with  lookahead  +,  because  the  +  in 
the  body  has  t he  same  precedence  as  the  lookahead,  but  is  left  associative. 
W i th  lookahead  *,  we  would  prefer  to  shift,  because  t he  lookahead  has  higher 
precedence  t h an  t he  +  in  t he  production. 

In  those  situations  where  the  rightmost  terminal  does  not  supply  t he  proper 
precedence  to  a  production,  we  can  force  a  precedence  by  appending  to  a  pro 
duction  the  t ag 

°/.prec  (terminal) 

The  precedence  and  associativity  of t he  production  will  then  be  t he  same  as  t h at 
of  t he  terminal,  which  presumably  is  defined  in  the  declaration  section.  Yacc 
does  not  report  shift/reduce  conflicts  t h at  are  resolved  using  this  precedence 
and  associativity  mechanism. 

This  "terminal"  can  be  a  placeholder,  like  UMINUS  in  Fig.  4.59;  this  termi 
nal  is  not  returned  by  the  lexical  analyzer,  but  is  declared  solely  to  define  a 
precedence  for  a  production.  In  Fig.  4.59,  t he  declaration 

•/.right  UMINUS 

assigns  to  t he  token  UMINUS  a  precedence  t h at  is  higher  t h an  t h at  of  *  and  /. 
In  t he  translation  rules  part,  the  tag: 

at  the  end  of  t he  production 

0/,prec  UMINUS 

e x pr 

: 

' -'  e x pr 

makes  the  unary-minus  operator  in  this  production  have  a  higher  precedence 
t h an  any  other  operator. 

4.9.3  Creating  Yacc  Lexical  Analyzers  with  Lex 

Lex was  designed to  produce lexical  analyzers t h at  could  be  used  with Yacc.  T he 
Lex  library  11  will  provide  a  driver  program  named  y y l e x O,  the  n a me  required 
by Yacc  for  its  lexical  analyzer.  If  Lex  is  used  to  produce  the  lexical  analyzer, 
we  replace  t he  routine  y y l e xO  in  the  third  part  of  t he Yacc  specification  by 
t he  statement 

# i n c l u de  " l e x . y y. c" 

and  we  have  each  Lex  action  return  a  terminal  known  to Yacc.  By  using 
the  # i n c l u de  " l e x . y y. c"  statement,  the  program  y y l ex  has  access  to Yacc's 
names  for  tokens,  since  the  Lex  output  file  is  compiled  as  p a rt  of  the Yacc 
o u t p ut  file y.tab.c. 

Under  the  UNIX  system,  if  the  Lex  specification  is  in  t he  file  f i r s t .l  and 

the Yacc  specification  in  s e c o n d . y,  we  can  say 

4.9. 

PARSER  GENERATORS 

295 

lex  first.1 

yacc  second.y 

cc  y.tab.c  -ly  -11 

to  obtain  the  desired  translator. 

The Lex  specification  in  Fig.  4.60  can  be  used  in  place  of the  lexical  analyzer 
in  Fig.  4.59.  T he  last  p a t t e r n,  meaning  "any  character,"  must  be  written \n| . 
since  the  dot  in  Lex  matches  any  character  except  newline, 

number 

[0-9]+\e.?I [0-9]*\e. [0-9] + 

7,7. 

[ ] 

{  /*  skip  blanks  */  } 

{number} {  sscanf (yytext,  "7,lf",  &yylval); 

\ n |. 

{  return  yytext[0];  } 

return  NUMBER;  } 

Figure  4.60:  Lex  specification  for y y l e xQ  in  Fig.  4.59 

4.9.4  Error  Recovery  in  Yacc 

In Yacc,  error  recovery  uses  a  form  of  error  productions.  First,  the  user  de 
cides  what  "major"  nonterminals  will  have  error  recovery  associated  with  them. 
Typical  choices  are  some  subset  of  the  nonterminals  generating  expressions, 
statements,  blocks,  and  functions.  The  user  then  adds  to  the  grammar  error 
productions  of  the  form  A -» error  a,  where  A  is  a  major  nonterminal  and 
a  is  a  string  of  grammar  symbols,  perhaps  the  empty  string; error  is  a Yacc 
reserved  word.  Yacc  will  generate  a  parser  from  such  a  specification,  treating 
the  error  productions  as  ordinary  productions. 

However,  when  the  parser  generated  by Yacc  encounters  an  error,  it  treats 
the  states  whose  sets  of  items  contain  error  productions  in  a  special  way.  On 
encountering  an  error, Yacc  pops  symbols  from  its  stack  until  it  finds  t he  top 
most  state  on  its  stack  whose  underlying  set  of  items  includes  an  item  of  t he 
form  A  —>  • error a.  The  parser  then  "shifts"  a fictitious  token error  onto  t he 
stack,  as  though  it  saw  the  token error  on  its  input. 

When  cc  is  e,  a  reduction  to  A  occurs  immediately  and  t he  semantic  action 
associated  with  the  production  A —>• • error  (which  might  be  a  user-specified 
error-recovery routine)  is  invoked.  T he  parser  then  discards  input  symbols  until 
it  finds  an  input  symbol  on  which  normal  parsing  can  proceed. 

If  a  is  not  empty, Yacc  skips  ahead  on  the  input  looking  for  a  substring 
t h at  can  be  reduced  to  a.  If  a  consists  entirely  of  terminals,  then  it  looks  for 
this  string  of terminals  on  t he  input,  and  "reduces"  t h em  by  shifting  them  onto 
the  stack.  At  this  point,  t he  parser  will  have error  a  on  top  of  its  stack.  The 
parser  will  then  reduce error  a  to  A,  and  resume  normal  parsing. 

For  example,  an  error  production  of  the  form 

296 

CHAPTER  4. 

SYNTAX  ANALYSIS 

%{ 
#include  <ctype.h> 

#include  <stdio.h> 

#define  YYSTYPE  double  /* double type for Yacc stack */ 

'/.} 
'/.token NUMBER 

'/.left > + » '-' 

'/.left  >*'  '/' 

'/.right  UMINUS 

'/,'/. 

lines  :  lines expr  >\n' 

{ printf ("°/,g\n",  $ 2 );  } 

I  lines  '\n; 

I  /*  empty */ 

I  error  '\n'  { yyerror("reenter previous line:"); 

yyerrok;  } 

> 

expr  :  expr  '+'  expr 

{  $$ =  $1  +  $3;  } 

I  expr  '-'  expr 

{  $$  =  $1  -  $3;  } 

I  expr  '*'  expr 

{  $$  =  $1  *  $3;  } 

I  expr 

expr 

{  $$  =  $1  /  $3;  } 

I  ' (' expr ' )' 

{  $$ = $2;  } 

I  '-'  expr  %prec UMINUS  {  $$ =  -  $2;  } 

|  NUMBER 

n 

#include  "lex.yy.c" 

Figure 4.61:  Desk  calculator  with  error  recovery 

stmt  ->  error ; 

would  specify  to  t he  parser  t h at  it  should  skip  just  beyond  the  next  semicolon 
on  seeing  an  error,  and  assume  t h at  a  statement  had  been  found.  T he  semantic 
routine  for  this  error  production  would  not  need  to  manipulate  the  input,  but 
could  generate  a  diagnostic  message  and  set  a  flag  to  inhibit  generation  of object 
code,  for  example. 

E x a m p le  4. 7 0:  Figure 4.61  shows  t he Yacc  desk  calculator  of Fig. 4.59  with 
the  error  production 

lines  :  error  '\n' 

This  error  production  causes  t he  desk  calculator  to  suspend  normal  parsing 
when  a  syntax  error  is  found  on  an  input  line.  On  encountering  t he  error, 

4.10. 

SUMMARY  OF  CHAPTER  4 

297 

t he  parser  in  t he  desk  calculator  starts  popping  symbols  from  its  stack  until  it 
encounters  a  state  t h at  has  a  shift  action  on  the  token  error.  State  0  is  such  a 
state  (in  this  example,  it's  the  only  such  state),  since  its  items  include 

lines  —y  • error  ' \ n' 

Also,  state  0  is  always  on  t he  b o t t om  of  the  stack.  The  parser  shifts  the  token 
error  onto  the  stack,  and  then  proceeds  to  skip  ahead  in  the  input  until  it  has 
found  a  newline  character.  At  this  point  the  parser  shifts  the  newline  onto  the 
stack,  reduces  error  ' \ n'  to  lines,  and  emits  the  diagnostic  message  "reenter 
previous  line:".  T he  special Yacc  routine  y y e r r ok resets  the  parser to  its  normal 
mode  of  operation. 

• 

4.9.5  Exercises  for  Section  4.9 

!  E x e r c i se  4 . 9 . 1:  Write  a Yacc  program t h at  takes boolean  expressions  as  input 
[as  given  by  t he  grammar  of  Exercise  4.2.2(g)]  and  produces  the  t r u th  value  of 
t he  expressions. 

!  E x e r c i se  4 . 9 . 2:  Write  a Yacc  program  t h at  takes  lists  (as  defined  by  the 
g r a m m ar  of  Exercise  4.2.2(e),  but  with  any  single  character  as  an  element,  not 
just  a)  and  produces  as  output  a  linear  representation  of  the  same  list;  i.e.,  a 
single  list  of  t he  elements,  in  t he  same  order  t h at  they  appear  in  the  input. 

!  E x e r c i se  4 . 9 . 3:  Write  a Yacc  program  t h at  tells  whether  its  input  is  a  palin 
drome  (sequence  of  characters  t h at  read  the  same  forward  and  backward). 

!  E x e r c i se  4 . 9 . 4:  Write  a Yacc  program  t h at  takes  regular  expressions  (as  de 
fined  by  the  g r a m m ar  of  Exercise  4.2.2(d),  but  with  any  single  character  as  an 
argument,  not  just  a)  and  produces  as  output  a  transition  table  for  a  nonde 
terministic  finite  a u t o m a t on  recognizing  the  same  language. 

4.10  Summary  of  Chapter  4 

•  Parsers.  A  parser  takes  as  input  tokens  from  t he  lexical  analyzer  and 
treats  the  token  names  as  terminal  symbols  of  a  context-free  grammar. 
T he  parser  then  constructs  a  parse  tree  for  its  input  sequence  of  tokens; 
t he  parse  tree  may  be  constructed  figuratively  (by  going  through  the  cor 
responding  derivation  steps)  or  literally. 

•  Context-Free  Grammars.  A  grammar  specifies  a  set  of  terminal  symbols 
(inputs),  another  set  of nonterminals  (symbols  representing  syntactic  con 
structs),  and  a  set  of  productions,  each  of  which  gives  a  way  in  which 
strings  represented  by  one  nonterminal  can  be  constructed  from  terminal 
symbols  and  strings  represented  by  certain  other  nonterminals.  A  pro 
duction  consists  of  a  head  (the  nonterminal  to  be  replaced)  and  a  body 
(the  replacing  string  of  grammar  symbols). 

298 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

•  Derivations.  T he  process  of starting  with  t he  start-nonterminal  of a  gram 
mar  and  successively  replacing  it  by  the  body  of  one  of  its  productions  is 
called  a  derivation.  If  the  leftmost  (or  rightmost)  nonterminal  is  always 
replaced,  then  the  derivation  is  called  leftmost  (respectively,  rightmost). 

•  Parse  Trees.  A  parse  tree  is  a  picture  of  a  derivation,  in  which  there  is 
a  node  for  each  nonterminal  t h at  appears  in  t he  derivation.  T he  children 
of  a  node  are  the  symbols  by  which  t h at  nonterminal  is  replaced  in  the 
derivation.  There is  a one-to-one  correspondence between  parse  trees,  left 
most  derivations,  and  rightmost  derivations  of  t he  same  terminal  string. 

•  Ambiguity.  A  grammar  for  which  some  terminal  string  has  two  or  more 
different  parse  trees,  or  equivalently  two  or  more  leftmost  derivations  or 
two  or  more  rightmost  derivations,  is  said  to  be  ambiguous.  In  most  cases 
of  practical  interest,  it  is  possible  to  redesign  an  ambiguous  g r a m m ar  so 
it  becomes  an  unambiguous  grammar  for  t he  same  language.  However, 
ambiguous  grammars  with  certain  tricks  applied  sometimes  lead  to  more 
efficient  parsers. 

•  Top-Down  and  Bottom-Up  Parsing. 

Parsers  are  generally  distinguished 

by  whether  they  work  top-down  (start  with  t he  g r a m m a r 's  start  symbol 
and  construct  the  parse  tree  from  t he  top)  or  b o t t o m - up  (start  with  t he 
terminal  symbols  t h at  form  t he  leaves  of  t he  parse  tree  and  build  the 
tree  from  the  b o t t o m ).  Top-down  parsers  include  recursive-descent  and 
LL  parsers,  while  the  most  common  forms  of  b o t t o m - up  parsers  are  LR 
parsers. 

•  Design  of  Grammars.  G r a m m a rs  suitable  for  top-down  parsing  often  are 
harder  to  design  t h an  those  used  by  b o t t o m - up  parsers.  It  is  necessary 
to  eliminate  left-recursion,  a  situation  where  one  nonterminal  derives  a 
string  t h at  begins  with  t he  same  nonterminal.  We  also  must  left-factor  — 
group  productions  for  t he  same  nonterminal  t h at  have  a  common  prefix 
in  the  body. 

•  Recursive-Descent  Parsers.  These  parsers  use  a  procedure  for  each  non 
terminal.  The  procedure  looks  at  its  input  and  decides  which  production 
to  apply  for  its  nonterminal.  Terminals  in  the  body  of t he  production  are 
matched  to  the  input  at  t he  appropriate  time,  while  nonterminals  in  t he 
body  result  in  calls  to  their  procedure.  Backtracking,  in  the  case  when 
the  wrong  production  was  chosen,  is  a  possibility. 

•  LL(1)  Parsers.  A  g r a m m ar  such  t h at  it  is  possible  to  choose  t he  correct 
production  with  which  to  expand  a  given  nonterminal,  looking  only  at 
t he  next  input  symbol,  is  called  LL(1).  These  grammars  allow  us  to 
construct  a  predictive  parsing  table  t h at  gives,  for  each  nonterminal  and 
each  lookahead  symbol,  t he  correct  choice  of production.  Error  correction 
can  be  facilitated  by  placing  error  routines  in  some  or  all  of  the  table 
entries  t h at  have  no  legitimate  production. 

4.10. 

SUMMARY  OF  CHAPTER  4 

299 

•  Shift-Reduce  Parsing.  Bottom-up  parsers  generally  operate  by  choosing, 
on  t he  basis  of t he  next  input  symbol  (lookahead  symbol)  and  the  contents 
of  t he  stack,  whether  to  shift  the  next  input  onto  the  stack,  or  to  reduce 
some  symbols  at  the  top  of  the  stack.  A  reduce  step  takes  a  production 
body  at  the  top  of the  stack  and  replaces  it  by  the  head  of the  production. 

4-  Viable  Prefixes.  In  shift-reduce  parsing,  the  stack  contents  are  always  a 
viable  prefix  —  t h at  is,  a  prefix  of  some  right-sentential  form  t h at  ends 
no  further  right  t h an  the  end  of  the  handle  of  t h at  right-sentential  form. 
T he  handle  is  the  substring  t h at  was  introduced  in  the  last  step  of  the 
rightmost  derivation  of  t h at  sentential  form. 

•  Valid  Items.  An  item  is  a  production  with  a  dot  somewhere  in  the  body. 
An  item  is  valid  for  a  viable  prefix  if  the  production  of  t h at  item  is  used 
to  generate  the  handle,  and  the  viable  prefix  includes  all  those  symbols 
to  the  left  of  the  dot,  but  not  those  below. 

•  LR  Parsers.  Each  of  the  several  kinds  of  LR  parsers  operate  by  first 
constructing  the  sets  of  valid  items  (called  LR  states)  for  all  possible 
viable  prefixes,  and  keeping  track  of t he  state  for  each  prefix  on  t he  stack. 
T he  set  of  valid  items  guide  the  shift-reduce  parsing  decision.  We  prefer 
to  reduce  if there  is  a  valid  item  with  t he  dot  at  the  right  end  of the  body, 
and  we  prefer  to  shift  t he  lookahead  symbol  onto  the  stack  if  t h at  symbol 
appears  immediately  to  the  right  of  the  dot  in  some  valid  item. 

•  Simple  LR  Parsers.  In  an  SLR  parser,  we  perform  a  reduction  implied  by 
a  valid  item  with  a  dot  at  t he  right  end,  provided  the  lookahead  symbol 
can  follow  t he  head  of  t h at  production  in  some  sentential  form.  The 
grammar  is  SLR,  and  this  method  can  be  applied,  if there  are  no  parsing-
action  conflicts;  t h at  is,  for  no  set  of  items,  and  for  no  lookahead  symbol, 
are  there  two  productions  to  reduce  by,  nor  is  there  the  option  to  reduce 
or  to  shift. 

•  Canonical-LR  Parsers.  This  more  complex  form  of  LR  parser  uses  items 
t h at  are  augmented  by  the  set  of lookahead  symbols  t h at  can  follow  t he  use 
of the  underlying  production.  Reductions  are  only  chosen  when  there  is  a 
valid  item  with  the  dot  at  the  right  end,  and  t he  current  lookahead  symbol 
is  one  of those  allowed for this  item.  A  canonical-LR parser  can  avoid  some 
of  t he  parsing-action  conflicts  t h at  are  present  in  SLR  parsers,  but  often 
has  many  more  states  t h an  the  SLR  parser  for  the  same  grammar. 

•  Lookahead-LR  Parsers.  LALR  parsers  offer  many  of  t he  advantages  of 
SLR  and  Canonical-LR  parsers,  by  combining  t he  states  t h at  have  the 
same  kernels  (sets  of items,  ignoring t he  associated  lookahead  sets).  Thus, 
t he  number  of  states  is  t he  same  as  t h at  of  the  SLR  parser,  but  some 
parsing-action  conflicts  present  in  the  SLR  parser  may  be  removed  in 
t he  LALR  parser.  LALR  parsers  have  become  the  method  of  choice  in 
practice. 

300 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

•  Bottom-  Up  Parsing  of  Ambiguous  Grammars. 

In  many  important  situa 
tions,  such  as  parsing  arithmetic  expressions,  we  can  use  an  ambiguous 
grammar,  and  exploit  side  information  such  as  t he  precedence  of operators 
to  resolve  conflicts  between  shifting  and  reducing,  or  between  reduction  by 
two  different  productions.  Thus,  LR  parsing  techniques  extend  to  many 
ambiguous  grammars. 

•  Yacc.  T he  parser-generator Yacc  takes  a  (possibly)  ambiguous  g r a m m ar 
It 
and  conflict-resolution  information  and  constructs  t he  LALR  states. 
then  produces  a  function  t h at  uses  these  states  to  perform  a  b o t t o m - up 
parse  and  call  an  associated  function  each  time  a  reduction  is  performed. 

4.11  References  for  Chapter  4 

T he  context-free  grammar  formalism  originated  with  Chomsky  [5],  as  part  of 
a  study  on  natural  language.  T he  idea  also  was  used  in  t he  syntax  description 
of  two  early  languages:  Fortran  by  Backus  [2]  and  Algol  60  by  Naur  [26].  The 
scholar  Panini  devised  an  equivalent  syntactic  notation  to  specify  the  rules  of 
Sanskrit  g r a m m ar  between  400  B.C.  and  200  B.C.  [19]. 

T he  phenomenon  of  ambiguity  was  observed  first  by  Cantor  [4]  and  Floyd 
[13].  Chomsky  Normal  Form  (Exercise  4.4.8)  is  from  [6].  T he  theory  of context-
free  grammars  is  summarized  in  [17]. 

Recursive-descent  parsing  was  the  method  of  choice  for  early  compilers, 
such  as  [16],  and  compiler-writing  systems,  such  as  META  [28]  and  T MG  [25]. 
LL  grammars  were  introduced  by  Lewis  and  Stearns  [24].  Exercise  4.4.5,  t he 
linear-time  simulation  of  recursive-descent,  is  from  [3]. 

One  of the  earliest  parsing  techniques,  due  to  Floyd  [14],  involved  t he  prece 
dence  of  operators.  T he  idea  was  generalized  to  p a r ts  of  t he  language  t h at  do 
not  involve  operators  by  W i r th  and  Weber  [29].  These  techniques  are  rarely 
used  today,  but  can  be  seen  as  leading  in  a  chain  of improvements  to  LR  parsing. 
LR  parsers  were  introduced  by  K n u th  [22],  and  the  canonical-LR  parsing 
tables  originated  there.  This  approach  was  not  considered  practical,  because  the 
parsing  tables  were  larger  t h an  the  main  memories  of  typical  computers  of  t he 
day,  until  Korenjak  [23]  gave  a  method  for  producing  reasonably  sized  parsing 
tables  for  typical  programming  languages.  DeRemer  developed  t he  LALR  [8] 
and  SLR  [9]  methods  t h at  are  in  use  today.  The  construction  of  LR  parsing 
tables  for  ambiguous  grammars  came  from  [1]  and  [12]. 

Johnson's Yacc  very  quickly  demonstrated  t he  practicality  of  generating 
parsers  with  an  LALR  parser  generator  for  production  compilers.  T he  manual 
for  t he Yacc  parser  generator  is  found  in  [20].  T he  open-source  version,  B i s o n, 
is  described  in  [10].  A  similar  LALR-based  parser  generator  called  CUP  [18] 
supports  actions  written  in  Java.  Top-down  parser  generators  incude  A n t lr 
[27],  a  recursive-descent  parser  generator  t h at  accepts  actions  in  C + +,  Java,  or 
C #,  and  LLGen  [15],  which  is  an  LL(l)-based  generator. 

Dain  [7]  gives  a  bibliography  on  syntax-error  handling. 

4.11.  REFERENCES  FOR  CHAPTER  4 

301 

T he  general-purpose  dynamic-programming  parsing  algorithm  described  in 
Exercise  4.4.9  was  invented  independently  by  J.  Cocke  (unpublished)  by  Young 
er  [30]  and  Kasami  [21];  hence  t he  "CYK  algorithm."  There  is  a  more  complex, 
general-purpose  algorithm  due  to  Earley  [11]  t h at  tabulates  LR-items  for  each 
substring  of t he  given  input;  this  algorithm,  while  also  0 ( n3)  in  general,  is  only 
0 ( n2)  on  unambiguous  grammars. 

1.  Aho,  A.  V.,  S.  C.  Johnson,  and  J.  D.  Ullman,  "Deterministic  parsing  of 
ambiguous  grammars,"  Comm.  ^ C M 1 8 :8  (Aug.,  1975),  pp.  441-452. 

2.  Backus,  J.W,  "The  syntax  and  semantics  of  t he  proposed  international 

algebraic  language  of  the  Zurich-ACM-GAMM  Conference,"  Proc.  Intl. 
Conf.  Information  Processing,  U N E S C O,  Paris,  (1959)  p p.  125-132. 

3.  Birman,  A.  and  J.  D.  Ullman,  "Parsing  algorithms  with  backtrack,"  In 

formation  and  Control  23:1  (1973),  pp.  1-34. 

4.  Cantor,  D.  C,  "On  the  ambiguity  problem  of  Backus  systems,"  J.  ACM 

9:4  (1962),  pp.  477-479. 

5.  Chomsky,  N.,  "Three  models  for  the  description  of language,"  IRE  Trans, 

on  Information  Theory  I T - 2 :3  (1956),  p p.  113-124. 

6.  Chomsky,  N.,  "On  certain  formal  properties  of  grammars,"  Information 

and  Control  2:2  (1959),  pp.  137-167. 

7.  Dain,  J.,  "Bibliography  on  Syntax  Error  Handling  in  Language  Transla 
tion  Systems,"  1991.  Available  from  the  comp. c o m p i l e rs  newsgroup;  see 
h t t p : / / c o m p i l e r s . i e c c . c o m / c o m p a r c h / a r t i c l e / 9 1 - 0 4 - 0 50 

. 

8.  DeRemer,  F.,  "Practical  Translators  for  LR(fc)  Languages,"  P h . D.  thesis, 

M I T,  Cambridge,  MA,  1969. 

9.  DeRemer,  F.,  "Simple  LR(fc)  grammars,"  Comm.  ACM  14:7  (July,  1971), 

p p.  453-460. 

10.  Donnelly,  C.  and  R.  Stallman,  "Bison:  T he  YACC-compatible  Parser 

Generator,"  h t t p : / / w w w . g n u . o r g / s o f t w a r e / b i s o n / m a n u a l/  . 

11.  Earley,  J.,  "An  efficient  context-free  parsing  algorithm,"  Comm.  ACM 

13:2  (Feb.,  1970),  pp.  94-102. 

12.  Earley,  J.,  "Ambiguity  and  precedence  in  syntax  description,"  Acta  In 

formation  4:2  (1975),  pp.  183-192. 

13.  Floyd,  R.  W.,  "On  ambiguity  in  phrase-structure  languages,"  Comm. 

ACM  5:10  (Oct.,  1962),  pp.  526-534. 

14.  Floyd,  R.  W.,  "Syntactic  analysis  and  operator  precedence,"  J.  A CM 10:3 

(1963),  pp.  316-333. 

302 

CHAPTER 

4. 

SYNTAX  ANALYSIS 

15.  Grune,  D  and  C.  J.  H.  Jacobs,  "A  programmer-friendly  LL(1)  parser 
generator,"  Software  Practice  and  Experience  18:1  (Jan.,  1988),  pp.  29¬ 
38. See also http://www.cs.vu.nl/~ceriel/LLgen.html . 

16.  Hoare,  C.  A.  R.,  "Report  on  the  Elliott  Algol  translator,"  Computer  J. 

5:2  (1962),  pp.  127-129. 

17.  Hopcroft,  J.  E.,  R.  Motwani,  and  J.  D.  Ullman,  Introduction  to  Automata 
Theory,  Languages,  and  Computation,  Addison-Wesley,  Boston  MA,  2001. 

18.  Hudson,  S.  E.  et  al.,  "CUP  LALR  Parser  Generator  in  Java,"  Available 

at http://www2.cs.tum.edu/projects/cup/ . 

19.  Ingerman,  P.  Z.,  "Panini-Backus  form  suggested,"  Comm.  ACM  10:3 

(March  1967),  p.  137. 

20.  Johnson,  S.  C,  "Yacc  —  Yet  Another  Compiler  Compiler,"  Computing 
Science  Technical  Report  32,  Bell  Laboratories,  Murray  Hill,  N J,  1975. 
Available at http://dinosaur.compilertools.net/yacc/ . 

21.  Kasami,  T.,  "An  efficient  recognition  and  syntax  analysis  algorithm  for 
context-free  languages,"  AFCRL-65-758,  Air  Force  Cambridge  Research 
Laboratory,  Bedford,  MA,  1965. 

22.  Knuth,  D.  E.,  "On  the  translation  of  languages  from  left  to  right,"  Infor 

mation  and  Control  8:6  (1965),  pp.  607-639. 

23.  Korenjak,  A.  J.,  "A  practical  method  for  constructing  LR(fc)  processors," 

Comm.  ACM  12:11  (Nov.,  1969),  pp.  613-623. 

24.  Lewis,  P.  M.  II  and  R.  E.  Stearns,  "syntax-directed  transduction,"  J. 

ACM  15:3  (1968),  pp.  465-488. 

25.  McClure,  R.  M.,  "TMG  —  a  syntax-directed  compiler,"  proc.  20th  ACM 

Natl.  Conf.  (1965),  p p.  262-274. 

26.  Naur,  P.  et  al.,  "Report  on  the  algorithmic  language  ALGOL  60,"  Comm. 
ACM  3:5  (May,  1960),  pp.  299-314.  See  also  Comm.  ACM  6:1  (Jan., 
1963),  pp.  1-17. 

27.  Parr, T., "ANTLR," http://www.antlr.org/ . 

28.  Schorre,  D.  V.,  "Meta-II:  a  syntax-oriented  compiler  writing  language," 

Proc.  19th  ACM  Natl.  Conf. 

(1964)  p p.  D1.3-1-D1.3-11. 

29.  Wirth,  N.  and  H.  Weber,  "Euler:  a  generalization  of  Algol  and  its  formal 

definition:  P a rt  I,"  Comm.  ACM  9:1  (Jan.,  1966),  p p.  13-23. 

30.  Younger,  D.H.,  "Recognition  and  parsing  of context-free  languages  in  time 

n3,"  Information  and  Control  10:2  (1967),  pp.  189-208. 

Chapter  5 

Syntax-Directed 
Translation 

This  chapter  develops  the  theme  of  Section  2.3: 
the  translation  of  languages 
guided  by  context-free  grammars.  T he  translation  techniques  in  this  chapter 
will  be  applied  in  Chapter  6  to  type  checking  and  intermediate-code  generation. 
T he  techniques  are  also  useful  for  implementing  little  languages  for  specialized 
tasks;  this  chapter  includes  an  example  from  typesetting. 

We  associate  information  with  a  language  construct  by  attaching  attributes 

to  t he  g r a m m ar  symbol(s)  representing  the  construct,  as  discussed  in  Sec 
tion  2.3.2.  A  syntax-directed  definition  specifies  the  values  of  attributes  by 
associating  semantic  rules  with  the  grammar  productions.  For  example,  an 
infix-to-postfix  translator  might  have  a  production  and  rule 

PR O D U C T I ON 

E  ->  Ei  +  T 

SE M A N T IC 

RU LE 

E.code  =  Ei.code  ||  T.code  ||  '+' 

(5.1) 

This  production  has  two  nonterminals,  E  and  T;  t he  subscript  in  E\  distin 
guishes  t he  occurrence  of  E  in  t he  production  body  from  t he  occurrence  of  E 
as  the  head.  Both  E  and  T  have  a  string-valued  attribute  code.  T he  semantic 
rule  specifies  t h at  t he  string  E.code  is  formed  by  concatenating  Ei.code,  T.code, 
and  t he  character  '+'.  While  the  rule  makes  it  explicit  t h at  the  translation  of 
E  is  built  up  from  the  translations  of  E\,  T,  and  '+',  it  may  be  inefficient  to 
implement  the  translation  directly  by  manipulating  strings. 

From  Section  2.3.5,  a  syntax-directed  translation  scheme  embeds  program 

fragments  called  semantic  actions  within  production  bodies,  as  in 

E  -»  Ei  +  T  {  print  '+'  } 

(5.2) 

By  convention,  semantic  actions  are  enclosed  within  curly  braces. 
(If  curly 
braces  occur  as  g r a m m ar  symbols,  we  enclose  t h em  within  single  quotes,  as  in 

303 

304 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

' {'  and  '}'.)  T he  position  of a  semantic  action  in  a  production  body  determines 
the  order  in  which  the  action  is  executed. 
In  production  (5.2),  t he  action 
occurs  at  the  end,  after  all  t he  grammar  symbols;  in  general,  semantic  actions 
may  occur  at  any  position  in  a  production  body. 

Between t he  two  notations,  syntax-directed  definitions  can  be  more readable, 
and  hence  more  useful  for  specifications.  However,  translation  schemes  can  be 
more  efficient,  and  hence  more  useful  for  implementations. 

T he  most  general  approach  to  syntax-directed  translation  is  to  construct  a 
parse  tree  or  a  syntax  tree,  and  then  to  compute  the  values  of attributes  at  t he 
nodes  of  the  tree  by  visiting  the  nodes  of  the  tree.  In  many  cases,  translation 
can  be  done  during  parsing,  without  building  an  explicit  tree.  We  shall  therefore 
study  a  class  of  syntax-directed  translations  called  "L-attributed  translations" 
(L  for  left-to-right),  which  encompass  virtually  all  translations  t h at  can  be 
performed  during  parsing.  We  also  study  a  smaller  class,  called  "S-attributed 
translations"  (S  for  synthesized),  which  can  be  performed  easily  in  connection 
with  a  bottom-up  parse. 

5.1 

Syntax-Directed  Definitions 

is  a  context-free  g r a m m ar  together  with 
A  syntax-directed  definition  (SDD) 
attributes  and  rules.  Attributes  are  associated  with  g r a m m ar  symbols  and  rules 
are  associated  with  productions.  If X  is  a  symbol  and  a  is  one  of its  attributes, 
then  we  write  X.a  to  denote  t he  value  of  a  at  a  particular  parse-tree  node 
labeled  X.  If  we  implement  t he  nodes  of  t he  parse  tree  by  records  or  objects, 
then  the  attributes  of  X  can  be  implemented  by  d a ta  fields  in  t he  records  t h at 
represent  the  nodes  for  X.  Attributes  may  be  of any  kind:  numbers,  types,  table 
references,  or  strings,  for  instance.  T he  strings  may  even  be  long  sequences  of 
code,  say  code  in  t he  intermediate  language  used  by  a  compiler. 

5.1.1 

Inherited  and  Synthesized  Attributes 

We  shall  deal  with  two  kinds  of  attributes  for  nonterminals: 

1.  A  synthesized  attribute  for  a  nonterminal  A  at  a  parse-tree  node  N  is 
defined  by  a  semantic  rule  associated  with  the  production  at  N.  Note 
t h at  the  production  must  have  A  as  its  head.  A  synthesized  a t t r i b u te  at 
node  N  is  defined  only  in  terms  of  a t t r i b u te  values  at  t he  children  of  N 
and  at  N  itself. 

2.  An 

inherited  attribute  for  a  nonterminal  B  at  a  parse-tree  node  N  is 
defined  by  a  semantic  rule  associated  with  t he  production  at  the  parent 
of  N.  Note  t h at  the  production  must  have  B  as  a  symbol  in  its  body.  An 
inherited  a t t r i b u te  at  node  N  is  defined  only  in  terms  of  a t t r i b u te  values 
at  JV's  parent,  N  itself,  and  N's  siblings. 

5.1. 

SYNTAX-DIRECTED  DEFINITIONS 

3 05 

An  Alternative  Definition  of  Inherited  Attributes 

No  additional  translations  are  enabled  if  we  allow  an  inherited  a t t r i b u te 
B.c  at  a  node  N  to  be  defined  in  terms  of  a t t r i b u te  values  at  t he  children 
of A?",  as  well  as  at  N  itself,  at  its  parent,  and  at  its  siblings.  Such  rules  can 
be  "simulated"  by  creating  additional  attributes  of  B,  say  B.ci,B.c2,.... 
These  are  synthesized  attributes  t h at  copy  t he  needed  attributes  of  t he 
children  of  t he  node  labeled  B.  We  then  compute  B.c  as  an  inherited 
attribute,  using  the  attributes  B.ci,  B.c2,... 
in  place  of  attributes  at  t he 
children.  Such  attributes  are  rarely  needed  in  practice. 

While  we  do  not  allow  an  inherited  attribute  at  node  N  to  be  defined  in  terms  of 
a t t r i b u te  values  at  the  children  of  node  N,  we  do  allow  a  synthesized  a t t r i b u te 
at  node  N  to  be  defined  in  terms  of  inherited  attribute  values  at  node  N  itself. 
Terminals  can  have  synthesized  attributes,  but  not  inherited  attributes.  At 
tributes  for  terminals  have  lexical  values  t h at  are  supplied  by  the  lexical  ana 
lyzer;  there  are  ho  semantic  rules  in  the  SDD  itself  for  computing  the  value  of 
an  a t t r i b u te  for  a  terminal. 

E x a m p le  5 . 1:  T he  SDD  in  Fig.  5 .1  is  based  on  our  familiar  grammar  for 
arithmetic  expressions  with  operators  +  and  *.  It  evaluates  expressions  termi 
nated  by  an  endmarker  n.  In  the  SDD,  each  of  the  nonterminals  has  a  single 
synthesized  attribute,  called  val  We  also  suppose  t h at  t he  terminal  d i g it  has 
a  synthesized  a t t r i b u te  lexval,  which  is  an  integer  value  returned  by  the  lexical 
analyzer. 

PR O D U C T I ON 

SE M A N T IC 

RU L ES 

En 

L.val  =  E.val 

E  ->  E1  +  T 

E.val  =  Ei.val  +  T.val 

E^T 
T^TX 

E.val  =  T.val 

* 

F 

T.val  =  Ti.val  x  F.val 

T  ->  F 

F-y(E) 

T.val  =  F.val 

F.val  =  E.val 

F  ->•  digit 

F.val  =  digit.lexval 

1) 

2) 

3) 

4) 

5) 

6) 

7) 

Figure  5 . 1:  Syntax-directed  definition  of  a  simple  desk  calculator 

T he  rule  for  production  1,  L  ->•  E  n,  sets  L.val  to  E.val,  which  we  shall  see 

is  t he  numerical  value  of  the  entire  expression. 

Production  2,  E  ->  Ex  +  T,  also  has  one  rule,  which  computes  t he  val 

a t t r i b u te  for  the  head  E  as  t he  sum  of  t he  values  at  E\  and  T.  At  any  parse-

306 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

tree  node  N  labeled  E,  the  value  of  val  for  E  is  the  sum  of  t he  values  of  val  at 
the  children  of  node  N  labeled  E  and  T. 

Production  3,  E  -»•  T,  has  a  single  rule  t h at  defines  t he  value  of  val  for  E 
to  be  the  same  as  the  value  of  val  at  the  child  for  T.  Production  4  is  similar  to 
the  second  production;  its  rule  multiplies  the  values  at  t he  children  instead  of 
adding  them.  T he  rules  for  productions  5  and  6  copy  values  at  a  child,  like  t h at 
for  the  third  production.  Production  7  gives  F.val  t he  value  of  a  digit,  t h at  is, 
t he  numerical  value  of  t he  token  d i g it  t h at  the  lexical  analyzer  returned. 

• 

An  SDD  t h at  involves  only  synthesized  attributes  is  called  S-attributed;  the 
SDD  in  Fig.  5.1  has  this  property.  In  an  S-attributed  SDD,  each  rule  computes 
an  attribute  for  the  nonterminal  at  t he  head  of  a  production  from  attributes 
taken  from  the  body  of  t he  production. 

For  simplicity,  the  examples  in  this  section  have  semantic  rules  without 
side  effects. 
In  practice,  it  is  convenient  to  allow  SDD's  to  have  limited  side 
effects,  such  as  printing  t he  result  computed  by  a  desk  calculator  or  interacting 
with  a  symbol  table.  Once  t he  order  of  evaluation  of  attributes  is  discussed 
in  Section  5.2,  we  shall  allow  semantic  rules  to  compute  arbitrary  functions, 
possibly  involving  side  effects. 

An  S-attributed  SDD  can  be  implemented  naturally  in  conjunction  with  an 
LR  parser.  In  fact,  t he  SDD  in  Fig.  5.1  mirrors  t he  Yacc  program  of  Fig.  4.58, 
which  illustrates  translation  during  LR  parsing.  T he  difference  is  t h a t,  in  the 
rule  for  production  1,  the  Yacc  program  prints  the  value  E.val  as  a  side  effect, 
instead  of  defining  t he  attribute  L.val. 

An  SDD  without  side  effects  is  sometimes  called  an  attribute  grammar.  T he 
rules  in  an  a t t r i b u te  g r a m m ar  define  t he  value  of  an  a t t r i b u te  purely  in  terms 
of  the  values  of  other  attributes  and  constants. 

5.1.2  Evaluating  an  SDD  at  the  Nodes  of  a  Parse  Tree 

To  visualize  t he  translation  specified  by  an  SDD,  it  helps  to  work  with  parse 
trees,  even  though  a  translator  need  not  actually  build  a  parse  tree.  Imagine 
therefore  t h at  the  rules  of  an  SDD  are  applied  by  first  constructing  a  parse  tree 
and  then  using  the  rules  to  evaluate  all  of  t he  attributes  at  each  of  the  nodes 
of t he  parse  tree.  A  parse  tree,  showing  t he  value(s)  of its  attribute(s)  is  called 
an  annotated  parse 

tree. 

How  do  we  construct  an  annotated  parse  tree?  In  what  order  do  we  evaluate 
attributes?  Before  we  can  evaluate  an  a t t r i b u te  at  a  node  of  a  parse  tree,  we 
must  evaluate  all  the  attributes  upon  which  its  value  depends.  For  example, 
if  all  attributes  are  synthesized,  as  in  Example  5.1,  then  we  must  evaluate  the 
val  attributes  at  all  of  the  children  of  a  node  before  we  can  evaluate  the  val 
a t t r i b u te  at  the  node  itself. 

W i th  synthesized  attributes,  we  can  evaluate  attributes  in  any  b o t t o m - up 
order,  such  as  t h at  of  a  postorder  traversal  of  the  parse  tree;  the  evaluation  of 
S-attributed  definitions  is  discussed  in  Section  5.2.3. 

5.1. 

SYNTAX-DIRECTED  DEFINITIONS 

307 

For  SDD's  with  b o th  inherited  and  synthesized  attributes,  there  is  no  guar 
antee  t h at  there  is  even  one  order  in  which  to  evaluate  attributes  at  nodes. 
For  instance,  consider  nonterminals  A  and  B,  with  synthesized  and  inherited 
attributes  A.s  and  BA,  respectively,  along  with  the  production  and  rules 

PR O D U C T I ON 

SE M A N T IC 

RU L ES 

A^B 

A.s  =  B.i; 
B.i  =  A.s  +  l 

These  rules  are  circular;  it  is  impossible  to  evaluate  either  A.s  at  a  node  N  or  BA 
at  t he  child  of  N  without  first  evaluating  t he  other.  T he  circular  dependency 
of  A.s  and  BA  at  some  pair  of  nodes  in  a  parse  tree  is  suggested  by  Fig.  5.2. 

Figure  5.2:  T he  circular  dependency  of  A.s  and  BA  on  one  another 

It  is  computationally  difficult  to  determine  whether  or  not  there  exist  any 
circularities  in  any  of the  parse  trees  t h at  a  given  SDD  could  have  to  t r a n s l a t e .1 
Fortunately,  there  are  useful  subclasses  of SDD's  t h at  are  sufficient  to  guarantee 
t h at  an  order  of  evaluation  exists,  as  we  shall  see  in  Section  5.2. 

E x a m p le  5 . 2:  Figure  5.3  shows  an  annotated  parse  tree  for  the  input  string 
3  *  5  +  4  n,  constructed  using  the  grammar  and  rules  of  Fig.  5.1.  The  values 
of  lexval  are  presumed  supplied  by  the  lexical  analyzer.  Each  of  the  nodes  for 
t he  nonterminals  has  a t t r i b u te  val  computed  in  a  b o t t o m - up  order,  and  we  see 
the  resulting  values  associated  with  each  node.  For  instance,  at  the  node  with 
a  child  labeled  *,  after  computing  T.val  =  3  and  F.val  =  5  at  its  first  and  third 
children,  we  apply  the  rule  t h at  says  T.val  is  t he  product  of  these  two  values, 
or  15. 

• 

Inherited  attributes  are  useful  when  the  structure  of  a  parse  tree  does  not 
"match"  the  abstract  syntax  of  the  source  code.  T he  next  example  shows  how 
inherited  attributes  can  be  used  to  overcome  such  a mismatch  due  to  a  grammar 
designed  for  parsing  rather  t h an  translation. 

1 Without  going  into  details,  while  the  problem  is  decidable,  it  cannot  be  solved  by  a 

polynomial-time  algorithm,  even  if  V  =  NT,  since  it  has  exponential  time  complexity. 

308 

CHAPTER  5. 

SYNTAX-DIRECTED  TRANSLATION 

L.val= 

19 

E.val-19 

n 

E.val=lb 

+ 

T.val=4 

T.val-lb 

F.val=4 

T.val  =3 

* 

F.val  =5 

digit .lexval  =  4 

F.val =  3 

digit, lexval  =  5 

digit, lexval  =  3 

Figure  5.3:  Annotated  parse  tree  for  3  *  5  +  4  n 

E x a m p le  5 . 3:  The  SDD  in  Fig.  5.4  computes  terms  like  3 *5  and  3 * 5 * 7. 
T he  top-down  parse  of  input  3 *5  begins  with  the  production  T  ^  FT'.  Here, 
F  generates  t he  digit  3,  b ut  the  operator  *  is  generated  by  X".  Thus,  t he  left 
operand  3  appears  in  a  different  subtree  of  the  parse  tree  from  *.  An  inherited 
a t t r i b u te  will  therefore  be  used  to  pass  the  operand  to  t he  operator. 

T he  g r a m m ar  in  this  example  is  an  excerpt  from  a  non-left-recursive  version 
of  t he  familiar  expression  grammar;  we  used  such  a  g r a m m ar  as  a  running 
example  to  illustrate  top-down  parsing  in  Section  4.4. 

PR O D U C T I ON 

SE M A N T IC  RU L ES 

1)  T 

FT' 

T'.inh  =  F.val 

T.val  =  T'.syn 

2)  T'->*FT{ 

T[.inh  =  T'.inh  x  F.val 

T'.syn  =  T[.syn 

3)  T'  -> e 

T'.syn  =  T'.inh 

4) 

F  -»  d i g it 

F.val  =  d i g i t, lexval 

Figure  5.4:  An  SDD  based  on  a  g r a m m ar  suitable  for  top-down  parsing 

Each  of  the  nonterminals  T  and  F  has  a  synthesized  a t t r i b u te  val; 
t he 
terminal  d i g it  has  a  synthesized  a t t r i b u te  lexval.  T he  nonterminal  T  has  two 
attributes:  an  inherited  a t t r i b u te  inh  and  a  synthesized  a t t r i b u te  syn. 

5.1. 

SYNTAX-DIRECTED  DEFINITIONS 

309 

T he  semantic  rules  are  based  on  the  idea t h at  the  left  operand  of the  operator 
*  is  inherited.  More  precisely,  the  head  T"  of  the  production  T' 
*  F  T[ 
inherits  t he  left  operand  of  *  in  t he  production  body.  Given  a  term  x  *  y  *  z, 
t he  root  of  t he  subtree  for  *  y  *  z  inherits  x.  Then,  the  root  of  the  subtree  for 
*  z  inherits  t he  value  of  x  *  y,  and  so  on,  if there  are  more  factors  in  t he  term. 
Once  all  the  factors  have  been  accumulated,  the  result  is  passed  back  up  t he 
tree  using  synthesized  attributes. 

To  see  how  t he  semantic  rules  are  used,  consider  t he  annotated  parse  tree 
for  3  *  5  in  Fig.  5.5.  T he  leftmost  leaf  in  t he  parse  tree,  labeled  digit,  has 
a t t r i b u te  value  lexval  =  3,  where  the  3  is  supplied  by  the  lexical  analyzer.  Its 
parent  is  for  production  4,  F  ->  digit.  The  only  semantic  rule  associated  with 
this  production  defines  F.val  =  digit.lexval,  which  equals  3. 

T.val  =  15 

d i g it  .lexval  =  5 

e 

Figure  5.5:  Annotated  parse  tree  for  3  *  5 

At  the  second  child  of  the  root,  the  inherited  a t t r i b u te  T'.inh  is  defined  by 
t he  semantic  rule  T'.inh  =  F.val  associated  with  production  1.  Thus,  the  left 
operand,  3,  for  t he  *  operator  is  passed  from  left  to  right  across  the  children  of 
the  root. 

T he  production  at  the  node  for  V  is  X"  -»•  *  FT[.  (We  retain  the  subscript 
1  in  t he  a n n o t a t ed  parse  tree  to  distinguish  between  t he  two  nodes  for  T'.)  T he 
inherited  a t t r i b u te  T[.inh  is  defined  by  the  semantic  rule  T[.inh  =  T'.inhx  F.val 
associated  with  production  2. 

W i th  T'.inh  =  3  and  F.val  =  5,  we  get  T[.inh  = 1 5.  At  t he  lower  node 
for  T[,  t he  production  is  T"  ->•  e.  T he  semantic  rule  T'.syn  —  T'.inh  defines 
T{.syn  —  15.  T he  syn  attributes  at  the  nodes  for  X"  pass  the  value  15  up  the 
tree  to  the  node  for  X,  where  T.val  =  15. 

• 

5.1.3  Exercises  for  Section  5.1 

E x e r c i se  5 . 1 . 1:  For  t he  SDD  of  Fig.  5.1,  give  annotated  parse  trees  for  the 
following  expressions: 

a) 

(3  +  4 ) * (5  +  6) n. 

310 

CHAPTER  5. 

SYNTAX-DIRECTED  TRANSLATION 

b)  1 * 2 * 3 * (4 + 5) n. 

c)  (9 + 8*  (7 + 6 )+ 5)  * 4n. 

E x e r c i se  5 . 1 . 2:  Extend  the  SDD  of  Fig.  5.4  to  handle  expressions  as  in 
Fig.  5.1. 

E x e r c i se  5 . 1 . 3:  Repeat  Exercise  5.1.1,  using  your  SDD  from  Exercise  5.1.2. 

5.2  Evaluation  Orders  for  SDD's 

"Dependency  graphs"  are  a  useful  tool  for  determining  an  evaluation  order  for 
the  attribute  instances  in  a  given  parse  tree.  While  an  annotated  parse  tree 
shows  the  values  of  attributes,  a  dependency  graph  helps  us  determine  how 
those  values  can  be  computed. 

In  this  section,  in  addition  to  dependency  graphs,  we  define  two  impor 
tant  classes  of  SDD's:  the  "S-attributed"  and  the  more  general  "L-attributed" 
SDD's.  The  translations  specified  by  these  two  classes  fit  well  with  t he  parsing 
methods  we  have  studied,  and  most  translations  encountered  in  practice  can  be 
written  to  conform  to  the  requirements  of  at  least  one  of  these  classes. 

5.2.1  Dependency  Graphs 

A  dependency  graph  depicts  t he  flow  of  information  among  the  a t t r i b u te  in 
stances  in  a  particular  parse  tree;  an  edge  from  one  a t t r i b u te  instance  to  an 
other  means  t h at  t he  value  of  the  first  is  needed  to  compute  t he  second.  Edges 
express  constraints  implied  by  the  semantic  rules.  In  more  detail: 

•  For  each  parse-tree  node,  say  a  node  labeled  by  grammar  symbol  X,  t he 

dependency  graph  has  a  node  for  each  a t t r i b u te  associated  with  X. 

•  Suppose  t h at  a  semantic  rule  associated  with  a  production  p  defines  the 
value  of  synthesized  a t t r i b u te  A.b  in  terms  of  t he  value  of  X.c  (the  rule 
may  define  A.b  in  terms  of  other  attributes  in  addition  to  X.c).  Then, 
the  dependency  graph  has  an  edge  from  X.c  to  A.b.  More  precisely,  at 
every  node  N  labeled  A  where  production  p  is  applied,  create  an  edge  to 
attribute  b  at  N,  from  the  a t t r i b u te  c  at  t he  child  of  N  corresponding  to 
this  instance  of  the  symbol  X  in  the  body  of  the  production.2 

•  Suppose  t h at  a  semantic  rule  associated  with  a  production  p  defines  the 
value  of  inherited  a t t r i b u te  B.c  in  terms  of  the  value  of  X.a.  Then,  t he 
dependency  graph  has  an  edge  from  X.a  to  B.c.  For  each  node  N  labeled 
B  t h at  corresponds  to  an  occurrence  of  this  B  in  t he  body  of  production 
p,  create  an  edge  to  attribute  c  at  N  from  the  a t t r i b u te  a  at  t he  node  M 

2  Since  a  node  N  can  have  several  children  labeled  X,  we  again  assume  that  subscripts 

distinguish  among  uses  of the  same  symbol  at  different  places  in  the  production. 

5.2. 

EVALUATION  ORDERS  FOR  SDD'S 

311 

t h at  corresponds  to  this  occurrence  of  X.  Note  t h at  M  could  be  either 
the  parent  or  a  sibling  of  N. 

E x a m p le  5 . 4:  Consider  the  following  production  and  rule: 

PR O D U C T I ON 

SE M A N T IC 

RU LE 

E  ->  Ei  +  T 

E.val 

-  Ei.val  +  T.val 

At  every  node  N  labeled  E,  with  children  corresponding  to  t he  b o dy  of  this 
production,  the  synthesized  a t t r i b u te  val  at  N  is  computed  using  the  values  of 
val  at  the  two  children,  labeled  E  and  T.  Thus,  a  portion  of  the  dependency 
graph  for  every  parse  tree  in  which  this  production  is  used  looks  like  Fig.  5.6. 
As  a  convention,  we  shall  show  the  parse  tree  edges  as  dotted  lines,  while  the 
edges  of  the  dependency  graph  are  solid. 

• 

E 

val 

Ei 

val 

+ 

T 

val 

Figure  5.6:  E.val  is  synthesized  from  Ei.val  and  Ei.val 

E x a m p le  5 . 5:  An  example  of  a  complete  dependency  graph  appears  in  Fig. 
5.7.  The  nodes  of the  dependency  graph,  represented  by  the  numbers  1  through 
9,  correspond  to  the  attributes  in  the  annotated  parse  tree  in  Fig.  5.5. 

T  9  val 

digit  2  lexval 

Figure  5.7:  Dependency  graph  for  the  annotated  parse  tree  of  Fig.  5.5 

Nodes  1  and  2  represent  the  a t t r i b u te  lexval  associated  with  the  two  leaves 
labeled  d i g i t.  Nodes  3  and  4  represent  the  a t t r i b u te  val  associated  with  the 
two  nodes  labeled  F.  T he  edges  to  node  3  from  1  and  to  node  4  from  2  result 

312 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

from  the  semantic  rule  t h at  defines  F.val  in  terms  of  digit.lexval 
equals  d i g it .lexval,  but  the  edge  represents  dependence,  not  equality. 

In  fact,  F.val 

Nodes  5  and  6  represent  t he  inherited  a t t r i b u te  T'.inh  associated  with  each 
of  the  occurrences  of  nonterminal  T'.  T he  edge  to  5  from  3  is  due  to  t he  rule 
T'.inh  =  F.val,  which  defines  T'.inh  at  the  right  child  of  the  root  from  F.val 
at  the  left  child.  We  see  edges  to  6  from  node  5  for  T'.inh  and  from  node  4 
for  F.val,  because  these  values  are  multiplied  to  evaluate  the  a t t r i b u te  inh  at 
node  6. 

Nodes  7  and  8  represent  the  synthesized  a t t r i b u te  syn  associated  with  the 
occurrences  of  X".  T he  edge  to  node  7  from  6  is  due  to  the  semantic  rule 
T'.syn  =  T'.inh  associated  with  production  3  in  Fig.  5.4.  T he  edge  to  node  8 
from  7  is  due  to  a  semantic  rule  associated  with  production  2. 

Finally,  node  9  represents  t he  attribute  T.val.  The  edge  to  9  from  8  is  due 

to  the  semantic  rule,  T.val  =  T'.syn,  associated  with  production  1. 

• 

5.2.2  Ordering  the  Evaluation  of  Attributes 

The  dependency  graph  characterizes  the  possible  orders  in  which  we  can  evalu 
ate  the  attributes  at  the  various  nodes  of  a  parse  tree.  If the  dependency  graph 
has  an  edge  from  node  M  to  node  N,  then  the  a t t r i b u te  corresponding  to  M 
must  be  evaluated  before  the  a t t r i b u te  of  N.  Thus,  the  only  allowable  orders 
of  evaluation  are  those  sequences  of  nodes  N\,  N2,... 
,Nk  such  t h at  if  there  is 
an  edge  of  the  dependency  graph  from  Ni  to  Nj,  then  i  <  j.  Such  an  ordering 
embeds  a  directed  graph  into  a  linear  order,  and  is  called  a  topological  sort  of 
the  graph. 

If there  is  any  cycle  in  the  graph,  then  there  are  no  topological  sorts;  t h at  is, 
there  is  no  way  to  evaluate  the  SDD  on  this  parse  tree.  If  there  are  no  cycles, 
however,  then  there  is  always  at  least  one  topological  sort.  To  see  why,  since 
there  are  no  cycles,  we  can  surely  find  a  node  with  no  edge  entering.  For  if there 
were  no  such  node,  we  could  proceed  from  predecessor  to  predecessor  until  we 
came  back  to  some  node  we  had  already  seen,  yielding  a  cycle.  Make  this  node 
the  first  in  the  topological  order,  remove  it  from  the  dependency  graph,  and 
repeat  the  process  on  the  remaining  nodes. 

E x a m p le  5 . 6:  The  dependency  graph  of  Fig.  5.7  has  no  cycles.  One  topologi 
cal  sort  is  the  order  in  which  t he  nodes  have  already  been  numbered:  1 , 2 , . ..  , 9. 
Notice  t h at  every edge  of the  graph  goes  from  a  node  to  a  higher-numbered  node, 
so  this  order  is  surely  a  topological  sort.  There  are  other  topological  sorts  as 
well,  such  as  1 , 3 , 5 , 2 , 4 , 6 , 7 , 8 , 9. 

• 

5.2.3  S-Attributed  Definitions 

As  mentioned  earlier,  given  an  SDD,  it  is  very  hard  to  tell  whether  there  exist 
any  parse  trees  whose  dependency  graphs  have  cycles.  In  practice,  translations 
can  be  implemented  using  classes  of  SDD's  t h at  guarantee  an  evaluation  order, 

5.2. 

EVALUATION  ORDERS  FOR  SDD'S 

313 

since  they  do  not  permit  dependency  graphs  with  cycles.  Moreover,  the  two 
classes  introduced  in  this  section  can  be  implemented  efficiently  in  connection 
with  top-down  or  b o t t o m - up  parsing. 

T he  first  class  is  defined  as  follows: 

•  An  SDD  is  S-attributed  if  every  a t t r i b u te  is  synthesized. 

E x a m p le  5 . 7:  T he  SDD  of Fig.  5.1  is  an  example  of an  S-attributed  definition. 
Each  attribute,  L.val,  E.val,  T.val,  and  F.val  is  synthesized. 

• 

W h en  an  SDD  is  S-attributed,  we  can  evaluate  its  attributes  in  any  bottom-
up  order  of t he  nodes  of the  parse  tree.  It  is  often  especially  simple  to  evaluate 
the  attributes  by  performing  a  postorder  traversal  of  t he  parse  tree  and  evalu 
ating  the  attributes  at  a  node  N  when  the  traversal  leaves  N  for  t he  last  time. 
T h at  is,  we  apply  t he  function  postorder,  defined  below,  to  the  root  of  the  parse 
tree  (see  also  the  box  "Preorder  and  Postorder  Traversals"  in  Section  2.3.4): 

postorder(N) 

{ 

for  (  each  child  C  of  N,  from  the  left  )  postorder(C); 
evaluate  the  attributes  associated  with  node  N; 

} 

S-attributed  definitions  can  be  implemented  during  bottom-up  parsing,  since 
a  b o t t o m - up  parse  corresponds  to  a  postorder  traversal.  Specifically,  postorder 
corresponds  exactly  to  the  order  in  which  an  LR  parser  reduces  a  production 
body  to  its  head.  This  fact  will  be  used  in  Section  5.4.2  to  evaluate  synthesized 
attributes  and  store  t h em  on  the  stack  during  LR  parsing,  without  creating  the 
tree  nodes  explicitly. 

5.2.4  L-Attributed  Definitions 

The  second  class  of  SDD's  is  called  L-attributed  definitions.  T he  idea  behind 
this  class  is  t h a t,  between  the  attributes  associated  with  a  production  body, 
dependency-graph  edges  can  go  from  left  to  right,  but  not  from  right  to  left 
(hence  "L-attributed").  More  precisely,  each  a t t r i b u te  must  be  either 

1.  Synthesized,  or 

2.  Inherited,  but  with  the  rules  limited  as  follows.  Suppose  t h at  there  is 
a  production  A  ->•  XXX2  •  •  •  Xn,  and  t h at  there  is  an  inherited  a t t r i b u te 
Xi.a  computed  by  a  rule  associated  with  this  production.  Then  the  rule 
may  use  only: 

(a)  Inherited  attributes  associated  with  the  head  A. 

(b)  Either  inherited  or  synthesized  attributes  associated  with  the  occur 
,  X^ 

rences  of  symbols  X±,X2,... 

left  of  X{. 

located 

the 

to 

314 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

(c)  Inherited  or  synthesized  attributes  associated  with  this  occurrence 
of  Xi  itself,  but  only  in  such  a  way  t h at  there  are  no  cycles  in  a 
dependency  graph  formed  by  the  attributes  of  this  X j. 

E x a m p le  5 . 8:  The  SDD  in  Fig.  5.4  is  L-attributed.  To  see  why,  consider  the 
semantic  rules  for  inherited  attributes,  which  are  repeated  here  for  convenience: 

PR O D U C T I ON 
FT' 
T 
T'  ->*F  T[ 

SE M A N T IC  RU LE 
T'.inh  =  F.val 
T[. inh  -  T'. inh  x  F. val 

The  first  of these  rules  defines  t he  inherited  a t t r i b u te  T'.inh  using  only  F.val, 
and  F  appears  to  the  left  of T'  in  t he  production  body,  as  required.  T he  second 
rule  defines  T[.inh  using  t he  inherited  a t t r i b u te  T'.inh  associated  with  the  head, 
and  F.val,  where  F  appears  to  t he  left  of  T[  in  t he  production  body. 

In  each  of  these  cases,  the  rules  use  information  "from  above  or  from  t he 
left,"  as  required  by  the  class.  T he remaining  attributes  are  synthesized.  Hence, 
the  SDD  is  L-attributed. 

• 

E x a m p le  5 . 9:  Any  SDD  containing  the  following  production  and  rules  cannot 
be  L-attributed: 

PR O D U C T I ON 
A  ->  B  C 

SE M A N T IC  RU L ES 
A.s  =  B.b; 
B.i  = 

f(C.c,A.s) 

The  first  rule,  A.s  =  B.b,  is  a  legitimate  rule  in  either  an  S-attributed  or  L-
attributed  SDD.  It  defines  a  synthesized  a t t r i b u te  A.s  in  terms  of  an  a t t r i b u te 
at  a  child  (that  is,  a  symbol  within  the  production  body). 

The  second  rule  defines  an  inherited  a t t r i b u te  B.i,  so  the  entire  SDD  cannot 
be  S-attributed.  Further,  although  the  rule  is  legal,  the  SDD  cannot  be  L-
attributed,  because  the  a t t r i b u te  C.c  is  used  to  help  define  B.i,  and  C  is  to 
the  right  of  B  in  the  production  body.  While  attributes  at  siblings  in  a  parse 
tree  may  be  used  in  L-attributed  SDD's,  they  must  be  to  the  left  of the  symbol 
whose  a t t r i b u te  is  being  defined. 

• 

5.2.5 

Semantic  Rules  with  Controlled  Side  Effects 

In  practice,  translations  involve  side  effects:  a  desk  calculator  might  print  a 
result;  a  code  generator  might  enter  the  type  of an  identifier  into  a  symbol  table. 
W i th  SDD's,  we  strike  a  balance  between  a t t r i b u te  grammars  and  translation 
schemes.  Attribute  grammars  have  no  side  effects  and  allow  any  evaluation 
order  consistent  with  the  dependency  graph.  Translation  schemes  impose  left-
to-right  evaluation  and  allow  semantic  actions  to  contain  any  program  fragment; 
translation  schemes  are  discussed  in  Section  5.4. 

We  shall  control  side  effects  in  SDD's  in  one  of  the  following  ways: 

5.2.  EVALUATION  ORDERS  FOR  SDD'S 

3 15 

•  Permit  incidental  side  effects  t h at  do  not  constrain  a t t r i b u te  evaluation. 
In  other  words,  permit  side  effects  when  a t t r i b u te  evaluation  based  on  any 
topological  sort  of the  dependency  graph  produces  a  "correct"  translation, 
where  "correct"  depends  on  the  application. 

•  Constrain  the  allowable  evaluation  orders,  so  t h at  the  same  translation  is 
produced  for  any  allowable  order.  T he  constraints  can  be  thought  of  as 
implicit  edges  added  to  the  dependency  graph. 

As  an  example  of  an  incidental  side  effect,  let  us  modify  t he  desk  calculator 
of  Example  5 .1  to  print  a  result.  Instead  of  the  rule  L.val  =  E.val,  which  saves 
the  result  in  t he  synthesized  attribute  L.val,  consider: 

PR O D U C T I ON 
L 

E  n 

1) 

SE M A N T IC  RU LE 

print(E.val) 

Semantic  rules  t h at  are  executed  for  their  side  effects,  such  as  print(E.val),  will 
be  treated  as  the  definitions  of  dummy  synthesized  attributes  associated  with 
the  head  of  t he  production.  T he  modified  SDD  produces  t he  same  translation 
under  any  topological  sort,  since  the  print  statement  is  executed  at  the  end, 
after  the  result  is  computed  into  E.val. 

E x a m p le  5. 1 0:  The  SDD  in  Fig.  5 .8  takes  a  simple  declaration  D  consisting 
of  a  basic  type  T  followed  by  a  list  L  of  identifiers.  T  can  be  i nt  or  float.  For 
each  identifier  on  t he  list,  the  type  is  entered  into  the  symbol-table  entry  for  the 
identifier.  We  assume  t h at  entering  the  type  for  one  identifier  does  not  affect 
the  symbol-table  entry  for  any  other  identifier.  Thus,  entries  can  be  u p d a t ed 
in  any  order.  This  SDD  does  not  check  whether  an  identifier  is  declared  more 
t h an  once;  it  can  be  modified  to  do  so. 

PR O D U C T I ON 

SE M A N T IC 

RU L ES 

1)  D^TL 

T  ->  i nt 

T  ->  float 
L  ->• Li  ,  id 

2) 

3) 

4) 

5) 

L.inh  =  T.type 

T.type =  integer 

T.type  =  float 
L\.inh  =  L.inh 
addType(id.  entry,  L.inh) 

L - Md 

addTypeiid.  entry,  L.inh) 

Figure  5 . 8:  Syntax-directed  definition  for  simple  type  declarations 

Nonterminal  D  represents  a  declaration,  which,  from  production  1,  consists 
of  a  type  T  followed  by  a  list  L  of  identifiers.  T  has  one  attribute,  T.type,  which 
is  t he  type  in  t he  declaration  D.  Nonterminal  L  also  has  one  attribute,  which 
we  call  ink  to  emphasize  t h at  it  is  an  inherited  attribute.  The  purpose  of  L.inh 

316 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

is  to  pass  the  declared  type  down  the  list  of identifiers,  so  t h at  it  can  be  added 
to  the  appropriate  symbol-table  entries. 

Productions  2  and  3  each  evaluate  the  synthesized  a t t r i b u te  T.type,  giving 

it  the  appropriate  value,  integer  or  float.  This  type  is  passed  to  t he  a t t r i b u te 
L.inh  in  the  rule  for  production  1.  Production  4  passes  L.inh  down  the  parse 
tree.  T h at  is,  t he  value  L\.inh  is  computed  at  a  parse-tree  node  by  copying  the 
value  of  L.inh  from  the  parent  of  t h at  node;  t he  parent  corresponds  to  the  head 
of  the  production. 

Productions  4  and  5  also  have  a  rule  in  which  a  function  addType  is  called 

with  two  arguments: 

1.  id.entry,  a  lexical  value  t h at  points  to  a  symbol-table  object,  and 

2.  L.inh,  the  type  being  assigned  to  every  identifier  on  the  list. 

We  suppose  t h at  function  addType  properly  installs  the  type  L.inh  as  t he  type 
of  the  represented  identifier. 

A  dependency  graph  for  the  input  string  float  idi  ,  i d2,  i d3  appears  in 
Fig.  5.9.  Numbers  1  through  10  represent  the  nodes  of  the  dependency  graph. 
Nodes  1,  2,  and  3  represent  the  a t t r i b u te  entry  associated  with  each  of  the 
leaves  labeled  id.  Nodes  6,  8,  and  10  are  the  d u m my  attributes  t h at  represent 
t he  application  of  the  function  addType  to  a  type  and  one  of  these  entry  values. 

D 

T 

REAL 

inh 

7 

L 

8 

entry 

entry 

id  2  2  entry 

inh  9 

L  10  entry 

entry 

Figure  5.9:  Dependency  graph  for  a  declaration  float  i d i,  i d2  ,  i d3 

Node  4  represents  t he  a t t r i b u te  T.type,  and  is  actually  where  a t t r i b u te  eval 
uation  begins.  This  type  is  then  passed  to  nodes  5,  7,  and  9  representing  L.inh 
associated  with  each  of  the  occurrences  of  the  nonterminal  L. 

• 

5.2. 

EVALUATION  ORDERS  FOR  SDD'S 

317 

5.2.6  Exercises  for  Section  5.2 

E x e r c i se  5 . 2 . 1:  W h at  are  all  the  topological  sorts  for  t he  dependency  graph 
of  Fig.  5.7? 

E x e r c i se  5 . 2 . 2:  For  t he  SDD  of  Fig.  5.8,  give  annotated  parse  trees  for  t he 
following  expressions: 

a)  i nt  a,  b,  c. 

b)  f l o at  w,  x,  y,  z. 

E x e r c i se  5 . 2 . 3:  Suppose  t h at  we  have  a  production  A  ->  BCD.  Each  of 
the  four  nonterminals  A,  B,  C,  and  D  have  two  attributes:  s  is  a  synthesized 
attribute,  and  i  is  an  inherited  attribute.  For  each  of  the  sets  of  rules  below, 
tell  whether  (i)  t he  rules  are  consistent  with  an  S-attributed  definition  (ii)  the 
rules  are  consistent  with  an  L-attributed  definition,  and  (in)  whether  t he  rules 
are  consistent  with  any  evaluation  order  at  all? 

a)  A.s  -  B.i  +  C.s. 

b)  A.s  =  B.i  +  C.s  and  D.i  =  A.i  +  B.s. 

c)  A.s  -  B.s  +  D.s. 

!  d)  A.s  =  D.i,  B.i  =  A.s  +  C.s,  C.i  =  B.s,  and  D.i  =  B.i  +  C.i. 

!  E x e r c i se  5 . 2 . 4:  This  grammar  generates  binary  numbers  with  a  "decimal" 

point: 

S-*  L  .  L  |  L 
L-+LB\B 
B  ->  0  |  1 

Design  an  L-attributed  SDD  to  compute  S.val,  t he  decimal-number  value  of 
an  input  string.  For  example,  t he  translation  of  string  1 0 1 . 1 01  should  be  t he 
decimal  number  5.625.  Hint:  use  an  inherited  a t t r i b u te  L.side  t h at  tells  which 
side  of  t he  decimal  point  a  bit  is  on. 

!!  E x e r c i se  5 . 2 . 5:  Design  an  S-attributed  SDD  for  the  g r a m m ar  and  translation 

described  in  Exercise  5.2.4. 

!!  E x e r c i se  5 . 2 . 6:  Implement  Algorithm  3.23,  which  converts  a  regular  expres 
sion  into  a  nondeterministic  finite  automaton,  by  an  L-attributed  SDD  on  a 
top-down  parsable  grammar.  Assume  t h at  there  is  a  token  char  representing 
any  character,  and  t h at  char.lexval  is  the  character  it  represents.  You  may  also 
assume  t he  existence  of  a  function  new()  t h at  returns  a  new  state,  t h at  is,  a 
state  never  before  returned  by  this  function.  Use  any  convenient  notation  to 
specify  the  transitions  of  the  NFA. 

318 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

5.3  Applications of Syntax-Directed Translation 

The  syntax-directed  translation  techniques  in  this  chapter  will  be  applied  in 
Chapter  6  to  type  checking  and  intermediate-code  generation.  Here,  we  consider 
selected  examples  to  illustrate  some  representative  SDD's. 

The  main  application  in  this  section  is  t he  construction  of syntax trees.  Since 
some  compilers  use  syntax  trees  as  an  intermediate  representation,  a  common 
form  of  SDD  turns  its  input  string  into  a  tree.  To  complete  t he  translation  to 
intermediate  code,  the  compiler  may  then  walk  t he  syntax  tree,  using  another 
set  of  rules  t h at  are  in  effect  an  SDD  on  the  syntax  tree  r a t h er  t h an  t he  parse 
tree.  (Chapter  6  also  discusses  approaches  to  intermediate-code  generation  t h at 
apply  an  SDD  without  ever  constructing  a  tree  explicitly.) 

We  consider  two  SDD's  for  constructing  syntax  trees  for  expressions.  T he 
first,  an  S-attributed  definition,  is  suitable  for  use  during  b o t t o m - up  parsing. 
The  second,  L-attributed,  is  suitable  for  use  during  top-down  parsing. 

The  final  example  of  this  section  is  an  L-attributed  definition  t h at  deals 

with  basic  and  array  types. 

5.3.1  Construction  of Syntax  Trees 

As  discussed  in  Section  2.8.2,  each  node  in  a  syntax  tree  represents  a  construct; 
the  children  of the  node  represent  the  meaningful  components  of t he  construct. 
A  syntax-tree  node  representing  an  expression  E\  +  E2  has  label  +  and  two 
children  representing  t he  subexpressions  E\  and  E2 • 

We  shall  implement  the  nodes  of  a  syntax  tree  by  objects  with  a  suitable 
number  of  fields.  Each  object  will  have  an  op  field  t h at  is  t he  label  of the  node. 
T he  objects  will  have  additional  fields  as  follows: 

•  If the  node  is  a  leaf,  an  additional  field  holds  the  lexical  value  for  t he  leaf. 
A  constructor  function  Leaf (op,  val)  creates  a  leaf object.  Alternatively,  if 
nodes  are  viewed  as  records,  then  Leaf  returns  a  pointer  to  a  new  record 
for  a  leaf. 

•  If  t he  node  is  an  interior  node,  there  are  as  many  additional  fields  as  the 
node  has  children  in  the  syntax  tree.  A  constructor  function  Node  takes 
two  or  more  arguments:  Node(op,ci,c2,... 
,ck)  creates  an  object  with 
first  field  op  and  k  additional  fields  for  t he  k  children  c\,...  , 

. 

E x a m p le  5 . 1 1:  The  S-attributed  definition  in  Fig.  5.10  constructs  syntax 
trees  for  a  simple  expression  grammar  involving  only  the  binary  operators  + 
and  -.  As  usual,  these  operators  are  at  the  same  precedence  level  and  are 
jointly  left  associative.  All  nonterminals  have  one  synthesized  a t t r i b u te  node, 
which  represents  a  node  of  the  syntax  tree. 

Every  time  t he  first  production  E 

E\  +  T  is  used,  its  rule  creates  a  node 
with  ' +'  for  op  and  two  children,  Ei.node  and  T.node,  for  t he  subexpressions. 
The  second  production  has  a  similar  rule. 

5.3. 

APPLICATIONS  OF 

SYNTAX-DIRECTED 

TRANSLATION 

319 

PR O D U C T I ON 

SE M A N T IC 

RU L ES 

E  ->•  Ei  +  T 

E 

E\—T 

E.node  = 

n ew 

Node(''+',E\.node,T.node) 

E.node  = 

n ew 

Node('-'\E\.node,T.node) 

E->T 

T->{E) 

T- Md 

E.node  =  T.node 

T.node  =  E.node 

T.node  —  n ew  Leaf (id,  id.  entry) 

T —> n um 

T.node  =  n ew  £ e a/ ( n u m , n u m. r o l) 

1) 

2) 

3) 

4) 

5) 

6) 

Figure  5 . 1 0:  Constructing  syntax  trees  for  simple  expressions 

For  production  3,  E  ->  T,  no  node  is  created,  since  E.node  is  t he  same  as 

T.node.  Similarly,  no  node  is  created  for  production  4,  T 
of  T.node  is  t he  same  as  E.node,  since  parentheses  are  used  only  for  grouping; 
they  influence  t he  structure  of t he  parse  tree  and  t he  syntax  tree,  but  once  their 
job  is  done,  there  is  no  further  need  to  retain  them  in  the  syntax  tree. 

(E).  T he  value 

T he  last  two  T-productions  have  a  single  terminal  on  the  right.  We  use  the 
constructor  Leaf to  create  a  suitable  node,  which  becomes  the  value  of  T.node. 
Figure  5 . 11  shows  t he  construction  of  a  syntax  tree  for  t he  input  a  —  4 +  c. 
T he  nodes  of  t he  syntax  tree  are  shown  as  records,  with  t he  op  field  first. 
Syntax-tree  edges  are  now  shown  as  solid  lines.  T he  underlying  parse  tree, 
which  need  not  actually  be  constructed,  is  shown  with  dotted  edges.  T he  third 
t y pe  of  line,  shown  dashed,  represents  t he  values  of  E.node  and  T-node;  each 
line  points  to  t he  appropriate  syntax-tree  node. 

At  t he  b o t t om  we  see  leaves  for  a,  4  and  c,  constructed  by  Leaf.  We  suppose 
t h at  t he  lexical  value  id. entry  points  into  the  symbol  table,  and  the  lexical 
value  uum.ual  is  t he  numerical  value  of  a  constant.  These  leaves,  or  pointers 
to  them,  become  t he  value  of  T.node  at  the  three  parse-tree  nodes  labeled  T, 
according  to  rules  5  and  6.  Note  t h at  by  rule  3,  the  pointer  to  the  leaf  for  a  is 
also  the  value  of  E.node  for  t he  leftmost  E  in  the  parse  tree. 

Rule  2  causes  us  to  create  a  node  with  op  equal  to  the  minus  sign  and 
pointers  to  t he  first  two  leaves.  Then,  rule  1  produces  the  root  node  of  the 
syntax  tree  by  combining  t he  node  for  —  with  the  third  leaf. 

If  t he  rules  are  evaluated  during  a  postorder  traversal  of  the  parse  tree,  or 
with  reductions  during  a  bpttom-up  parse,  then  the  sequence  of  steps  shown  in 
• 
Fig.  5 . 12  ends  with  p5  pointing  to  t he  root  of  t he  constructed  syntax  tree. 

W i th  a  g r a m m ar  designed  for  top-down  parsing,  t he  same  syntax  trees  are 
constructed,  using  the  same  sequence  of  steps,  even  though  t he  structure  of t he 
parse  trees  differs  significantly  from  t h at  of  syntax  trees. 

E x a m p le  5 . 1 2:  The  L-attributed  definition  in  Fig.  5 . 13  performs  the  same 
translation  as  t he  S-attributed  definition  in  Fig.  5 . 1 0.  The  attributes  for  t he 
g r a m m ar  symbols  E,  T,  id,  and  n um  are  as  discussed  in  Example  5 . 1 1. 

320 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

id  : 

to  entry  for  c 

id  : 

n u m;  4 

to  entry  for  a 

Figure  5.11:  Syntax  tree  for  a  —  4 +  c 

1) 

pi  =  n ew  Lea/(id,  entry-a); 

2)  P2  =  n ew  Leaf ( n u m, 4); 
3)  P3  =  n ew  Node('-',p1,p2); 
4)  P4  =  n ew  Leaf'(id,  entry-c); 
=  n ew  Node('+',p3,p4); 
5) 

p5 

Figure  5.12:  Steps  in  the  construction  of the  syntax  tree  for  a  —  4  +  c 

T he  rules  for  building  syntax  trees  in  this  example  are  similar  to  t he  rules 
for  t he  desk  calculator  in  Example  5.3.  In  the  desk-calculator  example,  a  t e rm 
x  *  y  was  evaluated  by  passing  x  as  an  inherited  attribute,  since  x  and  *  y 
appeared  in  different  portions  of  the  parse  tree.  Here,  the  idea  is  to  build  a 
syntax  tree  for  x  +  y  by  passing  x  as  an  inherited  attribute,  since  x  and  +  y 
appear  in  different  subtrees.  Nonterminal  E'  is  the  counterpart  of  nonterminal 
T"  in  Example  5.3.  Compare  the  dependency  graph  for  a  —  4  +  c  in  Fig.  5.14 
with  t h at  for  3  *  5  in  Fig.  5.7. 

Nonterminal  E'  has  an  inherited  a t t r i b u te  iinh  and  a  synthesized  a t t r i b u te 
syn.  Attribute  E'.inh  represents  t he  partial  syntax  tree  constructed  so  far. 
Specifically,  it  represents  t he  root  of  the  tree  for  t he  prefix  of  t he  input  string 
t h at  is  to  the  left  of  t he  subtree  for  E'.  At  node  5  in  t he  dependency  graph  in 
Fig.  5.14,  E'.inh  denotes  t he  root  of  t he  partial  syntax  tree  for  t he  identifier  a; 
t h at  is,  the  leaf for  a.  At  node  6,  E'.inh  denotes  the  root  for  t he  partial  syntax 

5.3. 

APPLICATIONS  OF 

SYNTAX-DIRECTED 

TRANSLATION 

3 21 

PR O D U C T I ON 

SE M A N T IC 

RU L ES 

E-*T 

E' 

E.node  =  E'  .syn 

E''.inh  =  T.node 

E'->+TE[ 

E[.inh  =  n ew  Node('+',  E'  .inh,T.node) 

E'  .syn  =  E[.syn 

E' 

->-TE[ 

E[.inh 

= 

n ew 

Node('-',E'.inh,T.node) 

E'  -t  e 

T->(E) 

T- > id 

E'  .syn  =  E[.syn 

E'.syn  =  E'.inh 

T.node  =  E.node 

T.node  =  n ew  Leaf (id,  id.  entry) 

T  -»•  n um 

T.node  =  n ew 

jLea/(num,  num.val) 

1) 

2) 

3) 

4) 

5) 

6) 

7) 

Figure  5 . 1 3:  Constructing  syntax  trees  during  top-down  parsing 

E  13  node 

Figure  5 . 1 4:  Dependency  graph  for  a  -  4 +  c,  with  t he  SDD  of  Fig.  5 . 13 

id 

7  entry 

e 

tree  for  the  input  a  — 4.  At  node  9,  E'.inh  denotes  t he  syntax  tree  for  a  — 4 + c. 
Since  there  is  no  more  input,  at  node  9,  E'.inh  points  to  t he  root  of  t he 
entire  syntax  tree.  T he  syn  attributes  pass  this  value  back  up  the  parse  tree 
until  it  becomes  the  value  of E.node.  Specifically,  the  a t t r i b u te  value  at  node  10 
is  defined  by  t he  rule  E'.syn  =  E'.inh  associated  with  t he  production  E'  —>  e. 
T he  a t t r i b u te  value  at  node  11  is  defined  by  t he  rule  E'.syn  =  E[  .syn  associated 
with  production  2  in  Fig.  5 . 1 3.  Similar  rules  define  t he  a t t r i b u te  values  at 
nodes  12  and  1 3. 

• 

1 

5.3.2  The  Structure  of  a  Type 

Inherited  attributes  are  useful  when  the  structure  of  the  parse  tree  differs  from 
t he  abstract  syntax  of  the  input;  attributes  can  then  be  used  to  carry  informa-

322 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

tion  from  one  p a rt  of  the  parse  tree  to  another.  The  next  example  shows  how 
a  mismatch  in  structure  can  be  due  to  the  design  of  the  language,  and  not  due 
to  constraints  imposed  by  the  parsing  method. 

E x a m p le  5 . 1 3:  In  C,  t he  t y pe  int  [2][3]  can  be  read  as,  "array  of  2  arrays 
of  3  integers."  T he  corresponding  type  expression  array(2,  array(3,  integer))  is 
represented  by  t he  tree  in  Fig.  5.15.  T he  operator  array  takes  two  parameters, 
a  number  and  a  type. 
If  types  are  represented  by  trees,  then  this  operator 
returns  a  tree  node  labeled  array  with  two  children  for  a  number  and  a  type. 

3 

integer 

Figure  5.15:  Type  expression  for  int[2][3] 

W i th  the  SDD  in  Fig.  5.16,  nonterminal  T  generates  either  a  basic  type  or 
an  array  type.  Nonterminal  B  generates  one  of  t he  basic  types  int  and  float. 
T  generates  a  basic  type  when  T  derives  B C  and  C  derives  e.  Otherwise,  C 
generates  array  components  consisting  of  a  sequence  of  integers,  each  integer 
surrounded  by  brackets. 

P R O D U C T I ON 

SE M A N T IC  R U L ES 

T 

->  B  C 

B  -»• 

int 

B 
-»•  float 
C  -¥  [  n um  ]  Ci 

C  -+  e 

T.t  =  C.t 
C.b  =  B.t 

B.t  = 

integer 

B.t  = 

float 

C.t  = 

array(num.val, 

C\.t) 

Cx.b  =  C.b 
C.t  =  C.b 

Figure  5.16:  T  generates  either  a  basic  type  or  an  array  t y pe 

T he  nonterminals  B  and  T  have  a  synthesized  a t t r i b u te  t  representing  a 
type.  T he  nonterminal  C  has  two  attributes:  an  inherited  a t t r i b u te  b  and  a 
synthesized  a t t r i b u te  t.  T he  inherited  b  attributes  pass  a  basic  type  down  t he 
tree,  and  t he  synthesized  t  attributes  accumulate  t he  result. 

An  annotated parse tree for  the  input  string  int [ 2 ]  [ 3 ]  is  shown  in  Fig.  5.17. 
T he  corresponding  type  expression  in  Fig.  5.15  is  constructed  by  passing  t he 
type  integer  from  B,  down  t he  chain  of  C's  through  the  inherited  attributes  b. 
T he  array  type  is  synthesized  up  t he  chain  of  C's  through  t he  attributes  t. 

In  more  detail,  at  t he  root  for  T  -»  B  C,  nonterminal  C  inherits  t he  type 
from  B,  using  t he  inherited  a t t r i b u te  C.b.  At  t he  rightmost  node  for  C,  t he 

5.3. 

APPLICATIONS  OF 

SYNTAX-DIRECTED 

TRANSLATION 

323 

e,  so  C.t  equals  C.6.  T he  semantic  rules  for  the  production 
[  n um  ]  C\  form  C.t  by  applying  the  operator  array  to  the  operands 

production  is  C 
C 
n u m. u a/  and  C\.t. 

• 

T.t  =  array(2,  array(3,  integer)) 

B.t  = 

integer 

integer 

C.b  = 
C.t  —  array(2,  array(3,  integer)) 

C.b  = 
integer 
C.t  =  array(3,  integer) 

C.b  = 
C.t  = 

integer 
integer 

e 

Figure  5.17:  Syntax-directed  translation  of  array  types 

5.3.3  Exercises  for  Section  5.3 

E x e r c i se  5 . 3 . 1:  Below  is  a  g r a m m ar  for  expressions  involving  operator  4-  and 
integer  or  floating-point  operands.  Floating-point  numbers  are  distinguished 
by  having  a  decimal  point. 

E-+E  +  T  |  T 
T  —»  n um  .  n um  |  n um 

a)  Give  an  SDD  to  determine  the  type  of  each  term  T  and  expression  E. 

b)  Extend  your  SDD  of  (a)  to  translate  expressions  into  postfix  notation. 
Use  the  unary  operator  i n t T o F l o at  to  t u rn  an  integer  into  an  equivalent 
float. 

!  E x e r c i se  5.3.2  :  Give  an  SDD  to  translate  infix  expressions  with  +  and  *  into 
equivalent  expressions  without  redundant  parentheses.  For  example,  since  b o th 
operators associate  from t he  left,  and  *  takes  precedence over  +,  ((a*(6+c))*(<i)) 
translates  into  a *  (b +  c)  *  d. 

!  E x e r c i se  5 . 3 . 3:  Give  an  SDD  to  differentiate  expressions  such  as  x  *  (3  *  x  + 
x  *  x)  involving  t he  operators  +  and  *,  the  variable  x,  a nd  constants.  Assume 
t h at  no  simplification  occurs,  so  t h a t,  for  example,  3  *  x  will  be  translated  into 
3  *  1  +  0  *  x. 

324 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

5.4  Syntax-Directed  Translation  Schemes 

Syntax-directed  translation  schemes  are  a  complementary  notation  to  syntax-
directed  definitions.  All  of  the  applications  of  syntax-directed  definitions  in 
Section  5.3  can  be  implemented  using  syntax-directed  translation  schemes. 

From  Section  2.3.5,  a  syntax-directed  translation  scheme  (SDT)  is  a  context-
free  grammar  with  program fragments  embedded  within  production  bodies.  T he 
program  fragments  are  called  semantic  actions  and  can  appear  at  any  position 
within  a  production  body.  By  convention,  we  place  curly  braces  around  actions; 
if  braces  are  needed  as  g r a m m ar  symbols,  then  we  quote  them. 

Any  SDT  can  be  implemented  by  first  building  a  parse  tree  and  then  per 

forming  t he  actions  in  a  left-to-right  depth-first  order;  t h at  is,  during  a  preorder 
traversal.  An  example  appears  in  Section  5.4.3. 

Typically,  SDT's  are  implemented  during  parsing,  without  building  a  parse 

tree.  In  this  section,  we  focus  on  t he  use  of  SDT's  to  implement  two  important 
classes  of  SDD's: 

1.  The  underlying  g r a m m ar  is  LR-parsable,  and  t he  SDD  is  S-attributed. 

2.  T he  underlying  grammar  is  LL-parsable,  and  t he  SDD  is  L-attributed. 

We  shall  see  how,  in  b o th  these  cases,  t he  semantic  rules  in  an  SDD  can  be 
converted  into  an  SDT  with  actions  t h at  are  executed  at  t he  right  time.  During 
parsing,  an  action  in  a  production  body  is  executed  as  soon  as  all  the  g r a m m ar 
symbols  to  the  left  of  the  action  have  been  matched. 

SDT's  t h at  can  be  implemented  during  parsing  can  be  characterized  by  in 
troducing  distinct  marker  nonterminals  in  place  of  each  embedded  action;  each 
marker  M  has  only  one  production,  M  -»  e.  If  the  g r a m m ar  with  marker  non 
terminals  can  be  parsed  by  a  given  method,  then  t he  SDT  can  be  implemented 
during  parsing. 

5.4.1  Postfix  Translation  Schemes 

By  far  t he  simplest  SDD  implementation  occurs  when  we  can  parse  t he  g r a m m ar 
bottom-up  and  the  SDD  is  S-attributed.  In  t h at  case,  we  can  construct  an  SDT 
in  which  each  action  is  placed  at  t he  end  of t he  production  and  is  executed  along 
with  t he  reduction  of  the  body  to  t he  head  of  t h at  production.  SDT's  with  all 
actions  at  t he  right  ends  of  t he  production  bodies  are  called  postfix  SDT's. 

E x a m p le  5 . 1 4:  T he  postfix  SDT  in  Fig.  5.18  implements  the  desk  calculator 
SDD  of  Fig.  5.1,  with  one  change: 
t he  action  for  t he  first  production  prints 
a  value.  T he  remaining  actions  are  exact  counterparts  of  the  semantic  rules. 
Since  t he  underlying  grammar  is  LR,  and  t he  SDD  is  S-attributed,  these  actions 
can  be  correctly  performed  along  with  t he  reduction  steps  of  t he  parser. 

• 

5.4. 

SYNTAX-DIRECTED 

TRANSLATION 

SCHEMES 

325 

L 
E 
E 
T 
T 
F 
F 

-> 
-> 

- )• 
-> 
-> 

£  n 
Ex+T 
T 
T±*F 
F 
(E) 
d i g it 

{  print (2?.vat)\  } 
{  E.val  =  Ei.val+  T.vol]  } 
{  E.val  =  T.vaf;  } 
{  T.val=Ti.valx  F.val] 
{  T.val  =  F.val;  } 
{  F.val  =  E.val;  } 
{  F.val  =  d i g it .lexval]  } 

} 

Figure  5.18:  Postfix  SDT  implementing  t he  desk  calculator 

5.4.2  Parser-Stack  Implementation  of  Postfix  SDT's 

Postfix  SDT's  can  be  implemented  during  LR  parsing  by  executing  the  actions 
when  reductions  occur.  T he  attribute(s)  of  each  grammar  symbol  can  be  put 
on  t he  stack  in  a  place  where  they  can  be  found  during  the  reduction.  T he 
best  plan  is  to  place  the  attributes  along  with  the  g r a m m ar  symbols  (or  the  LR 
states  t h at  represent  these  symbols)  in  records  on  the  stack  itself. 

In  Fig.  5.19,  the  parser  stack  contains  records  with  a  field  for  a  grammar 
symbol  (or  parser  state)  and,  below  it,  a  field  for  an  attribute.  T he  three 
g r a m m ar  symbols  X  YZ  are  on  top  of  the  stack;  perhaps  they  are  about  to  be 
reduced  according  to  a  production  like  A  —>  X  YZ.  Here,  we  show  X.x  as  t he 
one  a t t r i b u te  of  X,  and  so  on. 
In  general,  we  can  allow  for  more  attributes, 
either  by  making  the  records  large  enough  or  by  putting  pointers  to  records  on 
the  stack.  W i th  small  attributes,  it  may  be  simpler  to  make  t he  records  large 
enough,  even  if some  fields  go  unused  some  of t he  time.  However,  if one  or  more 
attributes  are  of  unbounded  size  —  say,  they  are  character  strings  —  then  it 
would  be  better  to  put  a  pointer  to  t he  attribute's  value  in  the  stack  record 
and  store  t he  actual  value  in  some  larger,  shared  storage  area  t h at  is  not  p a rt 
of  t he  stack. 

X 

Y 

Z 

State/grammar  symbol 

Synthesized  attribute(s) 

X.x 

Y.y 

Z.z 

J 

top 

Figure  5.19:  Parser  stack  with  a  field  for  synthesized  attributes 

If the  attributes  are  all  synthesized,  and  t he  actions  occur  at  the  ends  of the 
productions,  then  we  can  compute  the  attributes  for  the  head  when  we  reduce 
the  body  to  t he  head.  If  we  reduce  by  a  production  such  as  A X Y Z,  then 
we  have  all  t he  attributes  of  X,  Y,  and  Z  available,  at  known  positions  on  the 
stack,  as  in  Fig.  5.19.  After  t he  action,  A  and  its  attributes  are  at  the  top  of 
t he  stack,  in  t he  position  of  t he  record  for  X. 

E x a m p le  5.15  :  Let  us  rewrite  the  actions  of  t he  desk-calculator  SDT  of  Ex-

326 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

ample  5.14  so  t h at  they  manipulate  the  parser  stack  explicitly.  Such  stack 
manipulation  is  usually  done  automatically  by  the  parser. 

PR O D U C T I ON 

AC T I O NS 

L  -f  E  n 

{  print (stack [top  -  lj.ua/); 

top  =  top  —  1;  } 

E  ->  Ei  +  T 

{  stack[top  -  2].val  =  stack[top  -  2].val+  stack[top].val; 

E  ->  T 

top  =  top  —  2;  } 

T 

T 

Ti  *  F 

{  stack[top  -  2j.ua/  =  stack[top  -  2].val  x  stack[top].val; 

top  =  top —  2;  } 

F 

F  -±  (E) 

{  stack[top  —  2].ua/  =  stack[top  —  l].val; 

F  ->•  d i g it 

top — toj? — 2;  } 

Figure  5.20:  Implementing  the  desk  calculator  on  a  b o t t o m - up  parsing  stack 

Suppose  t h at  the  stack  is  kept  in  an  array  of  records  called  stack,  with  top 
a  cursor  to  t he  top  of t he  stack.  Thus,  stack[top]  refers  to  the  top  record  on  t he 
stack,  stack[top  —  1]  to  the  record  below  t h a t,  and  so  on.  Also,  we  assume  t h at 
each  record has  a field  called  val,  which holds  t he  attribute  of whatever  g r a m m ar 
symbol  is  represented  in  t h at  record.  Thus,  we  may  refer  to  the  a t t r i b u te  E.val 
t h at  appears  at  t he  third  position  on  t he  stack  as  stack[top  —  2].val.  T he  entire 
S DT  is  shown  in  Fig.  5.20. 

For  instance,  in  the  second  production,  E  -»  E\  +  T,  we  go  two  positions 
below  the  top  to  get  the  value  of E±,  and  we  find  the  value  of T  at  the  t o p.  T he 
resulting  sum  is  placed  where  t he  head  E  will  appear  after  t he  reduction,  t h at 
is,  two  positions  below  t he  current  top.  T he  reason  is  t h at  after  the  reduction, 
the  three  topmost  stack  symbols  are  replaced  by  one.  After  computing  E.val, 
we  pop  two  symbols  off  the  top  of  t he  stack,  so  t he  record  where  we  placed 
E.val  will  now  be  at  the  top  of  t he  stack. 

In  the  third  production,  E  —>  T,  no  action  is  necessary,  because  the  length 
of t he  stack  does  not  change,  and  t he  value  of T.val at  t he  stack  t op  will  simply 
become  the  value  of  E.val.  T he  same  observation  applies  to  t he  productions 
T  ->•  F  and  F 
d i g i t.  Production  F  ->•  (  E)  is  slightly  different.  Although 
t he  value  does  not  change,  two  positions  are  removed  from  t he  stack  during  t he 
reduction,  so  the  value  has  to  move  to  the  position  after  t he  reduction. 

Note  t h at  we  have  omitted  the  steps  t h at  manipulate  t he  first  field  of  t he 
stack  records  —  the  field  t h at  gives  t he  LR  state  or  otherwise  represents  t he 
grammar  symbol.  If  we  are  performing  an  LR  parse,  t he  parsing  table  tells  us 
what  the  new  state  is  every  time  we  reduce;  see  Algorithm  4.44.  Thus,  we  may 

5.4. 

SYNTAX-DIRECTED 

TRANSLATION 

SCHEMES 

327 

simply  place  t h at  state  in  t he  record  for  t he  new  top  of  stack. 

• 

5.4.3 

SDT's  With  Actions  Inside  Productions 

An  action  may  be  placed  at  any  position  within  t he  body  of  a  production. 
It  is  performed  immediately  after  all  symbols  to  its  left  are  processed.  Thus, 
if  we  have  a  production  B  -»  X  {a}  Y,  the  action  a  is  done  after  we  have 
recognized  X  (if  X  is  a  terminal)  or  all  t he  terminals  derived  from  X  (if  X  is 
a  nonterminal).  More  precisely, 

•  If  t he  parse  is  b o t t o m - u p,  then  we  perform  action  a  as  soon  as  this  oc 

currence  of  X  appears  on  the  top  of  t he  parsing  stack. 

•  If  t he  parse  is  top-down,  we  perform  a  just  before  we  a t t e m pt  to  expand 
this  occurrence  of  Y  (if  Y  a  nonterminal)  or  check  for  Y  on  t he  input  (if 
Y  is  a  terminal). 

SDT's  t h at  can  be  implemented  during  parsing  include  postfix  SDT's  and 
a  class  of  SDT's  considered  in  Section  5.5  t h at  implements  L-attributed  defini 
tions.  Not  all  SDT's  can  be  implemented  during  parsing,  as  we  shall  see  in  the 
next  example. 

E x a m p le  5. 1 6:  As  an  extreme  example  of  a  problematic  SDT,  suppose  t h at 
we  t u rn  our  desk-calculator  running  example  into  an  SDT  t h at  prints  the  prefix 
form  of  an  expression,  rather  t h an  evaluating  the  expression.  The  productions 
and  actions  are  shown  in  Fig.  5.21. 

1) 
L 
2)  E 
E 
3) 
T 
4) 
T 
5) 
F 
6) 
7)  F 

-> 
-» 
-> 
-> 

->• 

-> 

E  n 
{  p r i n t ( ' + ' );  }  #1  +T 
T 

{  print('*');  }  ?i  *E 
F 
(E) 
d i g it  {  print ( d i g it .lexval);  } 

Figure  5.21:  Problematic  SDT  for  infix-to-prefix  translation  during  parsing 

Unfortunately,  it  is  impossible  to  implement  this  SDT  during  either  top-
down  or  bottom-up  parsing,  because  the  parser  would  have  to  perform  critical 
actions,  like  printing  instances  of  *  or  +,  long  before  it  knows  whether  these 
symbols  will  appear  in  its  input. 

Using  marker  nonterminals  M2  and  M4  for  the  actions  in  productions  2 
and  4,  respectively,  on  input  3,  a  shift-reduce  parser  (see  Section  4.5.3)  has 
conflicts  between  reducing  by  M2  ->  e,  reducing  by  M4  —>  e,  and  shifting  t he 
digit. 

• 

328 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

Any  S DT  can  be  implemented  as  follows: 

1.  Ignoring  the  actions,  parse  the  input  and  produce  a  parse  tree  as  a  result. 

2.  Then,  examine  each  interior  node  N,  say  one  for  production  A  -±  a.  Add 
additional  children  to  N  for  the  actions  in  a,  so  the  children  of  N  from 
left  to  right  have  exactly  the  symbols  and  actions  of  a. 

3.  Perform  a  preorder  traversal  (see  Section  2.3.4)  of  t he  tree,  and  as  soon 

as  a  node  labeled  by  an  action  is  visited,  perform  t h at  action. 

For  instance,  Fig.  5.22  shows  the  parse  tree  for  expression  3 *5  +  4  with  ac 
tions  inserted.  If  we  visit  the  nodes  in  preorder,  we  get  the  prefix  form  of  t he 
expression:  +  *  3  5 4. 

{  print('+');  } 

E 

{  print(V);  } 

T 

* 

> 

digit 

{  print(4);  } 

digit 

{  print(5);  } 

digit  {  print(3);  } 

Figure  5.22:  Parse  tree  with  actions  embedded 

5.4.4  Eliminating  Left  Recursion  From  SDT's 

Since  no  g r a m m ar  with  left  recursion  can  be  parsed  deterministically  top-down, 
we  examined  left-recursion  elimination  in  Section  4.3.3.  W h en  t he  g r a m m ar  is 
p a rt  of  an  S D T,  we  also  need  to  worry  about  how  t he  actions  are  handled. 

First,  consider  the  simple  case,  in  which  the  only  thing  we  care  about  is 
the  order  in  which  the  actions  in  an  SDT  are  performed.  For  example,  if  each 
action  simply  prints  a  string,  we  care  only  about  t he  order  in  which  t he  strings 
are  printed.  In  this  case,  the  following  principle  can  guide  us: 

•  W h en  transforming  t he  grammar,  t r e at  t he  actions  as  if  they  were  termi 

nal  symbols. 

5.4. 

SYNTAX-DIRECTED 

TRANSLATION 

SCHEMES 

329 

This  principle  is  based  on  the  idea  t h at  the  g r a m m ar  transformation  preserves 
the  order  of  the  terminals  in  the  generated  string.  T he  actions  are  therefore 
executed  in  t he  same  order  in  any  left-to-right  parse,  top-down  or  b o t t o m - u p. 

T he  "trick"  for  eliminating  left  recursion  is  to  take  two  productions 

A  ->• Aa  |  (3 

t h at  generate  strings  consisting  of a  j3  and  any  number  of en's,  and  replace  t h em 
by  productions  t h at  generate  the  same  strings  using  a  new  nonterminal  R  (for 
"remainder")  of  the  first  production: 

A^j3R 
R  —»•  aR  |  e 

If (3  does  not  begin  with  A,  then  A  no  longer  has  a  left-recursive  production.  In 
regular-definition  terms,  with  both  sets  of  productions,  A  is  defined  by  0(a)*. 
See  Section  4.3.3  for  t he  handling  of  situations  where  A  has  more  recursive  or 
nonrecursive  productions. 

E x a m p le  5. 1 7:  Consider  the  following  E-productions  from  an  SDT  for  trans 
lating  infix  expressions  into  postfix  notation: 

E 
E 

-> 
-> 

E i +T 
T 

{  p r i n t ( ' + ' );  } 

If we  apply  the  standard  transformation  to  E,  the  remainder  of t he  left-recursive 
production  is 

a  =  +  T  {  print('-r');  } 

t he  body  of t he  other  production  is  T.  If we  introduce  R  for  the  remain 

and 
der  of  E,  we  get  the  set  of  productions: 

E 
R 
R 

T  R 

-+  +  T  {  printC-h');  }  R 
->• 

e 

• 

W h en  t he  actions  of  an  SDD  compute  attributes  rather  t h an  merely  printing 
output,  we  must  be  more  careful  about  how  we  eliminate  left  recursion  from  a 
grammar.  However,  if  the  SDD  is  S-attributed,  then  we  can  always  construct 
an  SDT  by  placing  attribute-computing  actions  at  appropriate  positions  in  t he 
new  productions. 

We  shall  give  a  general  schema  for  the  case  of  a  single  recursive  production, 
a  single  nonrecursive  production,  and  a  single  a t t r i b u te  of  the  left-recursive 
nonterminal;  t he  generalization  to  many  productions  of  each  type  is  not  hard, 
but  is  notationally  cumbersome.  Suppose  t h at  t he  two  productions  are 

330 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

A 
A 

-> 

A±Y 

{A.a  = 
X  {A.a  =  f(X.x)} 

g(A1.a,Y.y)} 

Here,  X.a  is  the  synthesized  a t t r i b u te  of  left-recursive  nonterminal  A,  and  X 
and  Y  are  single  g r a m m ar  symbols  with  synthesized  attributes  X.x  and  Y.y, 
respectively.  These  could  represent  a  string  of  several  g r a m m ar  symbols,  each 
with  its  own  attribute(s),  since  t he  schema  has  an  arbitrary  function  g  comput 
ing  A.a  in  the  recursive  production  and  an  arbitrary  function  /  computing  A.a 
In  each  case,  /  and  g  take  as  arguments  whatever 
in  the  second  production. 
attributes  they  are  allowed  to  access  if  the  SDD  is  S-attributed. 

We  want  to  t u rn  t he  underlying  g r a m m ar  into 

A 
R 

-» 

X  R 
| 
YR 

e 

Figure  5.23  suggests  what  the  SDT  on  t he  new  g r a m m ar  must  do.  In  (a) 
we  see  the  effect  of the  postfix  S DT  on  t he  original  grammar.  We  apply  /  once, 
corresponding  to  the  use  of production  A  ->  X,  and  then  apply  g  as  many  times 
as  we  use  the  production  A 
AY.  Since  R  generates  a  "remainder"  of  Y's, 
its  translation  depends  on  the  string  to  its  left,  a  string  of  t he  form  XYY  •  •  Y. 
Each  use  of  the  production  R  ->  YR  results  in  an  application  of  g.  For  R,  we 
use  an  inherited  a t t r i b u te  R.i  to  accumulate  the  result  of  successively  applying 
g,  starting  with  the  value  of  A.a. 

A.a 

= 

g(g(f(X.x),Y1.y),Y2.y) 

A 

A.a  =  g(f(X.x),Yuy) 

Y2 

X 

R.i  = 

f(X.x) 

A.a  = 

f(X.x) 

Yi 

Yi 

R.i 

= 

g(f(X.x),Yuy) 

X 

Y2 

'  R.i  =  g(g(f(X.x),  Yi.y),  Y2.y) 

(a) 

(b) 

Figure  5.23:  Eliminating  left  recursion  from  a  postfix  S DT 

In  addition,  R  has  a  synthesized  a t t r i b u te  R.s,  not  shown  in  Fig.  5.23. 
This  a t t r i b u te  is  first  computed  when  R  ends  its  generation  of  Y  symbols,  as 
signaled  by  the  use  of  production  R  —>•  e.  R.s  is  then  copied  up  the  tree,  so 
it  can  become  the  value  of  A.a  for  the  entire  expression  XYY  •  •  •  Y.  T he  case 
where  A  generates  XYY  is  shown  in  Fig.  5.23,  and  we  see  t h at  the  value  of  A.a 
at  the  root  of  (a)  has  two  uses  of  g.  So  does  R.i  at  the  b o t t om  of tree  (b),  and 
it  is  this  value  of  R.s  t h at  gets  copied  up  t h at  tree. 

To  accomplish  this  translation,  we  use  the  following  SDT: 

5.4. 

SYNTAX-DIRECTED 

TRANSLATION 

SCHEMES 

331 

A 
R 
R 

-> 
-> 
-> 

X 
Y 

{R.i  =  f(X.x)}  R 
{Ri.i  =  g(R.i,Y.y}  Ri 

{A.a  =  R.s} 

{R.s  =  Ri.s) 

e 

{R.s  =  R.i} 

Notice  t h at  t he  inherited  a t t r i b u te  R.i  is  evaluated  immediately  before  a  use 
of  R  in  the  body,  while  the  synthesized  attributes  A.a  and  -R.s  are  evaluated 
at  the  ends  of  the  productions.  Thus,  whatever  values  are  needed  to  compute 
these  attributes  will  be  available  from  what  has  been  computed  to  the  left. 

5.4.5 

SDT's  for  L-Attributed  Definitions 

In  Section  5.4.1,  we  converted  S-attributed  SDD's  into  postfix  SDT's,  with 
actions  at  the  right  ends  of  productions.  As  long  as  t he  underlying  grammar  is 
LR,  postfix  SDT's  can  be  parsed  and  translated  b o t t o m - u p. 

Now,  we  consider  the  more  general  case  of  an  L-attributed  SDD.  We  shall 
assume  t h at  the  underlying  grammar  can  be  parsed  top-down,  for  if  not  it  is 
frequently  impossible  to  perform  the  translation  in  connection  with  either  an 
LL  or  an  LR  parser.  W i th  any  grammar,  the  technique  below  can  be  imple 
mented  by  attaching  actions  to  a  parse  tree  and  executing  them  during  preorder 
traversal  of  t he  tree. 

T he  rules  for  turning  an  L-attributed  SDD  into  an  SDT  are  as  follows: 

1.  Embed  the  action  t h at  computes  the  inherited  attributes  for  a  nonterminal 
A  immediately  before  t h at  occurrence  of  A  in  the  body  of  the  production. 
If  several  inherited  attributes  for  A  depend  on  one  another  in  an  acyclic 
fashion,  order  t he  evaluation  of  attributes  so  t h at  those  needed  first  are 
computed  first. 

2.  Place  the  actions  t h at  compute  a  synthesized  attribute  for  the  head  of  a 

production  at  the  end  of  the  body  of  t h at  production. 

We  shall  illustrate  these  principles  with  two  extended  examples.  T he  first 
involves  typesetting.  It  illustrates  how  the  techniques  of compiling  can  be  used 
in  language  processing  for  applications  other  t h an  what  we  normally  think  of 
as  programming  languages.  The  second  example  is  about  the  generation  of 
intermediate  code  for  a  typical  programming-language  construct:  a  form  of 
while-statement. 

E x a m p le  5 . 1 8:  This  example  is  motivated  by  languages  for  typesetting  m a t h 
ematical  formulas.  Eqn  is  an  early  example  of  such  a  language;  ideas  from  Eqn 
are  still  found  in  the  T^X  typesetting  system,  which  was  used  to  produce  this 
book. 

We  shall  concentrate  on  only  the  capability  to  define  subscripts,  subscripts 
of  subscripts,  and  so  on,  ignoring  superscripts,  built-up  fractions,  and  all  other 
mathematical  features.  In  t he  Eqn  language,  one  writes  a  sub  i  sub  j  to  set 
the  expression  a{j.  A  simple  grammar  for  boxes  (elements  of  text  bounded  by 
a  rectangle)  is 

332 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

B ^ BlB2\ B1 

s ub 

B2\(B1)\ 

t e xt 

Corresponding  to  these  four  productions,  a  box  can  be  either 

1.  Two  boxes,  juxtaposed,  with  the  first,  B\,  to  t he  left  of  the  other,  B2. 

2.  A  box  and  a  subscript  box.  T he  second  box  appears  in  a  smaller  size, 

lower,  and  to  t he  right  of  t he  first  box. 

3.  A  parenthesized  box,  for  grouping  of  boxes  and  subscripts.  Eqn  and  I gX 
both  use  curly  braces  for  grouping,  but  we  shall  use  ordinary,  round  paren 
theses  to  avoid  confusion  with  the  braces  t h at  surround  actions  in  SDT's. 

4.  A  text  string,  t h at  is,  any  string  of  characters. 

This  grammar  is  ambiguous,  but  we  can  still  use  it  to  parse  bottom-up  if  we 
make  subscripting  and  juxtaposition  right  associative,  with  s ub  taking  prece 
dence  over  juxtaposition. 

Expressions  will  be  typeset  by  constructing  larger  boxes  out  of smaller  ones. 
In  Fig.  5.24,  the  boxes  for  E\  and  .height  are  about  to  be  juxtaposed  to  form 
the  box  for  Ei.height.  The  left  box  for  E\  is  itself  constructed  from  the  box 
for  E  and  the  subscript  1.  T he  subscript  1  is  handled  by  shrinking  its  box  by 
about  30%,  lowering  it,  and  placing  it  after  the  box  for  E.  Although  we  shall 
treat  .height  as  a  text  string,  the  rectangles  within  its  box  show  how  it  can  be 
constructed  from  boxes  for  the  individual  letters. 

Figure  5.24:  Constructing  larger  boxes  from  smaller  ones 

In  this  example,  we  concentrate  on  t he  vertical  geometry  of boxes  only.  T he 
horizontal  geometry —  the  widths  of boxes  —  is  also  interesting,  especially  when 
different  characters  have  different  widths.  It  m ay  not  be  readily  apparent,  but 
each  of  the  distinct  characters  in  Fig.  5.24  has  a  different  width. 

The  values  associated  with  the  vertical  geometry  of  boxes  are  as  follows: 

a)  T he  point  size  is  used  to  set  text  within  a  box.  We  shall  assume  t h at 
characters  not  in  subscripts  are  set  in  10  point  type,  the  size  of  type  in 
this  book.  Further,  we  assume  t h at  if  a  box  has  point  size  p,  then  its 
Inherited  a t t r i b u te  B.ps 
subscript  box  has  the  smaller  point  size  0.7p. 
will  represent  t he  point  size  of block  B.  This  a t t r i b u te  must  be  inherited, 
because  the  context  determines  by  how  much  a  given  box  needs  to  be 
shrunk,  due  to  t he  number  of  levels  of  subscripting. 

5.4. 

SYNTAX-DIRECTED 

TRANSLATION 

SCHEMES 

333 

b)  Each  box  has  a  baseline,  which  is  a  vertical  position  t h at  corresponds  to 
t he  b o t t o ms  of lines  of  text,  not  counting  any  letters,  like  "g"  t h at  extend 
below  the  normal  baseline. 
In  Fig.  5.24,  t he  dotted  line  represents  t he 
baseline  for  t he  boxes  E,  .height,  and  the  entire  expression.  The  baseline 
for  the  box  containing  the  subscript  1  is  adjusted  to  lower  the  subscript. 

c)  A  box  has  a  height,  which  is  the  distance  from  the  top  of  the  box  to  the 

baseline.  Synthesized  attribute  B.ht  gives  the  height  of  box  B. 

d)  A  box  has  a  depth,  which  is  the  distance  from  the  baseline  to  the  b o t t om 

of  t he  box.  Synthesized  attribute  B.dp  gives  the  depth  of  box  B. 

T he  SDD  in  Fig.  5.25  gives  rules  for  computing  point  sizes,  heights,  and 

depths.  Production  1  is  used  to  assign  B.ps  the  initial  value  10. 

PR O D U C T I ON 

SE M A N T IC 

RU L ES 

1) 

S-+B 

B.ps  =  10 

2)  B  —y  B\  B2 

Bi.ps  —  B.ps 
B2.ps  =  B.ps 
B.ht  =  max(B1.ht,  B2.ht) 
B.dp  —  max(Bi.d[p,  B2.dp) 

3) 

B  -y  Bi  s ub  B2 

Bi.ps  =  B.ps 

B2.ps  —  0.7  x  B.ps 
B.ht  =  max(B1M,  B2.ht-  0.25  x  B.ps) 
B.dp  =  max(Bi.dp,B2.dp  +  0.25  x  B.ps) 

4)  B  ->  (  Bi  ) 

Bi.ps  —  B.ps 
B.ht^Bi.ht 
B.dp  =  Bi.dp 

5)  B  ->  t e xt 

B.ht= 

getHt(B  .ps,  t e x t,  lexval) 

B.dp  =  getDp  (B.ps,  t e x t, lexval) 

Figure  5.25:  SDD  for  typesetting  boxes 

Production  2  handles  juxtaposition.  Point  sizes  are  copied  down  t he  parse 
tree;  t h at  is,  two  sub-boxes  of  a  box  inherit  the  same  point  size  from  the  larger 
box.  Heights  and  depths  are  computed  up  the  tree  by  taking  t he  maximum. 
T h at  is,  t he  height  of  t he  larger  box  is  t he  m a x i m um  of  t he  heights  of  its  two 
components,  and  similarly  for  the  depth. 

Production  3  handles  subscripting  and  is  the  most  subtle. 

In  this  greatly 
simplified  example,  we  assume  t h at  the  point  size  of  a  subscripted  box  is  70% 
of  the  point  size  of  its  parent.  Reality  is  much  more  complex,  since  subscripts 
cannot  shrink  indefinitely;  in  practice,  after  a  few  levels,  the  sizes  of  subscripts 

334 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

shrink  hardly  at  all.  Further,  we  assume  t h at  the  baseline  of  a  subscript  box 
drops  by  25%  of  the  parent's  point  size;  again,  reality  is  more  complex. 

Production  4  copies  attributes  appropriately  when  parentheses  are  used.  Fi 
nally,  production  5  handles  the  leaves  t h at  represent  text  boxes.  In  this  m a t t er 
too,  the  true  situation  is  complicated,  so  we  merely  show  two  unspecified  func 
tions  getHt  and  getDp  t h at  examine  tables  created  with  each  font  to  determine 
the  maximum  height  and  maximum  depth  of  any  characters  in  the  text  string. 
The  string  itself  is  presumed  to  be  provided  as  the  a t t r i b u te  lexval  of  terminal 
t e x t. 

Our  last  task  is  to  t u rn  this  SDD  into  an  SDT,  following  the  rules  for  an  L-

attributed  SDD,  which  Fig.  5.25  is.  The  appropriate  S DT  is  shown  in  Fig.  5.26. 
For  readability,  since  production  bodies  become  long,  we  split  t h em  across  lines 
and  line  up  the  actions.  Production  bodies  therefore  consist  of  the  contents  of 
all  lines  up  to  the  head  of  the  next  production. 

• 

PR O D U C T I ON 

AC T I O NS 

1) 

S 

2)  B 

3)  B 

B 

Bi 
B2 

{  B.ps  =  1 0 ;} 

{Bi.ps  = 
{B2.ps  = 
{  B.ht  = 
B.dp  = 

B.ps;  } 
B.ps;  } 
max(Bi.ht, 
m&x(Bi.dp,B2.dp); 

B2.ht); 

} 

Bi  s ub 
B2 

{Bi.ps  = 
{B2.ps  = 
{  B.ht  = 
B.dp  = 

B.ps;  } 
0.7  x  B.ps;  } 
max(Bi.ht,B2.ht- 
max(B1.dp,B2.dp  +  0.25 

0.25 

x 

B.ps); 
x  B.ps): 

4) 

B 

-> 

( 
Bi) 

{Bi.ps  = 
{  B.ht  = 
B.dp  = 

B.ps;  } 
Bi.ht; 
Bi.dp; 

} 

5)  B 

t e xt 

{  BM  = 
B.dp  = 

getHt  {B.ps,  text.lexval); 
getDp  (B.ps,  text.lexval);  } 

Figure  5.26:  SDT  for  typesetting  boxes 

Our  next  example  concentrates  on  a  simple  while-statement  and  the  gener 
ation  of  intermediate  code  for  this  type  of  statement. 
Intermediate  code  will 
be  treated  as  a  string-valued  attribute.  Later,  we  shall  explore  techniques  t h at 
involve  t he  writing  of pieces  of a  string-valued  a t t r i b u te  as  we  parse,  thus  avoid 
ing  t he  copying  of  long  strings  to  build  even  longer  strings.  T he  technique  was 
introduced  in  Example  5.17,  where  we  generated  the  postfix  form  of  an  infix 

5.4. 

SYNTAX-DIRECTED 

TRANSLATION 

SCHEMES 

335 

expression  "on-the-fly,"  rather  t h an  computing  it  as  an  attribute.  However,  in 
our  first  formulation,  we  create  a  string-valued  a t t r i b u te  by  concatenation. 

E x a m p le  5 . 1 9:  For  this  example,  we  only  need  one  production: 

S  ->  w h i le  (  C  )  Si 

Here,  S  is  the  nonterminal  t h at  generates  all  kinds  of  statements,  presumably 
including  if-statements,  assignment  statements,  and  others.  In  this  example,  C 
stands  for  a  conditional  expression  —  a  boolean  expression  t h at  evaluates  to 
t r ue  or  false. 

In  this  flow-of-control  example,  t he  only  things  we  ever  generate  are  labels. 
All  t he  other  intermediate-code  instructions  are  assumed  to  be  generated  by 
parts  of the  SDT  t h at  are  not  shown.  Specifically,  we  generate  explicit  instruc 
tions  of  the  form  l a b el  L,  where  L  is  an  identifier,  to  indicate  t h at  L  is  t he 
label  of  the  instruction  t h at  follows.  We  assume  t h at  t he  intermediate  code  is 
like  t h at  introduced  in  Section  2.8.4. 

T he  meaning  of  our  while-statement  is  t h at  the  conditional  C  is  evaluated. 
If it  is  true,  control  goes  to  the  beginning  of the  code  for  Si.  If false,  then  control 
goes  to  the  code  t h at  follows  the  while-statement's  code.  T he  code  for  Si  must 
be  designed  to  j u mp  to  the  beginning  of  the  code  for  the  while-statement  when 
finished;  t he  j u mp  to  the  beginning  of  the  code  t h at  evaluates  C  is  not  shown 
in  Fig.  5.27. 

We  use  the  following  attributes  to  generate  the  proper  intermediate  code: 

1.  The  inherited  a t t r i b u te  S.next  labels  the  beginning  of  the  code  t h at  must 

be  executed  after  S  is  finished. 

2.  T he  synthesized  a t t r i b u te  S.code  is  the  sequence  of  intermediate-code 
steps  t h at  implements  a  statement  S  and  ends  with  a  j u mp  to  S.next. 

3.  T he  inherited  a t t r i b u te  C.true  labels  the  beginning  of  the  code  t h at  must 

be  executed  if  C  is  true. 

4.  The  inherited  a t t r i b u te  C.false  labels  t he  beginning  of  t he  code  t h at  must 

be  executed  if  C  is  false. 

5.  The  synthesized  attribute  C.code  is  the  sequence  of  intermediate-code 
steps  t h at  implements  the  condition  C  and  jumps  either  to  C.true  or  to 
C.false,  depending  on  whether  C  is  true  or  false. 

T he  SDD  t h at  computes  these  attributes  for  the  while-statement  is  shown 

in  Fig.  5.27.  A  number  of  points  merit  explanation: 

•  T he  function  new  generates  new  labels. 

•  T he  variables  LI  and  L2  hold  labels  t h at  we  need  in  the  code.  LI  is  the 
beginning  of  the  code  for  the  while-statement,  and  we  need  to  arrange 

336 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

S  ->  w h i le  (C)Si 

Ll  =  newQ; 
L2  =  newQ; 
S±.next  =  LI; 
C.  false  =  S.next; 
C.true  =  1/2; 
S.code  =  l a b el  ||  LI  \\  C.code  ||  l a b el  ||  L2  ||  S1.code 

Figure  5.27:  SDD  for  while-statements 

t h at  Si  j u m ps  there  after  it  finishes.  T h at  is  why  we  set  Si.next  to  LI. 
L2  is  the  beginning  of the  code  for  Si,  and  it  becomes  the  value  of  C.true, 
because  we  branch  there  when  C  is  true. 

•  Notice  t h at  C.false  is  set  to  S.next,  because  when  t he  condition  is  false, 

we  execute  whatever  code  must  follow  the  code  for  S. 

•  We  use  ||  as  t he  symbol  for  concatenation  of intermediate-code  fragments. 
T he  value  of  S.code  thus  begins  with  t he  label  L I,  then  t he  code  for 
condition  C,  another  label  L2,  and  the  code  for  Si. 

This  SDD  is  L-attributed.  When  we  convert  it  into  an  SDT,  t he  only  re 
maining  issue  is  how  to  handle  the  labels  LI  and  L2,  which  are  variables,  and 
not  attributes.  If  we  treat  actions  as  dummy  nonterminals,  then  such  variables 
can  be  treated  as  t he  synthesized  attributes  of  dummy  nonterminals.  Since  LI 
and  L2  do  not  depend  on  any  other  attributes,  they  can  be  assigned  to  the 
first  action  in  t he  production.  T he  resulting  SDT  with  embedded  actions  t h at 
implements  this  L-attributed  definition  is  shown  in  Fig.  5.28. 

• 

S  ->  w h i le  ( 
C) 

{  LI  =  newQ;  L2  =  newQ;  C.false  =  S.next;  C.true  =  L2;  } 

{Si.next^Ll;} 

Si 

{  S.code  =  l a b el  ||  LI  ||  C.code  ||  l a b el  ||  L2  ||  Si.code;  } 

Figure  5.28:  SDT  for  while-statements 

5.4.6  Exercises  for  Section  5.4 

E x e r c i se  5 . 4 . 1:  We  mentioned  in  Section  5.4.2  t h at  it  is  possible  to  deduce, 
from  the  LR  state  on  the  parsing  stack,  what  grammar  symbol  is  represented 
by  t he  state.  How  would  we  discover  this  information? 

E x e r c i se  5 . 4 . 2:  Rewrite  the  following  SDT: 

A 
A  {a}  B  |  A  B  {b}  |  0 
B  ->  B  {c}  A  |  B  A  {d}  |  1 

5.5. 

IMPLEMENTING  L-ATTRIBUTED 

SDD'S 

337 

so  t h at  the  underlying  grammar  becomes  non-left-recursive.  Here,  a,  6,  c,  and 
d  are  actions,  and  0  and  1  are  terminals. 

!  E x e r c i se  5 . 4 . 3:  T he  following  SDT  computes  the  value  of  a  string  of  O's  and 

l 's  interpreted  as  a  positive,  binary  integer. 

B 

-» 
| 
j 

Br  0  {B.val  =  2  x  Bx.val] 
Bx  1  {B.val  =  2  x  Bx.val  +  1} 
1  {B.val  =  1} 

Rewrite  this  SDT  so  the  underlying  grammar  is  not  left  recursive,  and  yet  t he 
same  value  of  B.val  is  computed  for  t he  entire  input  string. 

!  E x e r c i se  5 . 4 . 4:  Write  L-attributed  SDD's  analogous  to  t h at  of  Example  5.19 
for  the  following  productions,  each  of which  represents  a  familiar  flow-of-control 
construct,  as  in  the  programming language  C.  You  may  need to  generate  a three-
address  statement  to  j u mp  to  a  particular  label  L,  in  which  case  you  should 
generate  g o to  L. 

a)  S  -)•  if  (  C  )  Si  e l se  S2 

b)  S 

do  Si  w h i le  (  C  ) 

c)  S 

-4'{'  L  '}';  L 

L  S  \  e 

Note  t h at  any  statement  in  the  list  can  have  a  j u mp  from  its  middle  to 
t he  next  Statement,  so  it  is  not  sufficient  simply  to  generate  code  for  each 
statement  in  order. 

E x e r c i se  5 . 4 . 5:  Convert  each  of  your  SDD's  from  Exercise  5.4.4  to  an  SDT 
in  the  manner  of  Example  5.19. 

E x e r c i se  5 . 4 . 6:  Modify  the  SDD  of Fig.  5.25  to  include  a synthesized  a t t r i b u te 
B.le,  t he  length  of  a  box.  T he  length  of  t he  concatenation  of  two  boxes  is  the 
sum  of t he  lengths  of  each.  Then  add  your  new  rules  to  the  proper  positions  in 
t he  SDT  of  Fig.  5.26 

E x e r c i se  5 . 4 . 7:  Modify  the  SDD  of  Fig.  5.25  to  include  superscripts  denoted 
by  operator  s up  between  boxes. 
If  box  B2  is  a  superscript  of  box  Bi,  then 
position  t he  baseline  of  B2  0.6  times  the  point  size  of  Bi  above  t he  baseline  of 
Bi.  Add  the  new  production  and  rules  to  the  SDT  of  Fig.  5.26. 

5.5 

Implementing  L-Attributed  SDD's 

Since  many  translation  applications  can  be  addressed  using  L-attributed  defi 
nitions,  we  shall  consider  their  implementation  in  more  detail  in  this  section. 
T he  following  methods  do  translation  by  traversing  a  parse  tree: 

338 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

1.  Build  the  parse  tree  and  annotate.  This  method  works  for  any  noncircular 
SDD  whatsoever.  We  introduced  annotated  parse  trees  in  Section  5.1.2. 

2.  Build 

the  parse 

tree,  add  actions,  and  execute 

the  actions 

in  preorder. 

This  approach  works  for  any  L-attributed  definition.  We  discussed  how 
to  t u rn  an  L-attributed  SDD  into  an  SDT  in  Section  5.4.5;  in  particular, 
we  discussed  how  to  embed  actions  into  productions  based  on  the  semantic 
rules  of  such  an  SDD. 

In  this  section,  we  discuss  the  following  methods  for  translation  during  parsing: 

3.  Use  a  recursive-descent  parser  with  one  function  for  each  nonterminal. 
The  function  for  nonterminal  A  receives  the  inherited  attributes  of  A  as 
arguments  and  returns  the  synthesized  attributes  of  A. 

4.  Generate  code  on  the  fly,  using  a  recursive-descent  parser. 

5.  Implement  an  SDT  in  conjunction  with  an  LL-parser.  T he  attributes  are 
kept  on  the  parsing  stack,  and  the  rules  fetch  the  needed  attributes  from 
known  locations  on  the  stack. 

6.  Implement  an  SDT  in  conjunction  with  an  LR-parser.  This  method  may 
be  surprising,  since  the  SDT  for  an  L-attributed  SDD  typically  has  ac 
tions  in  t he  middle  of  productions,  and  we  cannot  be  sure  during  an  LR 
parse  t h at  we  are  even  in  t h at  production  until  its  entire  body  has  been 
constructed.  We  shall  see,  however,  t h at  if the  underlying  grammar  is  LL, 
we  can  always  handle  b o th  the  parsing  and  translation  b o t t o m - u p. 

5.5.1  Translation  During  Recursive-Descent  Parsing 

A  recursive-descent  parser  has  a  function  A  for  each  nonterminal  A,  as  discussed 
in  Section  4.4.1.  We  can  extend  t he  parser  into  a  translator  as  follows: 

a)  T he  arguments  of  function  A  are  t he  inherited  attributes  of  nonterminal 

A. 

b)  The  return-value  of  function  A  is  the  collection  of  synthesized  attributes 

of  nonterminal  A. 

In  t he  body  of  function  A,  we  need  to  both  parse  and  handle  attributes: 

1.  Decide  upon  the  production  used  to  expand  A. 

2.  Check  t h at  each  terminal  appears  on  t he  input  when  it  is  required.  We 
shall  assume  t h at  no  backtracking  is  needed,  but  the  extension  to  recur 
sive-descent  parsing  with  backtracking  can  be  done  by  restoring  t he  input 
position  upon  failure,  as  discussed  in  Section  4.4.1. 

5.5. 

IMPLEMENTING 

L-ATTRIBUTED 

SDD'S 

339 

3.  Preserve,  in  local  variables,  t he  values  of  all  attributes  needed  to  compute 
inherited  attributes  for  nonterminals  in  the  body  or  synthesized  attributes 
for  t he  head  nonterminal. 

4.  Call  functions  corresponding  to  nonterminals  in  the  body  of  the  selected 
production,  providing  them  with  the  proper  arguments.  Since  the  un 
derlying  SDD  is  L-attributed,  we  have  already  computed  these  attributes 
and  stored  them  in  local  variables. 

E x a m p le  5.20  :  Let  us  consider  t he  SDD  and  SDT  of  Example  5.19  for  while-
statements.  A  pseudocode  rendition  of  the  relevant  parts  of  the  function  S 
appears  in  Fig.  5.29. 

s t r i ng 5(label  next)  { 

s t r i ng  Scode,  Ccode;  /*  local  variables  holding  code  fragments  */ 
l a b el  LI,  L2;  /*  the  local  labels  */ 
if  (  current  input  ==  token  w h i le  )  { 

advance  input; 
check  ' ('  is  next  on  the  input,  and  advance; 
LI  =  new(); 
L2  =  new(); 
Ccode  =  C(next,  L2); 
check  ' )'  is  next  on  the  input,  and  advance; 
Scode=  5  ( L I ); 
r e t u r n C ' l a b e l"  ||  LI  ||  Ccode  ||  " l a b e l"  ||  L2  ||  Scode); 

} 
else  /*  other  statement  types  */ 

} 

Figure  5.29:  Implementing  while-statements  with  a  recursive-descent  parser 

We  show  S  as  storing  and  returning  long  strings.  In  practice,  it  would  be 
far  more  efficient  for  functions  like  S  and  C  to  return  pointers  to  records  t h at 
represent  these  strings.  Then,  the  return-statement  in  function  S  would  not 
physically  concatenate  the  components  shown,  but  rather  would  construct  a 
record,  or  perhaps  tree  of  records,  expressing  the  concatenation  of  the  strings 
represented  by  Scode  and  Ccode,  t he  labels  LI  and  L2,  and  the  two  occurrences 
of  the  literal  string  " l a b e l ". 

• 

E x a m p le  5 . 2 1:  Now,  let  us  take  up  the  SDT  of  Fig.  5.26  for  typesetting 
boxes.  First,  we  address  parsing,  since  t he  underlying  grammar  in  Fig.  5.26 
is  ambiguous.  The  following  transformed  grammar  makes  juxtaposition  and 
subscripting  right  associative,  with  s ub  taking  precedence  over  juxtaposition: 

340 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

S 
B 
T 
F 

-+ 

-» 
-> 

\  T 

B 
T  Bi 
F  s ub  Ti 
(  B  ) 

| 

|  F 

t e xt 

T he  two  new  nonterminals,  T  and  F,  are  motivated  by  terms  and  factors  in 
expressions.  Here,  a  "factor,"  generated  by  F,  is  either  a  parenthesized  box 
or  a  text  string.  A  "term,"  generated  by  T,  is  a  "factor"  with  a  sequence  of 
subscripts,  and  a  box  generated  by  B  is  a  sequence  of juxtaposed  "terms." 

The  attributes  of  B  carry  over  to  T  and  F,  since  the  new  nonterminals  also 
denote  boxes;  they  were  introduced  simply  to  aid  parsing.  Thus,  b o th  T  and 
F  have  an  inherited  attribute  ps  and  synthesized  attributes  ht  and  dp,  with 
semantic  actions  t h at  can  be  adapted  from  the  SDT  in  Fig.  5.26. 

The  grammar  is  not  yet  ready  for  top-down  parsing,  since  t he  productions 
for  B  and  T  have  common  prefixes.  Consider  T,  for  instance.  A  top-down 
parser  cannot  choose  between  the  two  productions  for  T  by  looking  one  symbol 
ahead  in  the  input.  Fortunately,  we  can  use  a  form  of  left-factoring,  discussed 
in  Section  4.3.4,  to  make  t he  g r a m m ar  ready.  W i th  SDT's,  the  notion  of  com 
mon  prefix  applies  to  actions  as  well.  Both  productions  for  T  begin  with  t he 
nonterminal  F  inheriting  attribute  ps  from  T. 

T he  pseudocode  in  Fig.  5.30  for  T(ps)  folds  in  t he  code  for  F(ps).  After 
|  F,  there  is  only  one  call  to  F;  t he 
left-factoring  is  applied  to  T  -»  F  s ub  Ti 
pseudocode  shows  the  result  of  substituting  t he  code  for  F  in  place  of this  call. 
The  function  T  will  be  called  as  T(10.0)  by  t he  function  for  B,  which  we 
do  not  show. 
It  returns  a  pair  consisting  of  t he  height  and  depth  of  t he  box 
generated  by  nonterminal  T;  in  practice,  it  would  return  a  record  containing 
the  height  and  depth. 

Function  T  begins  by  checking  for  a  left  parenthesis,  in  which  case  it  must 

have  t he  production  F  —>  (B)  to  work  with.  It  saves  whatever  t he  B  inside  t he 
parentheses  returns,  but  if  t h at  B  is  not  followed  by  a  right  parenthesis,  then 
there  is  a  syntax  error,  which  must  be  handled  in  a  manner  not  shown. 

Otherwise,  if  the  current  input  is  t e x t,  then  the  function  T  uses  getHt  and 

getDp  to  determine  the  height  and  depth  of  this  text. 

T  then  decides  whether  the  next  box  is  a  subscript  and  adjusts  t he  point 
size,  if  so.  We  use  the  actions  associated  with  the  production  B  ->•  B  s ub  B 
in  Fig.  5.26  for  the  height  and  depth  of  the  larger  box.  Otherwise,  we  simply 
return  what  F  would  have  returned: 

(hl,d\). 

• 

5.5.2  On-The-Fly  Code  Generation 

T he  construction  of  long  strings  of  code  t h at  are  a t t r i b u te  values,  as  in  Ex 
ample  5.20,  is  undesirable  for  several  reasons,  including  t he  time  it  could  take 
In  common  cases  such  as  our  running  code-
to  copy  or  move  long  strings. 
generation  example,  we  can  instead  incrementally  generate  pieces  of  the  code 
into  an  array  or  output  file  by  executing  actions  in  an  SDT.  The  elements  we 
need  to  make  this  technique  work  are: 

5.5. 

IMPLEMENTING 

L-ATTRIBUTED 

SDD'S 

341 

(float,  float)  r(float  ps)  { 

float  hi,  h2,  dl,  d2;  /*  locals  to  hold  heights  and  depths  */ 
/*  start  code  for  F(ps)  */ 
if  (  current  input  ==  ' ('  )  { 
advance  input; 
(hl,dl)  =  B(ps); 
if  (current  input  !=  ' )'  )  syntax  error:  expected  ' ) '; 
advance  input; 

} 
e l se  if  (  current  input  ==  t e xt  )  { 

let  lexical  value  text.lexval  be  t; 
advance  input; 
hi  =  getHt(ps,  t); 
dl  =  getDp(ps,  t); 

} 
e l se  syntax  error:  expected  t e xt  or  '('; 
/*  end  code  for  F(ps)  */ 
if  (  current  input  ==  s ub  )  { 
advance  input; 
(h2,d2)  =  T{0.7*ps); 
r e t u rn  (max(/il, h2  —  0.25  *  ps),  m a x ( d l, d2  +  0.25  *  ps)); 

} 
r e t u rn 

(hi,  dl); 

Figure  5.30:  Recursive-descent  typesetting  of  boxes 

1.  There  is,  for  one  or  more  nonterminals,  a  main  attribute.  For  conve 
nience,  we  shall  assume  t h at  the  main  attributes  are  all  string  valued.  In 
Example  5.20,  the  attributes  S.code  and  C.code  are  main  attributes;  the 
other  attributes  are  not. 

2.  The  main  attributes  are  synthesized. 

3.  T he  rules  t h at  evaluate  t he  main  a t t r i b u te  (s)  ensure  t h at 

(a)  T he  main  a t t r i b u te  is  t he  concatenation  of  main  attributes  of  non 
terminals  appearing  in  the  body  of the  production  involved,  perhaps 
with  other  elements  t h at  are  not  main  attributes,  such  as  the  string 
l a b el  or  the  values  of  labels  LI  and  L2. 

(b)  The  main  attributes  of  nonterminals  appear  in  the  rule  in  the  same 
order  as  the  nonterminals  themselves  appear  in  the  production  body. 

As  a  consequence  of the  above  conditions,  the  main  attribute  can  be  constructed 
by  emitting  the  non-main-attribute  elements  of the  concatenation.  We  can  rely 

342 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

The  Type  of  Main  Attributes 

Our  simplifying  assumption  t h at  main  attributes  are  of string  type  is  really 
too  restrictive.  T he  true  requirement  is  t h at  the  type  of  all  the  main 
attributes  must  have  values  t h at  can  be  constructed  by  concatenation  of 
elements.  For  instance,  a  list  of  objects  of  any  type  would  be  appropriate, 
as  long  as  we  represent  these  lists  in  a  way  t h at  allows  elements  to  be 
efficiently  appended  to  the  end  of  t he  list.  Thus,  if  the  purpose  of  the 
main  attribute  is  to  represent  a  sequence  of  intermediate-code  statements, 
we  could  produce  the  intermediate  code  by  writing  statements  to  t he  end 
of  an  array  of  objects.  Of  course  t he  requirements  stated  in  Section  5.5.2 
still  apply  to  lists;  for  example,  main  attributes  must  be  assembled  from 
other  main  attributes  by  concatenation  in  order. 

on  the  recursive  calls  to  the  functions  for  the  nonterminals  in  a  production  b o dy 
to  emit  the  value  of  their  main  a t t r i b u te  incrementally. 

E x a m p le  5 . 2 2:  We  can  modify  the  function  of  Fig.  5.29  to  emit  elements  of 
t he  main  translation  S.code  instead  of  saving  t h em  for  concatenation  into  a 
return  value  of  S.code.  T he  revised  function  S  appears  in  Fig.  5.31. 

v o id  £ ( l a b el  next)  { 

l a b el  LI,  L2;  /*  the  local  labels  */ 
if  (  current  input  ==  token  w h i le  )  { 

advance  input; 
check  ' ('  is  next  on  t he  input,  and  advance; 
LI  =  newQ; 
L2  =  newQ; 
print("la.bel",Ll); 
C(next,  L2); 
check  ' )'  is  next  on  t he  input,  and  advance; 
print(" 
S(L1); 

l a b el  ",L2); 

} 
e l se  /*  other  statement  types  */ 

} 

Figure  5.31:  On-the-fly  recursive-descent  code  generation  for  while-statements 

In  Fig.  5.31,  S  and  C  now  have  no  return  value,  since  their  only  synthesized 
attributes  are  produced  by  printing.  Further,  the  position  of  the  print  state 
ments  is  significant.  The  order  in  which  output  is  printed  is:  first  l a b el  LI, 
then  t he  code  for  C  (which  is  the  same  as  the  value  of  Ccode  in  Fig.  5.29),  then 

5.5. 

IMPLEMENTING 

L-ATTRIBUTED 

SDD'S 

343 

l a b el  L2,  and  finally  the  code  from  the  recursive  call  to  S  (which  is  the  same 
as  Scode  in  Fig.  5.29).  Thus,  t he  code  printed  by  this  call  to  S  is  exactly  t he 
same  as  the  value  of  Scode  t h at  is  returned  in  Fig.  5.29). 

• 

Incidentally,  we  can  make  the  same  change  to  the  underlying  SDT:  t u rn  t he 
construction  of  a  main  a t t r i b u te  into  actions  t h at  emit  the  elements  of  t h at 
a t t r i b u t e.  In  Fig.  5.32  we  see  t he  S DT  of Fig.  5.28  revised  to  generate  code  on 
the  fly. 

S  —> 

w h i le  ( 

C  ) 
Si 

{LI  —  newQ;  L2  =  newQ;  C.false  =  S.next; 
C.true  =  L2;  print("label",  L I );  } 
Si.next  =  LI;  print("label",  L2); 

} 

{ 

Figure  5.32:  SDT  for  on-the-fly  code  generation  for  while  statements 

5.5.3  L-Attributed  SDD's  and  LL  Parsing 

Suppose  t h at  an  L-attributed  SDD  is  based  on  an  LL-grammar  and  t h at  we  have 
converted  it  to  an  SDT  with  actions  embedded  in  the  productions,  as  described 
in  Section  5.4.5.  We  can  then  perform  the  translation  during  LL  parsing  by 
extending  the  parser  stack  to  hold  actions  and  certain  d a ta  items  needed  for 
a t t r i b u te  evaluation.  Typically,  the  d a ta  items  are  copies  of  attributes. 

In  addition  to  records  representing  terminals  and  nonterminals,  the  parser 
stack  will  hold  action-records  representing  actions  to  be  executed  and  synth-
esize-records  to  hold  the  synthesized  attributes  for  nonterminals.  We  use  the 
following  two  principles  to  manage  attributes  on  the  stack: 

•  T he  inherited  attributes  of a  nonterminal  A  are  placed  in  the  stack  record 
t h at  represents  t h at  nonterminal.  The  code  to  evaluate  these  attributes 
will  usually  be  represented  by  an  action-record  immediately  above  the 
stack  record  for  A;  in  fact,  t he  conversion  of  L-attributed  SDD's  to  SDT's 
ensures  t h at  the  action-record  will  be  immediately  above  A. 

•  T he  synthesized  attributes  for  a  nonterminal  A  are  placed  in  a  separate 
synthesize-record  t h at  is  immediately  below  the  record  for  A  on  the  stack. 

This  strategy  places  records  of  several  types  on  the  parsing  stack,  trusting  t h at 
these  variant  record  types  can  be  managed  properly  as  subclasses  of  a  "stack-
record"  class.  In  practice,  we  might  combine  several  records  into  one,  but  the 
ideas  are  perhaps  best  explained  by  separating  d a ta  used  for  different  purposes 
into  different  records. 

Action-records  contain  pointers  to  code  to  be  executed.  Actions  may  also 
appear  in  synthesize-records;  these  actions  typically  place  copies  of  the  synthe 
sized  attribute(s)  in  other  records  further  down  the  stack,  where  t he  value  of 

344 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

t h at  attribute  will  be  needed  after  the  synthesize-record  and  its  attributes  are 
popped  off  the  stack. 

Let  us  take  a  brief  look  at  LL  parsing  to  see  the  need  to  make  t e m p o r a ry 
copies  of  attributes.  From  Section  4.4.4,  a  table-driven  LL  parser  mimics  a 
leftmost  derivation.  If  w  is  the  input  t h at  has  been  matched  so  far,  then  t he 
wa,  where  S 
stack  holds  a  sequence  of  g r a m m ar  symbols  a  such  t h at  S 

is  the  start  symbol.  When  the  parser  expands  by  a  production  A  ->•  B  C,  it 
replaces  A  on  top  of  the  stack  by  B  C. 

Suppose  nonterminal  C  has  an  inherited  a t t r i b u te  C.i.  W i th  AB  C,  the 
inherited  attribute  C.i  may  depend  not  only  on  the  inherited  attributes  of A,  but 
on  all  the  attributes  of  B.  Thus,  we  may  need  to  process  B  completely  before 
C.i  can  be  evaluated.  We  therefore  save  temporary  copies  of  all  the  attributes 
needed  to  evaluate  C.i  in  the  action-record  t h at  evaluates  C.i.  Otherwise,  when 
the  parser  replaces  A  on  top  of  the  stack  by  B  C,  the  inherited  attributes  of  A 
will  have  disappeared,  along  with  its  stack  record. 

Since  the  underlying  SDD  is  L-attributed,  we  can  be  sure  t h at  the  values 
of  the  inherited  attributes  of  A  are  available  when  A  rises  to  the  top  of  the 
stack.  T he  values  will  therefore  be  available  in  time  to  be  copied  into  t he 
action-record  t h at  evaluates  the  inherited  attributes  of  C.  Furthermore,  space 
for  t he  synthesized  attributes  of  A  is  not  a  problem,  since  t he  space  is  in  the 
synthesize-record  for  A,  which  remains  on  the  stack,  below  B  and  C,  when  the 
parser  expands  by  A  -»•  B  C. 

As  B  is  processed,  we  can  perform  actions  (through  a  record just  above  B  on 
the  stack)  t h at  copy  its  inherited  attributes  for  use  by  C,  as  needed,  and  after  B 
is  processed,  t he  synthesize-record  for  B  can  copy  its  synthesized  attributes  for 
use  by  C,  if needed.  Likewise,  synthesized  attributes  of A  may  need  temporaries 
to  help  compute  their  value,  and  these  can  be  copied  to  t he  synthesize-record 
for  A  as  B  and  then  C  are  processed.  The  principle  t h at  makes  all  this  copying 
of  attributes  work  is: 

•  All  copying  takes  place  among  t he  records  t h at  are  created  during  one 
expansion  of one  nonterminal.  Thus,  each  of these  records  knows  how  far 
below  it  on  t he  stack  each  other  record  is,  and  can  write  values  into  t he 
records  below  safely. 

T he  next  example  illustrates  the  implementation  of inherited  attributes  dur 
ing  LL  parsing  by  diligently  copying  a t t r i b u te  values.  Shortcuts  or  optimiza 
tions  are  possible,  particularly  with  copy  rules,  which  simply  copy  the  value  of 
one  a t t r i b u te  into  another.  Shortcuts  are  deferred  until  Example  5.24,.  which 
also  illustrates  synthesize-records. 

E x a m p le  5 . 2 3:  This  example  implements  t he  the  SDT  of  Fig.  5.32,  which 
generates  code  on  t he  fly  for  the  while-production.  This  SDT  does  not  have 
synthesized  attributes,  except  for  dummy  attributes  t h at  represent  labels. 

Figure  5.33(a)  shows  the  situation  as  we  are  about  to  use  t he  while-produc 
tion  to  expand 5,  presumably  because  t he  lookahead  symbol  on  t he  input  is 

5.5. 

IMPLEMENTING  L-ATTRIBUTED 

SDD'S 

345 

w h i l e.  T he  record  at  the  top  of stack  is  for  S,  and  it  contains  only  the  inherited 
a t t r i b u te  S.next,  which  we  suppose  has  the  value  x.  Since  we  are  now  parsing 
top-down,  we  show  the  stack  top  at  the  left,  according  to  our  usual  convention. 

top 

next 

top 
_L_ 
while 

(a) 

Action 
snext  =  x 
LI 
L2  =  ? 

C 

false 
true  =  ? 

Action 
all  =? 
al2  =  ? 

Si 
next  =  ? 

LI  =  newQ; 
L2  =  newQ; 
stacA^op —  1].false -=  snext; 
l].true  ---L2; 
stack[top  — 
stack[top  —  3].all  =  LI; 
stack[top  —  3].al2  =  L2; 
print("label", 

LI); 

stack[top  —  l].next  —  all; 
print(" label ",a!2); 

(b) 

Figure  5.33:  Expansion  of  S  according  to  the  while-statement  production 

Figure  5.33(b)  shows  the  situation  immediately  after  we  have  expanded  S. 
There  are  action-records  in  front  of  the  nonterminals  C  and  S i,  corresponding 
to  the  actions  in  the  underlying  SDT  of  Fig.  5.32.  T he  record  for  C  has  room 
for  inherited  attributes  true  and  false,  while  the  record  for  Si  has  room  for 
a t t r i b u te  next,  as  all  S-records  must.  We  show  values  for  these  fields  as  ?, 
because  we  do  not  yet  know  their  values. 

T he  parser  next  recognizes  w h i le  and  (  on  the  input  and  pops  their  records 
off the  stack.  Now,  the  first  action  is  at  the  top,  and  it  must  be  executed.  This 
action-record  has  a  field  snext,  which  holds  a  copy  of  the  inherited  a t t r i b u te 
S.next.  W h en  S  is  popped  from  t he  stack,  t he  value  of  S.next  is  copied  into 
the  field  snext  for  use  during  the  evaluation  of  the  inherited  attributes  for  C. 
T he  code  for  the  first  action  generates  new  values  for  LI  and  L2,  which  we 
shall  suppose  are  y  and  z,  respectively.  The  next  step  is  to  make  z  the  value  of 
C.true.  T he  assignment  stack[top  —  lj.true  =  L2  is  written  knowing  it  is  only 
executed  when  this  action-record  is  at  the  top  of  stack,  so  top  —  1  refers  to  the 
record  below  it  —  the  record  for  C. 

The  first  action-record  then  copies  LI  into  field  all  in  the  second  action, 
It  also  copies  L2  into  a  field  called 
where  it  will  be  used  to  evaluate  Si.next. 
all  of  the  second  action;  this  value  is  needed  for  t h at  action-record  to  print  its 
o u t p ut  properly.  Finally,  the  first  action-record  prints  l a b el  y  to  the  output. 

T he  situation  after  completing  t he  first  action  and  popping  its  record  off 

346 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

top 

c 
false  =  x 

true  =  z 

) 

Action 
al2  =  z 
all  =  y 

Si 
next  =  ? 

stack[top  — 
l
print("label", 

j

. n e a rf  =  all; 

al2); 

Figure  5.34:  After  the  action  above  C  is  performed 

the  stack  is  shown  in  Fig.  5.34.  T he  values  of inherited  attributes  in  t he  record 
for  C  have  been  filled  in  properly,  as  have  t he  temporaries  all  and  al2  in  the 
second  action  record.  At  this  point,  C  is  expanded,  and  we  presume  t h at  the 
code  to  implement  its  test  containing  j u m ps  to  labels  x  and  z,  as  appropriate, 
is  generated.  W h en  the  C-record  is  popped  from  t he  stack,  t he  record  for  ) 
becomes  t op  and  causes  the  parser  to  check  for  )  on  its  input. 

W i th  the  action  above  Si  at  the  top  of  t he  stack,  its  code  sets  Si.next  and 
emits  l a b el  z.  W h en  t h at  is  done,  the  record  for  Si  becomes  the  t op  of  stack, 
and  as  it  is  expanded,  we  presume  it  correctly  generates  code  t h at  implements 
whatever  kind  of  statement  it  is  and  then  j u mp  to  label  y. 

• 

E x a m p le  5 . 2 4:  Now,  let  us  consider  the  same  while-statement,  but  with  a 
translation  t h at  produces  t he  o u t p ut  S.code  as  a  synthesized  a t t r i b u t e,  rather 
t h an  by  on-the-fly  generation.  In  order  to  follow  the  explanation,  it  is  useful  to 
bear  in  mind  the  following  invariant  or  inductive  hypothesis,  which  we  assume 
is  followed  for  every  nonterminal: 

•  Every  nonterminal  t h at  has  code  associated  with  it  leaves  t h at  code,  as  a 

string,  in  the  synthesize-record  just  below  it  on  the  stack. 

Assuming  this  statement  is  true,  we  shall  handle  the  while-production  so  it 
maintains  this  statement  as  an  invariant. 

Figure  5.35(a)  shows  t he  situation  just  before  S  is  expanded  using  t he  pro 
duction  for  while-statements.  At  the  t op  of t he  stack  we  see  the  record  for  5;  it 
has  a  field  for  its  inherited  a t t r i b u te  S.next,  as  in  Example  5.23.  Immediately 
below  t h at  record  is  the  synthesize-record  for  this  occurrence  of  S.  T he  latter 
has  a  field  for  S.code,  as  all  synthesize-records  for  S  must  have.  We  also  show 
it  with  some  other  fields  for  local  storage  and  actions,  since  the  S DT  for  the 
while  production  in  Fig.  5.28  is  surely  p a rt  of  a  larger  SDT. 

Our  expansion  of  5  is  based  on  the  SDT  of  Fig.  5.28,  and  it  is  shown  in 
Fig.  5.35(b).  As  a  shortcut,  during  the  expansion,  we  assume  t h at  the  inherited 
a t t r i b u te  S.next  is  assigned  directly  to  C.false,  rather  t h an  being  placed  in  the 
first  action  and  then  copied  into  the  record  for  C. 

Let  us  examine  what  each  record  does  when  it  becomes  the  t op  of  stack. 
First,  t he  w h i le  record  causes  the  token  w h i le  to  be  matched  with  the  input, 

5.5. 

IMPLEMENTING  L-ATTRIBUTED 

SDD'S 

347 

TOP 

s 

next  =  x 

TOP 

SYNTHESIZE 
5. code 
code — ? 
DATA 

ACTIONS 

(A) 

while 

ACTION 

LI 
L2  =  ? 

£REE  =  ? 

SYNTHESIZE 
Ccode 
code = ? 

Si 

next  =  ? 

stack[top — 3]. Ccode =  code; 

LI  =  NEWQ; 
L2  =  newQ; 
stack[top  —  l].true =  L2; 
stack[top — 4]. next  =  L1; 
stack[top  —  5].ll  =  LI; 
stack[top — 5] .12 =  L2; 

SYNTHESIZE 
SI.code 
code = ? 
Ccode = ? 
JI  =  ? 
12 

SYNTHESIZE 
S. code 
code = ? 
DATA 

ACTIONS 

stack[top  —  l].code  = 

"label" || 11 || Ccode 
|| "label" || 12 || code; 

(b) 

Figure  5.35:  Expansion  of  S  with  synthesized  attribute  constructed  on  the  stack 

which  it  must,  or  else  we  would  not  have  expanded  S  in  this  way.  After  w h i le 
and  (  are  popped  off  t he  stack,  the  code  for  the  action-record  is  executed.  It 
generates  values  for  LI  and  L2,  and  we  take  the  shortcut  of  copying  them 
directly  to  the  inherited  attributes  t h at  need  them:  Si.next  and  C.true.  T he 
last  two  steps  of the  action  cause  LI  and  L2  to  be  copied  into  the  record  called 
"Synthesize  Si.code." 

The  synthesize-record  for  Si  does  double  duty:  not  only  will  it  hold  the  syn 
thesized  a t t r i b u te  Si. code,  but  it  will  also  serve  as  an  action-record  to  complete 
the  evaluation  of  the  attributes  for  the  entire  production  S  -»  w h i le  (C)  Si. 
In  particular,  when  it  gets  to  the  top,  it  will  compute  t he  synthesized  a t t r i b u te 
S.code  and  place  its  value  in  the  synthesize-record  for  the  head  S. 

When  C  becomes  the  top  of  the  stack,  it  has  both  its  inherited  attributes 
computed.  By  t he  inductive  hypothesis  stated  above,  we  suppose  it  correctly 
generates  code  to  execute  its  condition  and  j u mp  to  the  proper  label.  We  also 
assume  t h at  the  actions  performed  during  the  expansion  of  C  correctly  place 
this  code  in  the  record  below,  as  the  value  of  synthesized  attribute  C.code. 

After  C  is  popped,  the  synthesize-record  for  C.code  becomes  the  top. 
Its 
code  is  needed  in  the  synthesize-record  for  Si.code,  because  t h at  is  where  we 
concatenate  all  t he  code  elements  to  form  S.code.  T he  synthesize-record  for 
C.code  therefore  has  an  action  to  copy  C.code  into  t he  synthesize-record  for 
Si.code.  After  doing  so,  the  record  for  token  )  reaches  the  top  of  stack,  and 
causes  a  check  for  )  on  the  input.  Assuming  t h at  test  succeeds,  the  record  for 
Si  becomes  t he  top  of  stack.  By  our  inductive  hypothesis,  this  nonterminal  is 

348 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

Can  We  Handle  L-Attributed  SDD's  on  LR 
Grammars? 

In  Section  5.4.1,  we  saw  t h at  every  S-attributed  SDD  on  an  LR  g r a m m ar 
can  be  implemented  during  a  bottom-up  parse.  From  Section  5.5.3  every 
L-attributed  SDD  on  an  LL  grammar  can  be  parsed  top-down.  Since  LL 
grammars  are  a  proper  subset  of  the  LR  grammars,  and  t he  S-attributed 
SDD's  are  a  proper  subset  of the  L-attributed  SDD's,  can  we  handle  every 
LR  grammar  and  L-attributed  SDD  bottom-up? 

We  cannot,  as  the  following  intuitive  argument  shows.  Suppose  we 
have  a  production  A  ->  B  C  in  an  LR-grammar,  and  there  is  an  inherited 
a t t r i b u te  B.i  t h at  depends  on  inherited  attributes  of  A.  When  we  reduce 
to  B,  we  still  have  not  seen  the  input  t h at  C  generates,  so  we  cannot 
be  sure  t h at  we  have  a  body  of  production  A  —>•  B  C.  Thus,  we  cannot 
compute  B.i  yet,  since  we  are  unsure  whether  to  use  the  rule  associated 
with  this  production. 

Perhaps  we  could  wait  until  we  have  reduced  to  C,  and  know  t h at  we 
must  reduce  B C  to  A.  However,  even  then,  we  do  not  know  the  inherited 
attributes  of  A,  because  even  after  reduction,  we  may  not  be  sure  of  t he 
production  body  t h at  contains  this  A.  We  could  reason  t h at  this  decision, 
too,  should  be  deferred,  and  therefore  further  defer  the  computation  of  B.i. 
If  we  keep  reasoning  this  way,  we  soon  realize  t h at  we  cannot  make  any 
decisions  until  t he  entire  input  is  parsed.  Essentially,  we  have  reached  t he 
strategy  of  "build  the  parse  tree  first  and  then  perform  t he  translation." 

expanded,  and  the  net  effect  is  t h at  its  code  is  correctly  constructed  and  placed 
in  the  field  for  code  in  the  synthesize-record  for  Si. 

Now,  all  the  d a ta  fields  of the  synthesize-record  for  Si  have  been  filled  in,  so 
when  it  becomes  the  top  of stack,  the  action  in  t h at  record  can  be  executed.  T he 
action  causes  the  labels  and  code  from  C. code  and  S i. code  to  be  concatenated 
in  the  proper  order.  The  resulting  string  is  placed  in  the  record  below;  t h at  is, 
in  the  synthesize-record  for  S.  We  have  now  correctly  computed  S.code,  and 
when  the  synthesize-record  for  S  becomes  the  top,  t h at  code  is  available  for 
placement  in  another  record  further  down  t he  stack,  where  it  will  eventually 
be  assembled  into  a  larger  string  of  code  implementing  a  program  element  of 
which  this  S  is  a  part. 

• 

5.5.4  Bottom-Up  Parsing  of  L-Attributed  SDD's 

We  can  do  bottom-up  every  translation  t h at  we  can  do  top-down.  More  pre 
cisely,  given  an  L-attributed  SDD  on  an  LL  grammar,  we  can  a d a pt  the  gram 
m ar  to  compute  t he  same  SDD  on  t he  new  g r a m m ar  during  an  LR  parse.  T he 
"trick"  has  three  parts: 

5.5. 

IMPLEMENTING  L-ATTRIBUTED 

SDD'S 

349 

1.  Start  with  the  SDT  constructed  as  in  Section  5.4.5,  which  places  embed 

ded  actions  before  each  nonterminal  to  compute  its  inherited  attributes 
and  an  action  at  the  end  of  the  production  to  compute  synthesized  at 
tributes. 

2.  Introduce  into  the  grammar  a  marker  nonterminal  in  place  of  each  em 
bedded  action.  Each  such  place  gets  a  distinct  marker,  and  there  is  one 
production  for  any  marker  M,  namely  M  ->  e. 

3.  Modify  the  action  a  if  marker  nonterminal  M  replaces  it  in  some  produc 

tion  A 

a  {a}  (5,  and  associate  with  M  ->  e  an  action  a'  t h at 

(a)  Copies,  as  inherited  attributes  of  M,  any  attributes  of  A  or  symbols 

of  a  t h at  action  a  needs. 

(b)  Computes  attributes  in  t he  same  way  as  a,  but  makes  those  at 

tributes  be  synthesized  attributes  of  M. 

This  change  appears  illegal,  since  typically  the  action  associated  with 
production  M  —>•  e  will  have  to  access  attributes  belonging  to  grammar 
symbols  t h at  do  not  appear  in  this  production.  However,  we  shall  imple 
ment  t he  actions  on  the  LR  parsing  stack,  so  the  necessary  attributes  will 
always  be  available  a  known  number  of  positions  down  the  stack. 

E x a m p le  5.25  :  Suppose  t h at  there  is  a  production  A  -»  B  C  in  an  LL  gram 
mar,  and  the  inherited  a t t r i b u te  B.i  is  computed  from  inherited  a t t r i b u te  A.i 
by  some  formula  B.i  =  f(A.i).  T h at  is,  the  fragment  of  an  SDT  we  care  about 
is 

A->  {B.i  = 

f{A.i);}  B  C 

We  introduce  marker  M  with  inherited  a t t r i b u te  M.i  and  synthesized  a t t r i b u te 
M.s.  T he  former  will  be  a  copy  of  A.i  and  the  latter  will  be  B.i.  T he  SDT  will 
be  written 

A  -)>  M  B  C 
M  -+  {M.i  =  A.i;  M.s  =  f{M.i);} 

Notice  t h at  the  rule  for  M  does  not  have  A.i  available  to  it,  but  in  fact  we 
shall  arrange  t h at  every  inherited  a t t r i b u te  for  a  nonterminal  such  as  A  appears 
on  the  stack  immediately  below  where  the  reduction  to  A  will  later  take  place. 
Thus,  when  we  reduce  e  to  M,  we  shall  find  A.i  immediately  below  it,  from 
where  it  may  be  read.  Also,  the  value  of  M.s,  which  is  left  on  t he  stack  along 
with  M,  is  really  B.i  and  properly  is  found  right  below  where  the  reduction  to 
B  will  later  occur. 

• 

E x a m p le  5 . 2 6:  Let  us  t u rn  the  SDT  of Fig.  5.28  into  an  SDT  t h at  can  operate 
with  an  LR  parse  of  the  revised  grammar.  We  introduce  a  marker  M  before  C 
and  a  marker  N  before  S i,  so  the  underlying  grammar  becomes 

350 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

Why  Markers  Work 

Markers  are  nonterminals  t h at  derive  only  e  and  t h at  appear  only  once 
among  all  the  bodies  of  all  productions.  We  shall  not  give  a  formal  proof 
t h a t,  when  a  grammar  is  LL,  marker  nonterminals  can  be  added  at  any 
position  in  the  body,  and  the  resulting  grammar  will  still  be  LR.  T he 
intuition,  however,  is  as  follows.  If a g r a m m ar is  LL,  then  we  can  determine 
t h at  a  string  w  on  the  input  is  derived  from  nonterminal  A,  in  a  derivation 
t h at  starts  with  production  A  —>  a,  by  seeing  only  the  first  symbol  of  w 
(or  the  following  symbol  if  w  =  e).  Thus,  if  we  parse  w  bottom-up,  then 
t he  fact  t h at  a  prefix  of  w  must  be  reduced  to  a  and  then  to  S  is  known  as 
soon  as  the  beginning  of w  appears  on  the  input.  In  particular,  if we  insert 
markers  anywhere  in  a,  the  LR  states  will  incorporate  the  fact  t h at  this 
marker  has  to  be  there,  and  will  reduce  e  to  the  marker  at  the  appropriate 
point  on  the  input. 

S 
M 
N 

-» 

w h i le  (  M  C)  N  Si 

e 
e 

Before  we  discuss  t he  actions  t h at  are  associated  with  markers  M  and  N,  let 
us  outline  the  "inductive  hypothesis"  about  where  attributes  are  stored. 

1.  Below  the  entire  body  of  the  while-production  —  t h at  is,  below  w h i le 
on  the  stack  —  will  be  the  inherited  attribute  S.next  We  may  not  know 
the  nonterminal  or  parser  state  associated  with  this  stack  record,  but  we 
can  be  sure  t h at  it  will  have  a  field,  in  a  fixed  position  of t he  record,  t h at 
holds  S.next  before  we  begin  to  recognize  what  is  derived  from  this  S. 

2.  Inherited  attributes  C.true  and  C.false  will  be  just  below  t he  stack  record 
for  C.  Since  t he  grammar  is  presumed  to  be  LL,  t he  appearance  of w h i le 
on  the  input  assures  us  t h at  the  while-production  is  the  only  one  t h at  can 
be  recognized,  so  we  can  be  sure  t h at  M  will  appear  immediately  below 
C  on  the  stack,  and  M 's  record  will  hold  t he  inherited  attributes  of  C. 

3.  Similarly,  t he  inherited  a t t r i b u te  Si.next  must  a p p e ar  immediately  below 

Si  on  t he  stack,  so  we  may  place  t h at  a t t r i b u te  in  t he  record  for  N. 

4.  T he  synthesized  a t t r i b u te  C.code  will  appear  in  t he  record  for  C.  As 
always  when  we  have  a  long  string  as  an  a t t r i b u te  value,  we  expect  t h at 
in  practice  a  pointer  to  (an  object  representing)  the  string  will  appear  in 
t he  record,  while  the  string  itself  is  outside  the  stack. 

5.  Similarly,  t he  synthesized  a t t r i b u te  Si.code  will  appear  in  the  record  for 

S i. 

5.5. 

IMPLEMENTING  L-ATTRIBUTED 

SDD'S 

351 

Let  us  follow  t he  parsing  process  for  a  while-statement.  Suppose  t h at  a 

record  holding  S.next  appears  on  t he  t op  of  t he  stack,  and  the  next  input  is 
t he  terminal  w h i l e.  We  shift  this  terminal  onto  the  stack.  It  is  then  certain 
t h at  t he  production  being  recognized  is  the  while-production,  so  the  LR  parser 
can  shift  "("  and  determine  t h at  its  next  step  must  be  to  reduce  e  to  M.  T he 
stack  at  this  time  is  shown  in  Fig.  5.36.  We  also  show  in  t h at  figure  the  action 
t h at  is  associated  with  t he  reduction  to  M.  We  create  values  for  LI  and  L2, 
which  live  in  fields  of t he  M-record.  Also  in  t h at  record  are  fields  for  C.true  and 
C.false.  These  attributes  must  be  in  the  second  and  third  fields  of  the  record, 
for  consistency  with  other  stack  records  t h at  might  appear  below  C  in  other 
contexts  and  also  must  provide  these  attributes  for  C.  The  action  completes 
by  assigning  values  to  C.true  and  C.false,  one  from  the  L2  just  generated,  and 
t he  other  by  reaching  down  the  stack  to  where  we  know  S.next  is  found. 

? 

w h i le 

( 

S.next 

t op 

M 

C.true 

C.false 
LI 

L2 

C o de  e x e c u t ed  d u r i ng 
r e d u c t i on  of  e  to  M 

LI  =  newQ; 
L2  =  newQ; 
C.true  —  L2; 
C.false  =  stack[top  —  3].next; 

Figure  5.36:  LR  parsing  stack  after  reduction  of  e  to  M 

We  presume  t h at  the  next  inputs  are properly reduced  to  C.  The  synthesized 
a t t r i b u te  C.code  is  therefore  placed  in  the  record  for  C.  This  change  to  the  stack 
is  shown  in  Fig.  5.37,  which  also  incorporates  the  next  several  records  t h at  are 
later  placed  above  C  on  the  stack. 

w h i le 

( 

M 

C 

) 

N 

t op 

Si 

C.  true  C. code 

Si.next 

Si.code 

? 

S.next 

C.false 
LI 

L2 

Figure  5.37:  Stack  just  before  reduction  of  the  while-production  body  to  S 

Continuing  with  the  recognition  of  the  while-statement,  the  parser  should 
next  find  " )"  on  t he  input,  which  it  pushes  onto  t he  stack  in  a  record  of  its 
own.  At  t h at  point,  the  parser,  which  knows  it  is  working  on  a  while-statement 
because  t he  g r a m m ar  is  LL,  will  reduce  e  to  N.  T he  single  piece  of  d a ta  asso 
ciated  with  N  is  the  inherited  a t t r i b u te  Si.next.  Note  t h at  this  a t t r i b u te  needs 

352 

CHAPTER  5. 

SYNTAX-DIRECTED  TRANSLATION 

to  be  in  the  record  for  N  because  t h at  will  be  just  below  the  record  for  Si.  T he 
code  t h at  is  executed  to  compute  the  value  of  Si.next  is 

Si.next =  stack[top  —  3].LI; 

This  action  reaches  three  records  below  TV,  which  is  at  the  top  of  stack  when 
the  code  is  executed,  and  retrieves  the  value  of  L I. 

Next,  the  parser  reduces  some  prefix  of  t he  remaining  input  to  S,  which 
we  have  consistently  referred  to  as  Si  to  distinguish  it  from  t he  S  at  the  head 
of  the  production.  T he  value  of  Si.code  is  computed  and  appears  in  t he  stack 
record  for  Si.  This  step  takes  us  to  the  condition  t h at  is  illustrated  in  Fig.  5.37. 
At  this  point,  the  parser  will  reduce  everything  from  w h i le  to  Si  to  S.  T he 

code  t h at  is  executed  during  this  reduction  is: 

tempCode = l a b el || stack[top — 4].LI || stack[top — 3].code || 

l a b el ||  stack[top — 4].L2  ||  stack[top].code; 

top = top — 5; 
stack[top].code = tempCode; 

T h at  is,  we  construct  the  value  of S.code  in  a  variable  tempCode.  T h at  code  is 
the  usual,  consisting  of  the  two  labels  LI  and  L2,  the  code  for  C  and  the  code 
for  Si.  T he  stack  is  popped,  so  S  appears  where  w h i le  was.  T he  value  of  the 
code  for  S  is  placed  in  t he  code  field  of t h at  record,  where  it  can  be  interpreted 
as  the  synthesized  attribute  S.code.  Note  t h at  we  do  not  show,  in  any  of  this 
discussion,  the  manipulation  of LR  states,  which  must  also  appear  on  t he  stack 
in  the  field  t h at  we  have  populated  with  grammar  symbols. 

• 

5.5.5  Exercises  for  Section  5.5 

E x e r c i se  5 . 5 . 1:  Implement  each  of your  SDD's  of Exercise  5.4.4  as  a recursive-
descent  parser  in  t he  style  of  Section  5.5.1. 

E x e r c i se  5 . 5 . 2:  Implement  each  of your  SDD's  of Exercise  5.4.4  as  a recursive-
descent  parser  in  t he  style  of  Section  5.5.2. 

E x e r c i se  5 . 5 . 3:  Implement  each  of  your  SDD's  of  Exercise  5.4.4  with  an  LL 
parser  in  the  style  of  Section  5.5.3,  with  code  generated  "on  t he  fly." 

E x e r c i se  5 . 5 . 4:  Implement  each  of  your  SDD's  of  Exercise  5.4.4  with  an  LL 
parser  in  the  style  of  Section  5.5.3,  but  with  code  (or  pointers  to  t he  code) 
stored  on  t he  stack. 

E x e r c i se  5.5.5  :  Implement  each  of  your  SDD's  of  Exercise  5.4.4  with  an  LR 
parser  in  t he  style  of  Section  5.5.4. 

E x e r c i se  5 . 5 . 6: 
Implement  your  SDD  of  Exercise  5.2.4  in  the  style  of  Sec 
tion  5.5.1.  Would  an  implementation  in  the  style  of  Section  5.5.2  be  any  differ 
ent? 

6. 

SUMMARY  OF  CHAPTER  5 

353 

.6  Summary  of  Chapter  5 

4 

Inherited  and  Synthesized  Attributes:  Syntax-directed  definitions  may  use 
two  kinds  of  attributes.  A  synthesized  a t t r i b u te  at  a  parse-tree  node  is 
computed  from  attributes  at  its  children.  An  inherited  a t t r i b u te  at  a  node 
is  computed  from  attributes  at  its  parent  a n d / or  siblings. 

•  Dependency  Graphs:  Given  a  parse  tree  and  an  SDD,  we  draw  edges 
among  the  a t t r i b u te  instances  associated  with  each  parse-tree  node  to 
denote  t h at  t he  value  of t he  a t t r i b u te  at  t he  head  of t he  edge  is  computed 
in  terms  of  t he  value  of  the  a t t r i b u te  at  the  tail  of  t he  edge. 

•  Cyclic  Definitions: 

In  problematic  SDD's,  we  find  t h at  there  are  some 
parse  trees  for  which  it  is  impossible  to  find  an  order  in  which  we  can 
compute  all  the  attributes  at  all  nodes.  These  parse  trees  have  cycles  in 
their  associated  dependency  graphs. 
It  is  intractable  to  decide  whether 
an  SDD  has  such  circular  dependency  graphs. 

4  S-Attributed  Definitions: 

In  an  S-attributed  SDD,  all  attributes  are  syn 

thesized. 

4  L-Attributed  Definitions: 

In  an  L-attributed  SDD,  attributes  may  be  in 
herited  or  synthesized.  However,  inherited  attributes  at  a  parse-tree  node 
may  depend  only  on  inherited  attributes  of  its  parent  and  on  (any)  at 
tributes  of  siblings  to  its  left. 

•  Syntax  Trees:  Each  node  in  a  syntax  tree  represents  a  construct;  the  chil 
dren  of  t he  node  represent  the  meaningful  components  of  the  construct. 

4 

Implementing  S-Attributed  SDD's:  An  S-attributed  definition  can  be  im 
plemented  by  an  SDT  in  which  all  actions  are  at  the  end  of the  production 
(a  "postfix"  SDT).  T he  actions  compute  the  synthesized  attributes  of the 
production  head  in  terms  of  synthesized  attributes  of  t he  symbols  in  the 
body. 
If  the  underlying  grammar  is  LR,  then  this  S DT  can  be  imple 
mented  on  the  LR  parser  stack. 

4  Eliminating  Left  Recursion  From  SDT's: 

If  an  SDT  has  only  side-effects 
(no  attributes  are  computed),  then  the  standard  left-recursion-elimination 
algorithm  for  grammars  allows  us  to  carry  t he  actions  along  as  if  they 
were  terminals.  When  attributes  are  computed,  we  can  still  eliminate  left 
recursion  if  t he  SDT  is  a  postfix  S D T. 

4 

by  Recursive-Descent  Parsing: 

Implementing  L-attributed  SDD's 
have  an  L-attributed  definition  on  a  top-down  parsable  grammar,  we  can 
build  a  recursive-descent  parser  with  no  backtracking  to  implement  t he 
Inherited  attributes  become  arguments  of  t he  functions  for 
translation. 
their  nonterminals,  and  synthesized  attributes  are  returned  by  t h at  func 
tion. 

If  we 

354 

• 

CHAPTER 

5. 

SYNTAX-DIRECTED 

TRANSLATION 

Implementing  L-Attributed  SDD's  on  an  LL  Grammar:  Every  L-attribut 
ed  definition  with  an  underlying  LL  grammar  can  be  implemented  along 
with  t he  parse.  Records  to  hold  the  synthesized  attributes  for  a  non 
terminal  are  placed  below  t h at  nonterminal  on  t he  stack,  while  inherited 
attributes  for  a  nonterminal  are  stored  with  t h at  nonterminal  on  t he  stack. 
Action  records  are  also  placed  on  t he  stack  to  compute  attributes  at  t he 
appropriate  time. 

• 

Implementing  L-Attributed  SDD's  on  an  LL  Grammar,  Bottom-Up:  An 
L-attributed  definition  with  an  underlying  LL  g r a m m ar  can  be  converted 
to  a  translation  on  an  LR  grammar  and  the  translation  performed  in  con 
nection  with  a  bottom-up  parse.  T he  grammar  transformation  introduces 
"marker"  nonterminals  t h at  appear  on  the  bottom-up  parser's  stack  and 
hold  inherited  attributes  of  the  nonterminal  above  it  on  t he  stack.  Syn 
thesized  attributes  are  kept  with  their  nonterminal  on  t he  stack. 

5.7  References  for  Chapter  5 

Syntax-directed  definitions  are  a  form  of inductive  definition  in  which  t he  induc 
tion  is  on  t he  syntactic  structure.  As  such  they  have  long  been  used  informally 
in  mathematics.  Their  application  to  programming  languages  came  with  the 
use  of  a  g r a m m ar  to  structure  t he  Algol  60  report. 

T he  idea  of a  parser  t h at  calls  for  semantic  actions  can  be  found  in  Samelson 
and  Bauer  [8]  and  Brooker  and  Morris  [1]. 
Irons  [2]  constructed  one  of  t he 
first  syntax-directed  compilers,  using  synthesized  attributes.  The  class  of  L-
attributed  definitions  comes  from  [6]. 

Inherited  attributes,  dependency  graphs,  and  a  test  for  circularity  of  SDD's 

(that  is,  whether  or  not  there  is  some  parse  tree  with  no  order  in  which  t he  at 
tributes  can  be  computed)  are  from  K n u th  [5].  Jazayeri,  Ogden,  and  Rounds  [3] 
showed  t h at  testing  circularity  requires  exponential  time,  as  a  function  of  t he 
size  of  t he  SDD. 

Parser  generators  such  as  Yacc  [4]  (see  also  the  bibliographic  notes  in  Chap 

ter  4)  support  attribute  evaluation  during  parsing. 

T he  survey  by  Paakki  [7]  is  a  starting  point  for  accessing  t he  extensive 

literature  on  syntax-directed  definitions  and  translations. 

1.  Brooker,  R.  A.  and  D.  Morris,  "A  general  translation  program  for  phrase 

structure  languages,"  J.  ACM  9:1  (1962),  pp.  1-10. 

2.  Irons,  E.  T.,  "A  syntax  directed  compiler  for  Algol  60,"  Comm.  ACM 4:1 

(1961),  pp.  51-55. 

3.  Jazayeri,  M.,  W.  F.  Odgen,  and  W.  C.  Rounds,  "The  intrinsic  expo 

nential  complexity  of  the  circularity  problem  for  a t t r i b u te  grammars," 
Comm.  ACM  18:12  (1975),  pp.  697-706. 

5.7. 

REFERENCES  FOR  CHAPTER  5 

355 

4.  Johnson,  S.  C,  "Yacc  —  Yet  Another  Compiler  Compiler,"  Computing 
Science  Technical  Report  32,  Bell  Laboratories,  Murray  Hill,  NJ,  1975. 
Available  at  h t t p : / / d i n o s a u r . c o m p i l e r t o o l s . n e t / y a c c/  . 

5.  Knuth,  D.E.,  "Semantics  of  context-free  languages,"  Mathematical  Sys 
See  also  Mathematical  Systems 

(1968),  pp.  127-145. 

tems  Theory  2:2 
Theory  5:1  (1971),  pp.  95-96. 

6.  Lewis,  P.  M.  II,  D.  J.  Rosenkrantz,  and  R.  E.  Stearns,  "Attributed  trans 
lations,"  J.  Computer  and  System  Sciences  9:3  (1974),  pp.  279-307. 

7.  Paakki,  J.,  "Attribute  grammar  paradigms  —  a  high-level  methodology  in 
language  implementation,"  Computing  Surveys  27:2  (1995)  pp.  196-255. 

8.  Samelson,  K.  and  F.  L.  Bauer,  "Sequential  formula  translation,"  Comm. 

ACM  3:2  (1960),  p p.  76-83. 

Chapter  6 

Intermediate-Code 
Generation 

In  the  analysis-synthesis  model  of  a  compiler,  t he  front  end  analyzes  a  source 
program  and  creates  an  intermediate  representation,  from  which  the  back  end 
generates  target  code.  Ideally,  details  of the  source  language  are  confined  to  the 
front  end,  and  details  of  t he  target  machine  to  t he  back  end.  W i th  a  suitably 
defined  intermediate  representation,  a  compiler  for  language  i  and  machine  j 
can  then  be  built  by  combining  the  front  end  for  language  i  with  the  back 
end  for  machine  j.  This  approach  to  creating  suite  of  compilers  can  save  a 
considerable  amount  of  effort:  m  x  n  compilers  can  be  built  by  writing  just  m 
front  ends  and  n  back  ends. 

This  chapter  deals  with  intermediate  representations,  static  type  checking, 
and  intermediate  code  generation. 
For  simplicity,  we  assume  t h at  a  com 
piler  front  end  is  organized  as  in  Fig.  6.1,  where  parsing,  static  checking,  and 
intermediate-code  generation  are  done  sequentially;  sometimes  they  can  be  com 
bined  and  folded  into  parsing.  We  shall  use  the  syntax-directed  formalisms  of 
Chapters  2  and  5  to  specify  checking  and  translation.  Many  of  t he  translation 
schemes  can  be  implemented  during  either  bottom-up  or  top-down  parsing,  us 
ing  t he  techniques  of  Chapter  5.  All  schemes  can  be  implemented  by  creating 
a  syntax  tree  and  then  walking  the  tree. 

Parser 
Parser 

Static 
Checker 

Intermediate 
Intermediate 

Code 
Code 
Generator 
Generator 

intermediate 
code 

Code 
Generator 

front  end 

back  end 

Figure  6.1:  Logical  structure  of  a  compiler  front  end 

Static  checking  includes  type  checking,  which  ensures  t h at  operators  are  ap 
plied  to  compatible  operands.  It  also  includes  any  syntactic  checks  t h at  remain 

357 

358 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

after  parsing.  For  example,  static  checking  assures  t h at  a  break-statement  in 
C  is  enclosed  within  a  while-,  for-,  or  switch-statement;  an  error  is  reported  if 
such  an  enclosing  statement  does  not  exist. 

The  approach  in  this  chapter  can  be  used  for  a  wide  range  of  intermediate 
representations,  including  syntax  trees  and  three-address  code,  both  of  which 
were  introduced  in  Section  2.8.  T he  term  "three-address  code"  comes  from 
instructions  of  the  general  form  x  =  y  op  z  with  three  addresses:  two  for  the 
operands  y  and  z  and  one  for  t he  result  x. 

In  the  process  of translating  a  program  in  a  given  source  language  into  code 
for  a  given  target  machine,  a  compiler  may  construct  a  sequence  of intermediate 
representations,  as  in  Fig.  6.2.  High-level representations  are  close  to  the  source 
language  and  low-level  representations  are  close  to  the  target  machine.  Syntax 
trees  are  high  level;  they  depict  the  natural  hierarchical  structure  of t he  source 
program  and  are  well  suited  to  tasks  like  static  type  checking. 

Source 
Program 

High  Level 

Low  Level 

— I n t e r m e d i a te  —»- • • •  —»-  I n t e r m e d i a t e-
Representation 

Representation 

Target 
Code 

Figure  6.2:  A  compiler  might  use  a  sequence  of  intermediate  representations 

A  low-level  representation  is  suitable  for  machine-dependent  tasks  like  reg 
ister  allocation  and  instruction  selection.  Three-address  code  can  range  from 
high-  to  low-level,  depending  on  t he  choice  of  operators.  For  expressions,  t he 
differences  between  syntax  trees  and  three-address  code  are  superficial,  as  we 
shall  see  in  Section  6.2.3.  For  looping  statements,  for  example,  a  syntax  tree 
represents  the  components  of  a  statement,  whereas  three-address  code  contains 
labels  and  j u mp  instructions  to  represent  t he  flow  of  control,  as  in  machine 
language. 

The  choice  or  design  of  an  intermediate  representation  varies  from  compiler 
to  compiler.  An  intermediate  representation  m ay  either  be  an  actual  language 
or  it  may  consist  of  internal  d a ta  structures  t h at  are  shared  by  phases  of  t he 
compiler.  C  is  a  programming  language,  yet  it  is  often  used  as  an  intermediate 
form  because  it  is  flexible,  it  compiles  into  efficient  machine  code,  and  its  com 
pilers  are  widely  available.  The  original  C ++  compiler  consisted  of  a  front  end 
t h at  generated  C,  treating  a  C  compiler  as  a  back  end. 

6.1  Variants  of  Syntax  Trees 

Nodes  in  a  syntax  tree  represent  constructs  in  the  source  program;  the  children 
of  a  node  represent  the  meaningful  components  of  a  construct.  A  directed 
acyclic  graph  (hereafter  called  a  DAG)  for  an  expression  identifies  the  common 
subexpressions  (subexpressions  t h at  occur  more  t h an  once)  of  t he  expression. 
As  we  shall  see  in  this  section,  DAG's  can  be  constructed  by  using  t he  same 
techniques  t h at  construct  syntax  trees. 

6.1. 

VARIANTS  OF  SYNTAX  TREES 

359 

6.1.1  Directed  Acyclic  Graphs  for  Expressions 

Like  the  syntax  tree  for  an  expression,  a  DAG  has  leaves  corresponding  to 
atomic  operands  and  interior  codes  corresponding  to  operators.  The  difference 
is  t h at  a  node  N  in  a  DAG  has  more  t h an  one  parent  if  N  represents  a  com 
mon  subexpression;  in  a  syntax  tree,  the  tree  for  the  common  subexpression 
would  be  replicated  as  many  times  as  the  subexpression  appears  in  the  original 
expression.  Thus,  a  DAG  not  only  represents  expressions  more  succinctly,  it 
gives  t he  compiler  important  clues  regarding  the  generation  of  efficient  code  to 
evaluate  t he  expressions. 

E x a m p le  6 . 1:  Figure  6.3  shows  the  DAG  for  the  expression 

a  +  a  *  (b  -  c)  +  (b  -  c)  *  d 

The  leaf  for  a  has  two  parents,  because  a  appears  twice  in  the  expression. 
More  interestingly,  the  two  occurrences  of  t he  common  subexpression  b -c  are 
represented  by  one  node,  the  node  labeled  —.  T h at  node  has  two  parents, 
representing  its  two  uses  in  the  subexpressions  a* ( b - c)  and  ( b - c ) * d.  Even 
though  b  and  c  appear  twice  in  the  complete  expression,  their  nodes  each  have 
one  parent,  since  both  uses  are  in  the  common  subexpression  b - c. 

• 

Figure  6.3:  Dag  for  the  expression  a + a *  (b  -  c)  +  ( b - c)  *  d 

T he  SDD  of  Fig.  6.4  can  construct  either  syntax  trees  or  DAG's. 

It  was 
used  to  construct  syntax  trees  in  Example  5.11,  where  functions  Leaf  and  Node 
created  a  fresh  node  each  time  they  were  called. 
It  will  construct  a  DAG  if, 
before  creating  a  new  node,  these  functions  first  check  whether  an  identical  node 
already  exists.  If  a  previously  created  identical  node  exists,  the  existing  node 
is  returned.  For  instance,  before  constructing  a  new  node,  Node(op,  left,  right) 
we  check  whether  there  is  already  a  node  with  label  op,  and  children  left  and 
right,  in  t h at  order.  If  so,  Node  returns  the  existing  node;  otherwise,  it  creates 
a  new  node. 

E x a m p le  6 . 2:  T he  sequence  of  steps  shown  in  Fig.  6.5  constructs  the  DAG 
in  Fig.  6.3,  provided  Node  and  Leaf  return  an  existing  node,  if  possible,  as 

360 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

PR O D U C T I ON 

SE M A N T IC  RU L ES 

E-> 

E±+T 

E.node  = 

n ew 

Node(''+',E\.node,T.node) 

E-^Ei-T 

E->T 

E.node  =  n ew  Node('  —',  E\.node,T.node) 

E.node  =  T.node 

T.node 

E.node 

T- Md 

T.node 

n ew  Leaf  (id,  id.  entry) 

T  —>  n um 

T.  node 

n ew 

Leaf  (num,  mmi.val) 

1) 

2) 

3) 

4) 

5) 

6) 

Figure  6.4:  Syntax-directed  definition  to  produce  syntax  trees  or  DAG's 

pi  —  Leaf (id,  entry-a) 
pi  =  Leaf (id,  entry-a)  =  p\ 

1) 
2) 
3)  P3  =  Leaf (id,  entry-b) 
4)  PA  —  Leaf (id,  entry-c) 
Ps  =  Node('-',P3,PA) 
5) 
p6  =  Node{'*',pi,ps) 
6) 
7)  Pi  =  Node('+'\pi,p%) 
ps  =  Leaf (id,  entry-b)  =  p3 
8) 
9)  PQ  =  Leaf (id,  entry-c)  =  p^ 
10) 
=  Node('-',p3,p4)  =P5 
11)  Pn  =  Leaf  (id,  entry-d) 
12) 
pi2  =  JVode('*',pB,pii) 
pis 

Node('+',p7,pi2) 

pio 

= 

13) 

Figure  6.5:  Steps  for  constructing  t he  DAG  of  Fig.  6.3 

discussed  above.  We  assume  t h at  entry-a  points  to  t he  symbol-table  entry  for 
a,  and  similarly  for  t he  other  identifiers. 

When  the  call  to  Leaf (id,  entry-a)  is  repeated  at  step  2,  t he  node  created 
by  the  previous  call  is  returned,  so  p2  =  Pi •  Similarly,  t he  nodes  returned  at 
steps  8  and  9  are  t he  same  as  those  returned  at  steps  3  and  4  (i.e.,  ps  =  p3 
and  PQ  =  p^).  Hence  t he  node  returned  at  step  10  must  be  t he  same  at  t h at 
returned  at  step  5;  i.e.,  pio  =  P5- 

• 

6.1.2  The  Value-Number  Method  for  Constructing  DAG's 

Often,  the  nodes  of  a  syntax  tree  or  DAG  are  stored  in  an  array  of  records,  as 
suggested by  Fig.  6.6.  Each  row  of t he  array  represents  one  record,  and  therefore 
one  node.  In  each  record,  the  first  field  is  an  operation  code,  indicating  the  label 
of  the  node. 
In  Fig.  6.6(b),  leaves  have  one  additional  field,  which  holds  t he 
lexical  value  (either  a  symbol-table  pointer  or  a  constant,  in  this  case),  and 

6.1. 

VARIANTS  OF  SYNTAX  TREES 

361 

interior  nodes  have  two  additional  fields  indicating  the  left  and  right  children. 

+ 

i 

10 

to  entry 
for  i 

; 

— 

10 
;  l  1  2 
'  3 
!  i 

id 

1 
2  n um 
+ 
= 

4 

3 

5 

i 

(a)  DAG 

(b)  Array. 

Figure  6.6:  Nodes  of  a  DAG  for  i  =  i  +  10  allocated  in  an  array 

In  this  array,  we  refer  to  nodes  by  giving  t he  integer  index  of  t he  record 
for  t h at  node  within  t he  array.  This  integer  historically  has  been  called  the 
value  number  for  the  node  or  for  the  expression  represented  by  the  node.  For 
instance,  in  Fig.  6.6,  the  node  labeled -I-  has  value  number  3,  and  its  left  and 
right  children  have  value  numbers  1  and  2,  respectively.  In  practice,  we  could 
use  pointers  to  records  or  references  to  objects  instead  of  integer  indexes,  but 
we  shall  still  refer  to  the  reference  to  a  node  as  its  "value  number." 
If  stored 
in  an  appropriate  d a ta  structure,  value  numbers  help  us  construct  expression 
DAG's  efficiently;  the  next  algorithm  shows  how. 

Suppose  t h at  nodes  are  stored  in  an  array,  as  in  Fig.  6.6,  and  each  node  is 
referred  to  by  its  value  number.  Let  t he  signature  of  an  interior  node  be  the 
triple  (op,/,r),  where  op  is  the  label,  I  its  left  child's  value  number,  and  r  its 
right  child's  value  number.  A  unary  operator  may  be  assumed  to  have  r  =  0-

A l g o r i t hm  6.3 
DAG. 

T he  value-number  method  for  constructing  the  nodes  of  a 

I N P U T:  Label  op,  node  /,  and  node  r. 

O U T P U T:  T he  value  number  of  a  node  in  the  array  with  signature  (op,  l,r). 

M E T H O D:  Search  the  array  for  a  node  M  with  label  op,  left  child  I,  and  right 
child  r.  If there  is  such  a  node,  return  t he  value  number  of  M.  If  not,  create  in 
the  array  a  new  node  N  with  label  op,  left  child  I,  and  right  child  r,  and  return 
its  value  number. 

• 

While  Algorithm  6.3  yields  t he  desired  output,  searching  the  entire  array 
every  time  we  are  asked  to  locate  one  node  is  expensive,  especially  if  t he  array 
holds  expressions  from  an  entire  program.  A  more  efficient  approach  is  to  use  a 
hash  table,  in  which  the  nodes  are  put  into  "buckets,"  each  of  which  typically 
will  have  only  a  few  nodes.  T he  hash  table  is  one  of  several  d a ta  structures 
t h at  support  dictionaries  efficiently.1  A  dictionary  is  an  abstract  d a ta  type  t h at 

1See  Aho,  A.  V.,  J.  E.  Hopcroft,  and  J.  D.  Ullman,  Data  Structures  and  Algorithms, 

Addison-Wesley,  1983,  for  a  discussion  of  data  structures  supporting  dictionaries. 

362 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

allows  us  to  insert  and  delete  elements  of  a  set,  and  to  determine  whether  a 
given  element  is  currently  in  the  set.  A  good  d a ta  structure  for  dictionaries, 
such  as  a  hash  table,  performs  each  of these  operations  in  time  t h at  is  constant 
or  close  to  constant,  independent  of  t he  size  of  t he  set. 

To  construct  a  hash  table  for  the  nodes  of  a  DAG,  we  need  a  hash  function 
h  t h at  computes  the  index  of  the  bucket  for  a  signature  (op,  I, r),  in  a  way  t h at 
distributes  t he  signatures  across  buckets,  so  t h at  it  is  unlikely  t h at  any  one 
bucket  will  get  much  more  t h an  a  fair  share  of  the  nodes.  T he  bucket  index 
h(op,  I, r)  is  computed  deterministically  from  op,  I,  and  r,  so  t h at  we  may  repeat 
t he  calculation  and  always  get  to  t he  same  bucket  index  for  node  (op,  I,  r). 

T he  buckets  can  be  implemented  as  linked  lists,  as  in  Fig.  6.7.  An  array, 
indexed  by  hash  value,  holds  the  bucket  headers,  each  of  which  points  to  t he 
first  cell  of  a  list.  Within  the  linked  list  for  a  bucket,  each  cell  holds  t he  value 
number  of  one  of  t he  nodes  t h at  hash  to  t h at  bucket.  T h at  is,  node  (op,l,r) 
can  be  found  on  the  list  whose  header  is  at  index  h(op,l,r)  of  the  array. 

Array  of  bucket 
headers  indexed 
by  hash  value 

0 

20 

List  elements 
representing  nodes 

25 

Figure  6.7:  D a ta  structure  for  searching  buckets 

Thus,  given  t he  input  node  op,  I,  and  r,  we  compute  the  bucket  index 
h(op,l,r)  and  search  t he  list  of  cells  in  this  bucket  for  the  given  input  node. 
Typically,  there  are  enough  buckets  so  t h at  no  list  has  more  t h an  a  few  cells. 
We  may  need  to  look  at  all  the  cells  within  a  bucket,  however,  and  for  each 
value  number  v  found  in  a  cell,  we  must  check  whether  t he  signature  (op,l,r) 
of  t he  input  node  matches  the  node  with  value  number  v  in  the  list  of  cells  (as 
in  Fig.  6.7).  If  we  find  a  match,  we  return  v.  If  we  find  no  match,  we  know 
no  such  node  can  exist  in  any  other  bucket,  so  we  create  a  new  cell,  add  it  to 
the  list  of  cells  for  bucket  index  h(op,  l,r),  and  return  the  value  number  in  t h at 
new  cell. 

6.1.3  Exercises  for  Section  6.1 

E x e r c i se  6 . 1 . 1:  Construct  t he  DAG  for  the  expression 

((a;  +  y)-  {{x  +  y)*(x-  y)))  +  ((x  +  y)  *  (x  -  y)) 

6.2. 

THREE-ADDRESS  CODE 

363 

E x e r c i se  6 . 1 . 2:  Construct  the  DAG  and  identify  the  value  numbers  for  t he 
subexpressions  of the  following  expressions,  assuming  +  associates  from  the  left. 

a)  a  +  b+  (a  +  b). 

b)  a  +  b +  a  +  b. 

c)  a  +  a  +  ((fl  +  a  +  a  +  (a  +  a  +  a  +  a ) ). 

6.2  Three-Address  Code 

In  three-address  code,  there  is  at  most  one  operator  on  the  right  side  of  an 
instruction;  t h at  is,  no  built-up  arithmetic  expressions  are  permitted.  Thus  a 
source-language  expression  like  x+y*z  might  be  translated  into  the  sequence  of 
three-address  instructions 

ti  =  y  *  z 
t2  =  x  +  ti 

where  ti  and  t2  are  compiler-generated  temporary  names.  This  unraveling  of 
multi-operator  arithmetic  expressions  and  of  nested  flow-of-control  statements 
makes  three-address  code  desirable  for  target-code  generation  and  optimization, 
as  discussed  in  Chapters  8  and  9.  The  use  of  names  for  the  intermediate  values 
computed  by  a  program  allows  three-address  code  to  be  rearranged  easily. 

E x a m p le  6 . 4:  Three-address  code  is  a  linearized  representation  of  a  syntax 
tree  or  a  DAG  in  which  explicit  names  correspond  to  the  interior  nodes  of  the 
graph.  T he  DAG  in  Fig.  6.3  is  repeated  in  Fig.  6.8,  together  with  a  correspond 
ing  three-address  code  sequence. 

• 

ti  =  b 
t2  =  a  * 

-  c 

ti 

b 

c 

(a)  DAG 

t3  =  a  +  t2 

t4  = 

ti  *  d 

t5  = 

t3  + 

t4 

(b)  Three-address  code 

Figure  6.8:  A  DAG  and  its  corresponding  three-address  code 

364 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

6.2.1  Addresses  and  Instructions 

Three-address  code  is  built  from  two  concepts:  addresses  and  instructions.  In 
object-oriented  terms,  these  concepts  correspond  to  classes,  and  t he  various 
kinds  of  addresses  and  instructions  correspond  to  appropriate  subclasses.  Al 
ternatively,  three-address  code  can  be  implemented  using  records  with  fields 
for  the  addresses;  records  called  quadruples  and  triples  are  discussed  briefly  in 
Section  6.2.2. 

An  address  can  be  one  of  the  following: 

•  A  name.  For  convenience,  we  allow  source-program  names  to  appear  as 
addresses  in  three-address  code. 
In  an  implementation,  a  source  name 
is  replaced  by  a  pointer  to  its  symbol-table  entry,  where  all  information 
about  the  name  is  kept. 

•  A  constant.  In  practice,  a  compiler  must  deal  with  many  different  types 
of  constants  and  variables.  Type  conversions  within  expressions  are  con 
sidered  in  Section  6.5.2. 

•  A  compiler-generated  temporary. 

It  is  useful,  especially  in  optimizing  com 
pilers,  to  create  a  distinct  name  each  time  a  temporary  is  needed.  These 
temporaries  can  be  combined,  if  possible,  when  registers  are  allocated  to 
variables. 

We  now  consider  the  common  three-address  instructions  used  in  the  rest  of 
this  book.  Symbolic  labels  will  be  used  by  instructions  t h at  alter  the  flow  of 
control.  A  symbolic  label  represents  the  index  of  a  three-address  instruction  in 
the  sequence  of  instructions.  Actual  indexes  can  be  substituted  for  the  labels, 
either  by  making  a  separate  pass  or  by  "backpatching,"  discussed  in  Section  6.7. 
Here  is  a  list  of  the  common  three-address  instruction  forms: 

1.  Assignment  instructions  of  the  form  x  =  y  op  z,  where  op  is  a  binary 

arithmetic  or  logical  operation,  and  x,  y,  and  z  are  addresses. 

2.  Assignments  of t he  form  x  =  op  y,  where  op  is  a  unary  operation.  Essen 
tial  unary  operations  include  unary  minus,  logical  negation,  shift  opera 
tors,  and  conversion  operators  t h a t,  for  example,  convert  an  integer  to  a 
floating-point  number. 

3.  Copy  instructions  of  the  form  x  =  y,  where  x  is  assigned  the  value  of  y. 

4.  An  unconditional  j u mp  g o to  L.  T he  three-address  instruction  with  label 

L  is  t he  next  to  be  executed. 

5.  Conditional  jumps  of the  form  if  x  g o to  L  and  if F a l se  x  g o to  L.  These 
instructions  execute  the  instruction  with  label  L  next  if  x  is  t r ue  and 
false,  respectively.  Otherwise,  t he  following  three-address  instruction  in 
sequence  is  executed  next,  as  usual. 

6.2. 

THREE-ADDRESS  CODE 

365 

6.  Conditional  j u m ps  such  as  if  x  relop  y  g o to  L,  which  apply  a  relational 
to  x  and  y,  and  execute  the  instruction  with 
operator  (<,  ==,  >=,  etc.) 
label  L  next  if  x  stands  in  relation  relop  to  y. 
If  not,  the  three-address 
instruction  following  if  x  relop  y  g o to  L  is  executed  next,  in  sequence. 

7.  Procedure  calls  and  returns  are  implemented  using  the  following  instruc 
tions:  param  x  for  parameters;  c a l l p,  n  and  y  =  c a l l p,  n  for  procedure 
and  function  calls,  respectively;  and  r e t u rn  y,  where  y,  representing  a 
returned  value,  is  optional.  Their  typical  use  is  as  t he  sequence  of  three-
address  instructions 

param  x± 
param  x2 

param 
xn 
c a ll  p,  n 

generated  as  part  of  a  call  of  the  procedure  p(x\,x2,  •  •  •  ,xn).  The  in 
teger  n,  indicating  the  number  of  actual  parameters  in  " c a ll  p,  n,"  is 
not  redundant  because  calls  can  be  nested.  T h at  is,  some  of  the  first 
param  statements  could  be  parameters  of  a  call  t h at  comes  after  p  returns 
its  value;  t h at  value  becomes  another  parameter  of  the  later  call.  T he 
implementation  of  procedure  calls  is  outlined  in  Section  6.9. 

• 

8.  Indexed  copy  instructions  of  the  form  x  = y[il  and  xlil  = y.  T he  instruc-
tion  x = y lil  sets  x  to  the  value  in  the  location  i  memory  units  beyond 
^ 
location  y.  The  instruction  x[i"]  =y  sets  t he  contents  of  t he  location  i 
units  beyond  x  to  t he  value  of  y. 

9.  Address  and  pointer  assignments  of the  form  x  =  &y,  x  =  * y,  and  * x  -  y. 
The  instruction  x  =  ky  sets  the  r-value  of  x  to  be  the  location  (/-value) 
of  y?  Presumably  y  is  a  name,  perhaps  a  temporary,  t h at  denotes  an 
expression  with  an  /-value  such  as  A [ i]  [ j ],  and  #  is  a  pointer  name  or 
temporary. 
In  the  instruction  x  =  *y,  presumably  y  is  a  pointer  or  a 
t e m p o r a ry  whose  r-value  is  a  location.  T he  r-value  of  x  is  m a de  equal 
to  the  contents  of  t h at  location.  Finally,  * x  =  y  sets  the  r-value  of  t he 
object  pointed  to  by  x  to  the  r-value  of  y. 

E x a m p le  6 . 5:  Consider  the  statement 

do  i  =  i + 1;  w h i le  ( a [ i]  <  v ); 

Two  possible  translations  of  this  statement  are  shown  in  Fig.  6.9.  T he  transla 
tion  in  Fig.  6.9  uses  a  symbolic  label  L,  attached  to  the  first  instruction.  The 

2P r om  Section  2.8.3,  I-  and  r-values  are  appropriate  on  the  left  and  right  sides  of  assign 

ments,  respectively. 

366 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

translation  in  (b)  shows  position  numbers  for  the  instructions,  starting  arbitrar 
ily  at  position  100.  In  both  translations,  the  last  instruction  is  a  conditional 
j u mp  to  the  first  instruction.  The  multiplication  i *8  is  appropriate  for  an 
array  of  elements  t h at  each  take  8  units  of  space. 

• 

tl  =  i  +  1 
i  =  tx 
t2  =  i  *  8 
t3  =  a  [  t2  ] 
if  t3  <  v  g o to  L 

100 
101 
102 
103 
104 

ti  =  i  +  1 
i  =  ti 
t2  =  i  *  8 
t3  =  a  [  t2  ] 
if  t3 < V  g o to 

(a)  Symbolic  labels. 

(b)  Position  numbers. 

Figure  6.9:  Two  ways  of  assigning  labels  to  three-address  statements 

The  choice  of  allowable  operators  is  an  important  issue  in  the  design  of  an 
intermediate  form.  The  operator  set  clearly  must  be  rich  enough  to  implement 
the  operations  in  the  source  language.  Operators  t h at  are  close  to  machine 
instructions  make  it  easier  to  implement  the  intermediate  form  on  a  target 
machine.  However,  if t he  front  end  must  generate  long  sequences  of instructions 
for  some  source-language  operations,  then  the  optimizer  and  code  generator 
may  have  to  work  harder  to  rediscover  the  structure  and  generate  good  code 
for  these  operations. 

6.2.2  Quadruples 

T he  description  of  three-address  instructions  specifies  the  components  of  each 
type  of  instruction,  but  it  does  not  specify  the  representation  of  these  instruc 
tions  in  a  d a ta  structure.  In  a  compiler,  these  instructions  can  be  implemented 
as  objects  or  as  records  with  fields  for  the  operator  and  t he  operands.  Three 
such  representations  are  called  "quadruples,"  "triples,"  and  "indirect  triples." 

A  quadruple  (or  just  "quad!')  has  four  fields,  which  we  call  op,  arg1:  arg2, 
and  result.  The  op  field  contains  an  internal  code  for  the  operator.  For  instance, 
t he  three-address  instruction  x  =  y + z  is  represented  by  placing  +  in  op,  y  in 
arg1,  z  in  arg2,  and  x  in  result.  T he  following  are  some  exceptions  to  this  rule: 

1.  Instructions  with  unary  operators  like  x  =  minus y  or  x  =  y  do  not  use 
arg2.  Note  t h at  for  a  copy  statement  like  x  =  y,  op  is  =,  while  for  most 
other  operations,  t he  assignment  operator  is  implied. 

2.  Operators  like  p ar  am  use  neither  arg2  nor  result. 

3.  Conditional  and  unconditional  j u m ps  put  t he  target  label  in  result. 

E x a m p le  6 . 6:  Three-address  code  for  t he  assignment  a  =  b * - c + b * - c; 
appears  in  Fig.  6.10(a).  T he  special  operator  minus  is  used  to  distinguish  t he 

6.2. 

THREE-ADDRESS  CODE 

367 

unary  minus  operator,  as  in  -  c,  from  the  binary  minus  operator,  as  in  b -  c. 
Note  t h at  the  unary-minus  "three-address"  statement  has  only  two  addresses, 
as  does  the  copy  statement  a  =  t5. 

T he  quadruples  in  Fig.  6.10(b)  implement  t he  three-address  code  in  (a). 

• 

tl  =  minus  c 
=  b  *  ti 
t2 
t3 
=  minus  c 
t4  =  b  *  t3 
t2  +  t4 
= 
t5 
a  = 
t5 

* 

op 

argx 
0  minus  i  c 
i  b 
1 
2  minus  i  c 
i  b 
* 
3 
|  t2 
4 
+ 
t5 
[ 

5 

= 

arg2  result 

ti 

' 
' 

t3 
t4 

ti 
t2 
t3 
! 
t4 
! 
! 
t5 
i  a 

(a)  Three-address  code 

(b)  Quadruples 

Figure  6.10:  Three-address  code  and  its  quadruple  representation 

For  readability,  we  use  actual  identifiers  like  a,  b,  and  c  in  t he  fields  argx, 
arg2,  and  result  in  Fig.  6.10(b),  instead  of pointers  to  their  symbol-table  entries. 
Temporary  names  can  either  by  entered  into  the  symbol  table  like  programmer-
defined  names,  or  they  can  be  implemented  as  objects  of  a  class  Temp  with  its 
own  methods. 

6.2.3  Triples 

A  triple  has  only  three  fields,  which  we  call  op,  argx,  and  arg2-  Note  t h at 
t he  result  field  in  Fig.  6.10(b)  is  used  primarily  for  temporary  names.  Using 
triples,  we  refer  to  the  result  of  an  operation  x  op  y  by  its  position,  rather 
t h an  by  an  explicit  temporary  name.  Thus,  instead  of  the  temporary  ti  in 
Fig.  6.10(b),  a  triple  representation  would  refer  to  position  (0).  Parenthesized 
numbers  represent  pointers  into  the  triple  structure  itself. 
In  Section  6.1.2, 
positions  or  pointers  to  positions  were  called  value  numbers. 

Triples  are  equivalent  to  signatures  in  Algorithm  6.3.  Hence,  the  DAG  and 
triple  representations  of  expressions  are  equivalent.  The  equivalence  ends  with 
expressions,  since  syntax-tree  variants  and  three-address  code  represent  control 
flow  quite  differently. 

E x a m p le  6 . 7:  The  syntax  tree  and  triples  in  Fig.  6.11  correspond  to  t he 
three-address  code  and  quadruples  in  Fig.  6.10.  In  t he  triple  representation  in 
Fig.  6.11(b),  the  copy  statement  a  =  t5  is  encoded  in  t he  triple  representation 
by  placing  a  in  the  arc^  field  and  (4)  in  t he  arg2 

field. 

• 

A  ternary  operation  like  x[i]  =  y  requires  two  entries  in  the  triple  structure; 
for  example,  we  can  p ut  x  and  i  in  one  triple  and  y  in  t he  next.  Similarly, 
x  =  y{.%]  can  implemented  by  treating  it  as  if  it  were  the  two  instructions 

368 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

Why  Do  We  Need  Copy  Instructions? 

A  simple  algorithm  for  translating  expressions  generates  copy  instructions 
for  assignments,  as  in  Fig.  6.10(a),  where  we  copy  ts  into  a  rather  t h an 
assigning  t2  +14  to  a  directly.  Each  subexpression  typically  gets  its  own, 
new  temporary  to  hold  its  result,  and  only  when  the  assignment  operator  = 
is  processed  do  we  learn  where  to  put  the  value  of t he  complete  expression. 
A  code-optimization  pass,  perhaps  using  t he  DAG  of  Section  6.1.1  as  an 
intermediate  form,  can  discover  t h at 

can  be  replaced  by  a. 

+ 

* 
\ 

m i n us  b 

* 
/ 

\ 
m i n us 

1 

c 

op 

0  minus 
* 
1 
2  minus 
* 
+ 

3 

4 

5 

= 

argx 
c 

b 

c 

b 

(1) 
a 

(0) 

(2) 
(3) 
(4) 

(a)  Syntax  tree 

(b)  Triples 

Figure  6.11:  Representations  of a + a *  (b —  c)  +  (b — c)  * d 

t  =  y[i]  and  x  =  t,  where  i is  a  compiler-generated  temporary.  Note  t h at  the 
temporary  t  does  not  actually  appear  in  a  triple,  since  t e m p o r a ry  values  are 
referred  to  by  their  position  in  the  triple  structure. 

A  benefit  of  quadruples  over  triples  can  be  seen  in  an  optimizing  compiler, 
where  instructions  are  often  moved  around.  W i th  quadruples,  if  we  move  an 
instruction  t h at  computes  a  t e m p o r a ry  t,  then  the  instructions  t h at  use  t  require 
no  change.  W i th  triples,  t he  result  of an  operation  is  referred  to  by  its  position, 
so  moving  an  instruction  may  require  us  to  change  all  references  to  t h at  result. 
This  problem  does  not  occur  with  indirect  triples,  which  we  consider  next. 

Indirect  triples  consist  of  a  listing  of  pointers  to  triples,  rather  t h an  a  listing 
of triples  themselves.  For  example,  let  us  use  an  array  instruction to  list  pointers 
to  triples  in  the  desired  order.  Then,  t he  triples  in  Fig.  6.11(b)  might  be 
represented  as  in  Fig.  6.12. 

W i th  indirect  triples,  an  optimizing  compiler  can  move  an  instruction  by 
reordering  t he  instruction  list,  without  affecting  t he  triples  themselves.  W h en 
implemented  in  Java,  an  array  of  instruction  objects  is  analogous  to  an  indi 
rect  triple  representation,  since  Java  treats  t he  array  elements  as  references  to 
objects. 

6.2. 

THREE-ADDRESS  CODE 

369 

instruction 
35 
(0) 
36 
37 
38 
39 
40 

(1) 
(2) 
(3) 
(4) 
(5) 

* 

op 

argx 
c 
0  minus 
b 
1 
2  minus  c 
* 
b 
3 
4 
+ 
5 

(1) 
a 

= 

arg2 

(0) 

(2) 
(3) 
(4) 

Figure  6.12:  Indirect  triples  representation  of  three-address  code 

6.2.4 

Static  Single-Assignment  Form 

Static  single-assignment  form  (SSA)  is  an  intermediate  representation  t h at  fa 
cilitates  certain  code  optimizations.  Two  distinctive  aspects  distinguish  SSA 
from  three-address  code.  T he  first  is  t h at  all  assignments  in  SSA  are  to  vari 
ables  with  distinct  names;  hence  the  t e rm  static  single-assigment.  Figure  6.13 
shows  t he  same  intermediate  program  in  three-address  code  and  in  static  single-
assignment  form.  Note  t h at  subscripts  distinguish  each  definition  of  variables 
p  and  q  in  t he  SSA  representation. 

p  =  a  +  b 
q  =  p-  c 
p  =  q *d 

P  = 
e  -  P 
q  =  p  +  q 

px  =  a  +  b 
qi  =  Pi  "  c 
p2= qx*d 

_P2 

e

= 

P3
q2  =  Ps 

+  <ii 

(a)  Three-address  code. 

(b)  Static  single-assignment  form. 

Figure  6.13:  Intermediate  program  in  three-address  code  and  SSA 

T he  same  variable  may  be  defined  in  two  different  control-flow  paths  in  a 

program.  For  example,  t he  source  program 

if  (  f l ag  )  x  = -1;  e l se  x  =  1; 
y  =  x  *  a; 

If  we  use 
has  two  control-flow  paths  in  which  the  variable  x  gets  defined. 
different  names  for  x  in  the  true  part  and  the  false  p a rt  of  t he  conditional 
statement,  then  which  name  should  we  use  in  the  assignment  y  =  x  *  a?  Here 
is  where  t he  second  distinctive  aspect  of  SSA  comes  into  play.  SSA  uses  a 
notational  convention  called  t he  (^-function  to  combine  t he  two  definitions  of x: 

if  (  f l ag  )  xi  = -1;  e l se  x2  =  1; 
x3  =  0( x i , x2); 

 
370 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

Here,  (j)(x1,x2)  has  the  value x2  if  the  control  flow  passes  through  the  true 
part  of  the  conditional  and  the  value  x2  if  t he  control  flow  passes  through  t he 
false  part.  T h at  is  to  say,  the  ^-function  returns  the  value  of  its  argument  t h at 
corresponds  to  the  control-flow  p a th  t h at  was  taken  to  get  to  the  assignment-
statement  containing  t he  ^-function. 

6.2.5  Exercises  for  Section  6.2 

Exercise  6 . 2 . 1:  Translate the arithmetic expression a + - (& -I- c)  into: 

a)  A  syntax  tree. 

b)  Quadruples. 

c)  Triples. 

d)  Indirect  triples. 

Exercise  6 . 2 . 2:  Repeat  Exercise  6.2.1  for  the  following  assignment  state 
ments: 

i.  a = b[i]  +  c[j]. 

ii.  a[i]  =  b*c  -  b*d. 

Hi.  x  =  f (y+1)  +  2. 

iv.  x  =  *p  +  &y. 

! Exercise  6 . 2 . 3:  Show  how  to  transform  a  three-address  code  sequence  into 

one  in  which  each  defined  variable  gets  a  unique  variable  name. 

6.3  Types  and  Declarations 

T he  applications  of  types  can  be  grouped  under  checking  and  translation: 

•  Type  checking  uses  logical  rules  to  reason  about  the  behavior  of  a  program 
at  r un  time.  Specifically,  it  ensures  t h at  t he  types  of t he  operands  match 
t he  type  expected  by  an  operator.  For  example,  the  &&  operator  in  Java 
expects  its  two  operands  to  be  booleans;  the  result  is  also  of type  boolean. 

•  Translation  Applications.  From  t he  type  of  a  name,  a  compiler  can  de 
termine  t he  storage  t h at  will  be  needed  for  t h at  name  at  run  time.  Type 
information  is  also  needed  to  calculate  t he  address  denoted  by  an  array 
reference,  to  insert  explicit  type  conversions,  and  to  choose  t he  right  ver 
sion  of  an  arithmetic  operator,  among  other  things. 

6.3. 

TYPES  AND  DECLARATIONS 

371 

In  this  section,  we  examine  types  and  storage  layout  for  names  declared 
within  a  procedure  or  a  class.  The  actual  storage  for  a  procedure  call  or  an 
object  is  allocated  at  run  time,  when  the  procedure  is  called  or  the  object  is 
created.  As  we  examine  local  declarations  at  compile  time,  we  can,  however, 
lay  out  relative  addresses,  where  t he  relative  address  of  a  n a me  or  a  component 
of  a  d a ta  structure  is  an  offset  from  the  start  of  a  d a ta  area. 

6.3.1  Type  Expressions 

Types  have  structure,  which  we  shall  represent  using  type  expressions:  a  type 
expression  is  either  a  basic  type  or  is  formed  by  applying  an  operator  called  a 
type  constructor  to  a  type  expression.  The  sets  of  basic  types  and  constructors 
depend  on  t he  language  to  be  checked. 

E x a m p le  6 . 8:  T he  array  type  i nt [2]  [3]  can  be  read  as  "array  of  2  arrays 
of  3  integers  each"  and  written  as  a  type  expression  array(2,  array(3,  integer)). 
This  type  is  represented  by  the  tree  in  Fig.  6.14.  T he  operator  array  takes  two 
• 
parameters,  a  number  and  a  type. 

array 

array 

3 

integer 

Figure  6.14:  Type  expression  for  i nt  [2]  [3] 

We  shall  use  the  following  definition  of  type  expressions: 

•  A  basic  type  is  a  type  expression.  Typical  basic  types  for  a  language 
the  latter  denotes  "the 
integer,  float,  and  void; 

include  boolean,  char, 
absence  of  a  value." 

•  A  t y pe  name  is  a  type  expression. 

•  A  type  expression  can  be  formed  by  applying  t he  array  t y pe  constructor 

to  a  number  and  a  type  expression. 

•  A  record  is  a  d a ta  structure  with  named  fields.  A  type  expression  can 
be  formed  by  applying  t he  record  type  constructor  to  t he  field  names  and 
their  types.  Record  types  will  be  implemented  in  Section  6.3.6  by  applying 
the  constructor  record  to  a  symbol  table  containing  entries  for  the  fields. 

•  A  t y pe  expression  can  be  formed  by  using  t he  type  constructor  —>•  for  func 
tion  types.  We  write  s  —»•  t  for  "function  from  type  s  to  type  r."  Function 
types  will  be  useful  when  type  checking  is  discussed  in  Section  6.5. 

372 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

Type  Names  and  Recursive  Types 

Once  a  class  is  defined,  its  name  can  be  used  as  a  type  name  in  C++  or 
Java;  for  example,  consider Node  in  the  program  fragment 

p u b l ic class Node { • • • } 

p u b l ic  Node  n; 

Names  can  be  used  to  define  recursive  types,  which  are  needed  for 

d a ta  structures  such  as  linked  lists.  T he  pseudocode  for  a  list  element 

class Cell  {  int  info;  Cell next; •••  } 

defines  the  recursive  type Cell  as  a  class  t h at  contains  a  field  i n fo  and 
a  field next  of  type Cell.  Similar  recursive  types  can  be  defined  in  C 
using  records  and  pointers.  The  techniques  in  this  chapter  carry  over  to 
recursive  types. 

•  If  s  and  t  are  type  expressions,  then  their  Cartesian  product  s  x  t  is  a 
type  expression.  Products  are  introduced  for  completeness;  they  can  be 
used  to  represent  a  list  or  tuple  of  types  (e.g.,  for  function  parameters). 
We  assume  t h at  x  associates  to  the  left  and  t h at  it  has  higher  precedence 
t h an  ->. 

•  Type  expressions  may  contain  variables  whose  values  are  type  expressions. 

Compiler-generated  type  variables  will  be  used  in  Section  6.5.4. 

A  convenient  way  to  represent  a  type  expression  is  to  use  a  graph.  T he 
value-number  method  of  Section  6.1.2,  can  be  adapted  to  construct  a  dag  for  a 
type  expression,  with  interior  nodes  for  type  constructors  and  leaves  for  basic 
types,  type  names,  and  type  variables;  for  example,  see  the  tree  in  Fig.  6.14.3 

6.3.2  Type  Equivalence 

When  are  two  type  expressions  equivalent?  Many  type-checking  rules  have  t he 
form,  "if two  type  expressions  are  equal  t h en  return  a  certain  type  e l se  error." 
Potential  ambiguities  arise  when  names  are  given  to  type  expressions  and  t he 
names  are  then  used  in  subsequent  type  expressions.  T he  key  issue  is  whether 
a  name  in  a  type  expression  stands  for  itself  or  whether  it  is  an  abbreviation 
for  another  type  expression. 

3Since  type  names  denote  type  expressions,  they  can  set  up  implicit  cycles;  see  the  box 
on  "Type  Names  and  Recursive  Types."  If  edges  to  type  names  are  redirected  to  the  type 
expressions  denoted  by  the  names,  then  the  resulting  graph  can  have  cycles  due  to  recursive 
types. 

6.3. 

TYPES  AND  DECLARATIONS 

373 

When  type  expressions  are  represented  by  graphs,  two  types  are  structurally 

equivalent  if  and  only  if  one  of  the  following  conditions  is  true: 

•  They  are  the  same  basic  type. 

•  They  are  formed  by  applying  the  same  constructor  to  structurally  equiv 

alent  types. 

•  One  is  a  type  name  t h at  denotes  the  other. 

If  type  names  are  treated  as  standing  for  themselves,  then  t he  first  two  condi 
tions  in  the  above  definition  lead  to  name  equivalence  of  type  expressions. 

Name-equivalent  expressions  are  assigned  t he  same  value  number,  if  we  use 
Algorithm  6.3.  Structural  equivalence  can  be  tested  using  the  unification  algo 
rithm  in  Section  6.5.5. 

6.3.3  Declarations 

We  shall  study  types  and  declarations  using  a  simplified  grammar  t h at  declares 
just  one  name  at  a  time;  declarations  with  lists  of  names  can  be  handled  as 
discussed  in  Example  5.10.  T he  grammar  is 

D 
T 
B 
C 

-> 
-> 

T  id  ;  D 
B  C 
i nt 
| 
e 

|  e 
r e c o rd 

| 
|  float 
[  n um  ]  C 

' {'  D  '}' 

The  fragment  of  the  above  grammar  t h at  deals  with  basic  and  array  types 
was  used  to  illustrate  inherited  attributes  in  Section  5.3.2.  T he  difference  in 
this  section  is  t h at  we  consider  storage  layout  as  well  as  types. 

Nonterminal  D  generates  a  sequence  of  declarations.  Nonterminal  T  gen 
erates  basic,  array,  or  record  types.  Nonterminal  B  generates  one  of  t he  basic 
types  i nt  and 
float.  Nonterminal  C,  for  "component,"  generates  strings  of 
zero  or  more  integers,  each  integer  surrounded  by  brackets.  An  array  type  con 
sists  of  a  basic  type  specified  by  B,  followed  by  array  components  specified  by 
nonterminal  C.  A  record  type  (the  second  production  for  T)  is  a  sequence  of 
declarations  for  the  fields  of  the  record,  all  surrounded  by  curly  braces. 

6.3.4  Storage  Layout  for  Local  Names 

From  the  type  of  a  name,  we  can  determine  t he  amount  of  storage  t h at  will  be 
needed  for  the  name  at  run  time.  At  compile  time,  we  can  use  these  amounts  to 
assign  each  name  a  relative  address.  T he  type  and  relative  address  are  saved  in 
the  symbol-table  entry  for  the  name.  D a ta  of varying  length,  such  as  strings,  or 
d a ta  whose  size  cannot  be  determined  until  run  time,  such  as  dynamic  arrays, 
is  handled  by  reserving  a  known  fixed  amount  of  storage  for  a  pointer  to  the 
data.  Run-time  storage  management  is  discussed  in  Chapter  7. 

374 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

Address  Alignment 

T he  storage  layout  for  d a ta  objects  is  strongly  influenced  by  t he  address 
ing  constraints  of  the  target  machine.  For  example,  instructions  to  add 
integers  may  expect  integers  to  be  aligned,  t h at  is,  placed  at  certain  posi 
tions  in  memory  such  as  an  address  divisible  by  4.  Although  an  array  of 
ten  characters  needs  only  enough  bytes  to  hold  ten  characters,  a  compiler 
may  therefore  allocate  12  bytes  —  t he  next  multiple  of 4  —  leaving  2  bytes 
unused.  Space  left  unused  due  to  alignment  considerations  is  referred  to  as 
padding.  When  space  is  at  a  premium,  a  compiler  may  pack  d a ta  so  t h at 
no  padding  is  left;  additional  instructions  may  then  need  to  be  executed 
at  run  time  to  position  packed  d a ta  so  t h at  it  can  be  operated  on  as  if  it 
were  properly  aligned. 

Suppose  t h at  storage  comes  in  blocks  of  contiguous  bytes,  where  a  byte  is 
t he  smallest  unit  of  addressable  memory.  Typically,  a  byte  is  eight  bits,  and 
some  number  of  bytes  form  a  machine  word.  Multibyte  objects  are  stored  in 
consecutive  bytes  and  given  the  address  of  the  first  byte. 

The  width  of a  type  is  the  number  of storage  units  needed  for  objects  of t h at 
type.  A  basic  type,  such  as  a  character,  integer,  or  float,  requires  an  integral 
number  of  bytes.  For  easy  access,  storage  for  aggregates  such  as  arrays  and 
classes  is  allocated  in  one  contiguous  block  of  b y t e s .4 

T he  translation  scheme  (SDT)  in  Fig.  6.15  computes  types  and  their  widths 
for  basic  and  array  types;  record  types  will  be  discussed  in  Section  6.3.6.  T he 
SDT  uses  synthesized  attributes  type  and  width  for  each  nonterminal  and  two 
variables  t  and  w  to  pass  type  and  width  information  from  a  B  node  in  a  parse 
tree  to  t he  node  for  the  production  C  —>  e.  In  a  syntax-directed  definition,  t 
and  w  would  be  inherited  attributes  for  C. 

T he  body  of  the  T-production  consists  of  nonterminal  B,  an  action,  and 
nonterminal  C,  which  appears  on  the  next  line.  T he  action  between  B  and  C 
sets  t  to  B.type  and  w  to  B. width.  If  B  —>•  i nt  then  B.type  is  set  to  integer  and 
B.width  is  set  to  4,  t he  width  of  an  integer.  Similarly,  if  B  -+  float  then  B.type 
is  float  and  B.width  is  8,  t he  width  of  a  float. 

T he  productions  for  C  determine  whether  T  generates  a  basic  t y pe  or  an 

array  type.  If  C  —>•  e,  then  t  becomes  C.type  and  w  becomes  C. width. 

Otherwise,  C  specifies  an  array component.  T he action for  C  —>  [  n um ]  C\ 
forms  C.type  by  applying  the  type  constructor  array  to  the  operands  num.value 
and  C\.type.  For  instance,  the  result  of  applying  array  might  be  a  tree  structure 
such  as  Fig.  6.14. 

4 Storage  allocation  for  pointers  in  C  and  C ++  is  simpler  if  all  pointers  have  the  same 
width.  The  reason  is  that  the  storage  for  a  pointer  may  need  to  be  allocated  before  we  learn 
the  type  of  the  objects  it  can  point  to. 

6.3. 

TYPES  AND  DECLARATIONS 

375 

T 

B 

B 

C 

->  B 
C 

i nt 

float 

e 

{  t  =  B.type;  w  —  B.width;  } 

{  B.type  = 

integer;  B.width  — 4 

{  B.type  =  float;  B.width  —  8;  } 

{  C.type  —  t;  C.width  =  w;  } 

C 

-+ 

[  n um  ]  C\ 

{ 

array(mim.value, 

C\.type); 

C.width  =  num..value  x  C-y. width;  } 

Figure  6.15:  Computing  types  and  their  widths 

The  width  of an  array  is  obtained  by  multiplying  the  width  of an  element  by 
t he  number  of elements  in  the  array.  If addresses  of consecutive  integers  differ  by 
4,  then  address  calculations  for  an  array  of integers  will  include  multiplications 
by  4.  Such  multiplications  provide  opportunities  for  optimization,  so  it  is  helpful 
for  the  front  end  to  make  them  explicit.  In  this  chapter,  we  ignore  other  machine 
dependencies  such  as  the  alignment  of  d a ta  objects  on  word  boundaries. 

E x a m p le  6.9  :  The  parse  tree  for  the  type  i nt  [2]  [3]  is  shown  by  dotted  lines 
in  Fig.  6.16.  The  solid  lines  show  how  the  type  and  width  are  passed  from  B, 
down  t he  chain  of  C's  through  variables  t  and  w,  and  then  back  up  the  chain 
as  synthesized  attributes  type  and  width.  T he  variables  t  and  w  are  assigned 
the  values  of  B.type  and  B.width,  respectively,  before  the  subtree  with  the  C 
nodes  is  examined.  The  values  of  t  and  w  are  used  at  the  node  for  C  —>  e  to 
• 
start  the  evaluation  of  the  synthesized  attributes  up  the  chain  of  C  nodes. 

type  —  array(2,  array(3,  integer)) 

width  =  24 

Figure  6.16:  Syntax-directed  translation  of  array  types 

e 

376 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

6.3.5 

Sequences  of  Declarations 

Languages  such  as  C  and  Java  allow  all  the  declarations  in  a  single  procedure 
to  be  processed  as  a  group.  T he  declarations  may  be  distributed  within  a  Java 
procedure,  but  they  can  still  be  processed  when  the  procedure  is  analyzed. 
Therefore,  we  can  use  a  variable,  say  offset,  to  keep  track  of  the  next  available 
relative  address. 

T he  translation  scheme  of  Fig.  6.17  deals  with  a  sequence  of  declarations 
of  the  form  T  id,  where  T  generates  a  type  as  in  Fig.  6.15.  Before  the  first 
declaration  is  considered,  offset  is  set  to  0.  As  each  new  name  x  is  seen,  x  is 
entered  into  the  symbol  table  with  its  relative  address  set  to  t he  current  value 
of  offset,  which  is  then  incremented  by  t he  width  of  the  type  of  x. 

P 

{  offset  =  0;  } 

D 

D 

->•  T  id  ; 

{  top.put{\d.lexeme,  T.type,  offset); 

offset  = 

offset+  T.width;  } 

D 

-+  e 

Figure  6.17:  Computing  the  relative  addresses  of  declared  names 

T he  semantic  action  within  t he  production  D  —>  T id  ;  D\  creates  a  symbol-

table  entry  by  executing 
top  denotes 
top.put(id.lexeme,  T.type, 
the  current  symbol  table.  T he  method  top.put  creates  a  symbol-table  entry  for 
id.lexeme,  with  type  T.type  and  relative  address  offset  in  its  d a ta  area. 

offset).  Here 

T he  initialization  of  offset  in  Fig.  6.17  is  more  evident  if  the  first  production 

appears  on  one  line  as: 

P 

{  offset = 0;  }  D 

(6.1) 

Nonterminals  generating  e,  called  marker  nonterminals,  can  be  used  to  rewrite 
productions  so  t h at  all  actions  appear  at  the  ends  of  right  sides;  see  Sec 
tion  5.5.4.  Using  a  marker  nonterminal  M,  (6.1)  can  be  restated  as: 

P 

-+  M  D 

M 

-» 

e 

{  offset  =  0;  } 

6.3.6  Fields  in  Records  and  Classes 
T he  translation  of  declarations  in  Fig.  6.17  carries  over  to  fields  in  records  and 
classes.  Record  types  can  be  added  to  the  g r a m m ar  in  Fig.  6.15  by  adding  t he 
following  production 

T 

-+ 

r e c o rd  '{'  D  '}' 

6.3. 

TYPES  AND  DECLARATIONS 

377 

T he  fields  in  this  record  type  are  specified  by  the  sequence  of  declarations 
generated  by  D.  T he  approach  of  Fig.  6.17  can  be  used  to  determine  the  types 
and  relative  addresses  of  fields,  provided  we  are  careful  about  two  things: 

•  T he  field  names  within  a  record  must  be  distinct;  t h at  is,  a  name  may 

appear  at  most  once  in  the  declarations  generated  by  D. 

•  T he  offset  or  relative  address  for  a  field  name  is  relative  to  t he  d a ta  area 

for  t h at  record. 

E x a m p le  6 . 1 0:  The  use  of  a  name  x  for  a  field  within  a  record  does  not 
conflict  with  other  uses  of the  name  outside  the  record.  Thus,  the  three  uses  of 
x  in  t he  following  declarations  are  distinct  and  do  not  conflict  with  each  other: 

f l o at  x; 
r e c o rd  {  f l o at  x; 
i nt  t a g; 
r e c o rd  { 

f l o at  y;  }  p; 
f l o at  x; 

f l o at  y;  }  q; 

A  subsequent  assignment  x  =  p. x + q. x;  sets  variable  x  to  t he  sum  of t he  fields 
named  x  in  the  records  p  and  q.  Note  t h at  the  relative  address  of  x  in  p  differs 
• 
from  the  relative  address  of  x  in  q. 

For  convenience,  record  types  will  encode  both  the  types  and  relative  ad 
dresses  of  their  fields,  using  a  symbol  table  for  the  record  type.  A  record  type 
has  the  form  record(t),  where  record  is  the  type  constructor,  and  i i sa  symbol-
table  object  t h at  holds  information  about  the  fields  of  this  record  type. 

T he  translation  scheme  in  Fig.  6.18  consists  of  a  single  production  to  be 
added  to  the  productions  for  T  in  Fig.  6.15.  This  production  has  two  semantic 
actions.  The  embedded  action  before  D  saves  the  existing  symbol  table,  denoted 
by  top  and  sets  top  to  a  fresh  symbol  table.  It  also  saves  the  current  offset,  and 
sets  offset to  0.  T he  declarations  generated  by  D  will  result  in  types  and  relative 
addresses  being  put  in  the  fresh  symbol  table.  The  action  after  D  creates  a 
record  type  using  top,  before  restoring  the  saved  symbol  table  and  offset. 

T 

->• 

r e c o rd 

{  Env.push(top);  top  =  n ew  EnvQ; 
Stack.push(offset);  offset  =  0;  } 

D  '}' 

{  T.type  =  record(top);  T.width  =  offset; 
top  —  Env.popQ;  offset  =  Stack.popQ;  } 

Figure  6.18:  Handling  of  field  names  in  records 

For  concreteness,  the  actions  in  Fig.  6.18  give  pseudocode  for  a  specific  im 
plementation.  Let  class  Env  implement  symbol  tables.  The  call  Env.push(top) 
pushes  the  current  symbol  table  denoted  by  top  onto  a  stack.  Variable  top  is 
then  set  to  a  new  symbol  table.  Similarly,  offset  is  pushed  onto  a  stack  called 
Stack.  Variable  offset  is  then  set  to  0. 

378 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

After  the  declarations  in  D  have  been  translated,  the  symbol  table  top  holds 
the  types  and  relative  addresses  of the  fields  in  this  record.  Further,  offset  gives 
the  storage  needed  for  all  the  fields.  T he  second  action  sets  T.type  to  record(top) 
and  T. width  to  offset  Variables  top  and  offset  are  then  restored  to  their  pushed 
values  to  complete  t he  translation  of  this  record  type. 

This  discussion  of  storage  for  record  types  carries  over  to  classes,  since  no 

storage  is  reserved  for  methods.  See  Exercise  6.3.2. 

6.3.7  Exercises  for  Section  6.3 

E x e r c i se  6 . 3 . 1:  Determine  the  types  and  relative  addresses  for  the  identifiers 
in  the  following  sequence  of  declarations: 

float  x; 

record {  float  x;  float y;  } p; 
record {  int  tag;  float  x;  float  y;  }  q; 

!  E x e r c i se  6 . 3 . 2:  Extend  the  handling  of field names  in  Fig.  6.18  to  classes  and 

single-inheritance  class  hierarchies. 

a)  Give  an  implementation  of  class  Env  t h at  allows  linked  symbol  tables,  so 
t h at  a  subclass  can  either  redefine  a  field  name  or  refer  directly  to  a  field 
name  in  a  superclass. 

b)  Give  a  translation  scheme  t h at  allocates  a  contiguous  d a ta  area  for  the 
fields  in  a  class,  including  inherited  fields.  Inherited  fields  must  maintain 
the  relative  addresses  they  were  assigned  in  t he  layout  for  the  superclass. 

6.4  Translation  of Expressions 

The  rest  of  this  chapter  explores  issues  t h at  arise  during  the  translation  of  ex 
pressions  and  statements.  We  begin  in  this  section  with  the  translation  of  ex 
pressions  into  three-address  code.  An  expression  with  more  t h an  one  operator, 
like  a  +  b*  c,  will  translate  into  instructions  with  at  most  one  operator  per  in 
struction.  An  array  reference  A[i][j]  will  expand  into  a  sequence  of three-address 
instructions  t h at  calculate  an  address  for  the  reference.  We  shall  consider  type 
checking  of  expressions  in  Section  6.5  and  the  use  of  boolean  expressions  to 
direct  the  flow  of  control  through  a  program  in  Section  6.6. 

6.4.1  Operations  Within  Expressions 

The  syntax-directed  definition  in  Fig.  6.19  builds  up  t he  three-address  code  for 
an  assignment  statement  S  using  attribute  code  for  S  and  attributes  addr  and 
code  for  an  expression  E.  Attributes  S.code  and  E.code  denote  t he  three-address 
code  for  S  and  E,  respectively.  Attribute  E.addr  denotes  the  address  t h at  will 

6.4. 

TRANSLATION  OF  EXPRESSIONS 

379 

PRODUCTION 

SEMANTIC  RULES 

S 

-> 

id  =  E  v 

S.  code  =  E.code 

|| 

gen(top.get(id.lexeme) 

'= 

E.addr) 

E  —>  Ei  +  Ei 

E.addr 
E.code 

—  n ew  Temp () 
=  Ei.code  ||  Ei-code  || 
gen(E.addr 

'=' 

Ei.addr'+' 

Ei.addr) 

\ 

-Ei 

E.addr 
E.code 

=  n ew  Temp  () 
=  Ei.code 

|| 

gen(E.addr 

'=' 

' m i n u s'  Ei.addr) 

| 

(Ei) 

E.addr 
E.  code 

=  Ei.addr 
=  Ei.code 

1 

id 

E.addr 
E.code 

= 

top.  get(id.  lexeme) 

11 

Figure  6.19:  Three-address  code  for  expressions 

hold  the  value  of  E.  Recall  from  Section  6.2.1  t h at  an  address  can  be  a  name, 
a  constant,  or  a  compiler-generated  temporary. 

Consider  the  last  production,  E  ->•  id,  in  the  syntax-directed  definition  in 
Fig.  6.19.  When  an  expression  is  a  single  identifier,  say  x,  then  x  itself holds  the 
value  of  t he  expression.  T he  semantic  rules  for  this  production  define  E.addr 
to  point  to  the  symbol-table  entry  for  this  instance  of  id.  Let  top  denote  t he 
current  symbol  table.  Function  top. get  retrieves  the  entry  when  it  is  applied  to 
t he  string  representation  id.lexeme  of  this  instance  of  id.  E.code  is  set  to  t he 
empty  string. 

W h en  E  —>  (Ei),  the  translation  of  E  is  the  same  as  t h at  of  t he  subex 

pression  Ei.  Hence,  E.addr  equals  Ei.addr,  and  E.code  equals  Ei.code. 

T he  operators  +  and  unary  -  in  Fig.  6.19  are  representative  of the  operators 
in  a  typical  language.  The  semantic  rules  for  E  —>  E\  + E2,  generate  code  to 
compute  t he  value  of  E  from  t he  values  of  E\  and  E2.  Values  are  computed 
into  newly  generated  temporary  names. 
If  E\  is  computed  into  Ei.addr  and 
E2  into  E2. addr,  then  E\  +  E2  translates  into  t  =  E\. addr +  E2. addr,  where  t  is 
a  new  t e m p o r a ry  name.  E.addr  is  set  to  t.  A  sequence  of  distinct  t e m p o r a ry 
names  ti,t2,... 

is  created  by  successively  executing  n ew  Tempi). 
For  convenience,  we  use  t he  notation  gen(x  '='  y  '+'  z)  to  represent  the 
three-address  instruction  x  =  y + z.  Expressions  appearing  in  place  of variables 
like  x,  y,  and  z  are  evaluated  when  passed  to  gen,  and  quoted  strings  like 
are  taken  literally.5  Other  three-address  instructions  will  be  built  up  similarly 

5In  syntax-directed  definitions,  gen  builds  an  instruction  and  returns  it.  In  translation 
schemes,  gen  builds  an  instruction  and  incrementally  emits  it  by  putting  it  into  the  stream 

380 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

by  applying  gen  to  a  combination  of  expressions  and  strings. 

When  we  translate  the  production  E  ->  Ei+E2, 

t he  semantic  rules  in 
Fig.  6.19  build  up  E.code  by  concatenating  Ei.code,  E2.code,  and  an  instruc 
tion  t h at  adds  the  values  of  E\  and  E2.  The  instruction  puts  the  result  of  t he 
addition  into  a  new  temporary  name  for  E,  denoted  by  E.addr. 

The  translation  of  E  -»  -  E\  is  similar.  The  rules  create  a  new  temporary 

for  E  and  generate  an  instruction  to  perform  the  unary  minus  operation. 

Finally,  the  production  S 

id = E;  generates  instructions  t h at  assign  the 
value  of  expression  E  to  the  identifier  id.  T he  semantic  rule  for  this  production 
uses  function  top.get  to  determine  t he  address  of  t he  identifier  represented  by 
id,  as  in  the  rules  for  E  —v  id.  S.code  consists  of  the  instructions  to  compute 
the  value  of  E  into  an  address  given  by  E.addr,  followed  by  an  assignment  to 
the  address  top.get(id.lexeme)  for  this  instance  of  id. 

E x a m p le  6 . 1 1:  The  syntax-directed  definition  in  Fig.  6.19  translates  the  as 
signment  statement  a  =  b  +  -  c;  into  t he  three-address  code  sequence 

ti  =  minus  c 
t2  =  b  +  ti 
t2 
a  = 

• 

6.4.2 

Incremental  Translation 

Code  attributes  can  be  long  strings,  so  they  are  usually  generated  incremen 
tally,  as  discussed  in  Section  5.5.2.  Thus,  instead  of  building  up  E.code  as  in 
Fig.  6.19,  we  can  arrange  to  generate  only  the  new  three-address  instructions, 
as  in  the  translation  scheme  of  Fig.  6.20.  In  the  incremental  approach,  gen  not 
only  constructs  a  three-address  instruction,  it  appends  the  instruction  to  the 
sequence  of  instructions  generated  so  far.  T he  sequence  may  either  be  retained 
in  memory  for  further  processing,  or  it  may  be  o u t p ut  incrementally. 

The  translation  scheme  in  Fig.  6.20  generates  the  same  code  as  the  syntax-
directed  definition  in  Fig.  6.19.  W i th  t he  incremental  approach,  t he  code  at 
tribute  is  not  used,  since  there  is  a  single  sequence  of instructions  t h at  is  created 
by  successive  calls  to  gen.  For  example,  the  semantic  rule  for  E  ->•  E\  + E2  in 
Fig.  6.20  simply  calls  gen  to  generate  an  add  instruction;  the  instructions  to 
compute  Ei 

into  Ei.addr  and  E2  into  E2.addr  have  already  been  generated. 

T he  approach  of  Fig.  6.20  can  also  be  used  to  build  a  syntax  tree.  T he  new 
Ex  + E2  creates  a  node  by  using  a  constructor,  as  in 

semantic  action  for  E 

E 

Ei  +  E2 

{E.addr  =  n ew  Node(''+',  Ei.addr,  E2.addr); 

} 

Here,  a t t r i b u te  addr  represents  the  address  of  a  node  rather  t h an  a  variable  or 
constant. 

of  generated  instructions. 

6.4. 

TRANSLATION  OF  EXPRESSIONS 

381 

S 

id  =  E  ; 

{  gen(  top.get(id.lexeme)  '—'  E.addr)]  } 

E 

->  Ei  +  E2 

{  E.addr  =  n ew  Tempi); 
gen(E.addr 

'='  Ei.addr 

'+'  E2.addr); 

} 

| 

-  Ei 

{  E.addr  =  n ew  Tempi); 

gen(E.addr 

'=' 

' m i n u s'  Ei.addr); 

} 

| 

| 

(  Ei  ) 

{  E.addr  =  Ei.addr;  } 

id 

{  E.addr  = 

top.geti\d.lexeme); 

} 

Figure  6.20:  Generating  three-address  code  for  expressions  incrementally 

6 . 4 .3  Addressing  Array  Elements 

Array  elements  can  be  accessed  quickly  if they  are  stored  in  a  block  of  consecu 
tive  locations.  In  C  and  Java,  array  elements  are  numbered  0 , 1 , . ..  , n  —  1,  for 
an  array  with  n  elements.  If  the  width  of  each  array  element  is  w,  then  t he  iih 
element  of  array  A  begins  in  location 

base  +  i  x  w 

(6.2) 

where  base  is  the  relative  address  of  the  storage  allocated  for  the  array.  T h at 
is,  base  is  the  relative  address  of  ^4[0]. 

The  formula  (6.2)  generalizes  to  two  or  more  dimensions.  In  two  dimensions, 
we  write  A[ii][i2]  in  C  and  Java  for  element  i2  in  row  ii.  Let  w\  be  the  width 
of  a  row  and  let  w2  be  the  width  of  an  element  in  a  row.  T he  relative  address 
of  .A[zi][z2]  can  then  be  calculated  by  the  formula 

base  +  ii  x  wi  +  i2  x  w2 

(6.3) 

In  k  dimensions,  the  formula  is 

base  +  ii  x  w±  +  i2  x  w2  -I 

f-  ik  x  wk 

(6.4) 

where  Wj,  for  1  <  j  <  k,  is  the  generalization  of  Wi  and  w2  in  (6.3). 

Alternatively,  t he  relative  address  of  an  array  reference  can  be  calculated 
in  terms  of  t he  numbers  of  elements  rij  along  dimension  j  of  the  array  and  t he 
width  w  =  Wk  of  a  single  element  of  the  array.  In  two  dimensions  (i.e.,  k  =  2 
and  w  =  w2),  the  location  for  A[n][i2]  is  given  by 

base  +  (h  x  n2  +  i2)  x  w 

(6.5) 

In  k  dimensions,  the  following  formula  calculates  the  same  address  as  (6.4): 

base  + ( ( • ••  (zi  x  n2  +  i2)  x  n3  +  i3)  •  •  •)  x  nk  +  ik)  x  w 

(6.6) 

382 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

More  generally,  array  elements  need  not  be  numbered  starting  at  0. 

In  a 
one-dimensional  array,  t he  array  elements  are  numbered  low,  low  +  1 , . ..  ,  high 
and  base  is  the  relative  address  of  A[low}.  Formula  (6.2)  for  t he  address  of  A[i] 
is  replaced  by: 

base +  (i  —  low)  x  w 

(6.7) 

The  expressions  (6.2)  and  (6.7)  can  be  both  be  rewritten  as  i  x  w + c,  where 
the  subexpression  c  =  base  —  low  x  w  can  be  precalculated  at  compile  time. 
Note  t h at  c  =  base  when  low  is  0.  We  assume  t h at  c  is  saved  in  t he  symbol 
table  entry  for  A,  so  the  relative  address  of  A[i]  is  obtained  by  simply  adding 
i  x  w  to  c. 

Compile-time  precalculation  can  also  be  applied  to  address  calculations  for 
elements  of  multidimensional  arrays;  see  Exercise  6.4.5.  However,  there  is  one 
situation  where  we  cannot  use  compile-time  precalculation:  when  the  array's 
If  we  do  not  know  t he  values  of  low  and  high  (or  their  gen 
size  is  dynamic. 
eralizations  in  many  dimensions)  at  compile  time,  then  we  cannot  compute 
constants  such  as  c.  Then,  formulas  like  (6.7)  must  be  evaluated  as  they  are 
written,  when  the  program  executes. 

T he  above  address  calculations  are  based  on  row-major  layout  for  arrays, 
which  is  used  in  C  and  Java.  A  two-dimensional  array  is  normally  stored  in 
one  of  two  forms,  either  row-major  (row-by-row)  or  column-major  (column-by-
column).  Figure  6.21  shows  the  layout  of  a  2  x  3  array  A  in  (a)  row-major  form 
and  (b)  column-major  form.  Column-major  form  is  used  in  the  Fortran  family 
of  languages. 

T 

First  row 

Second row 

1 

A[l,l] 

A[l,2] 

A[l,3] 

A[2,l] 

A[2,2] 

A[2,3] 

A[l,l] 

A[2,l] 

A[l,2] 

A[2,2] 

A[l,3] 

A[2,3] 

T 
First  column 

id co 
Second  column 

i 
Third  column 
± 

(a)  Row  Major 

(b)  Column  Major 

Figure  6.21:  Layouts  for  a  two-dimensional  array. 

We  can  generalize  row-  or  column-major  form  to  many  dimensions.  T he 
generalization  of  row-major  form  is  to  store  the  elements  in  such  a  way  t h a t, 
as  we  scan  down  a  block  of  storage,  t he  rightmost  subscripts  appear  to  vary 
fastest,  like  t he  numbers  on  an  odometer.  Column-major  form  generalizes  to 
t he  opposite  arrangement,  with  the  leftmost  subscripts  varying  fastest. 

6.4. 

TRANSLATION  OF  EXPRESSIONS 

383 

6.4.4  Translation  of  Array  References 

T he  chief problem  in  generating  code  for  array  references  is  to  relate  t he  address-
calculation  formulas  in  Section  6.4.3  to  a  g r a m m ar  for  array  references.  Let 
nonterminal  L  generate  an  array  name  followed  by  a  sequence  of  index  expres 
sions: 

L 

-+  L  [  E  ] 

| 

id  [  E  ] 

As  in  C  and  Java,  assume  t h at  the  lowest-numbered  array  element  is  0. 
Let  us  calculate  addresses  based  on  widths,  using  the  formula  (6.4),  rather 
t h an  on  numbers  of  elements,  as  in  (6.6).  The  translation  scheme  in  Fig.  6.22 
generates  three-address  code  for  expressions  with  array  references.  It  consists  of 
t he  productions  and  semantic  actions  from  Fig.  6.20,  together  with  productions 
involving  nonterminal  L. 

S 

-> 

id  =  E  ; 

{  gen(top.get(\d.lexeme) 

'='  E.addr);  } 

| 

L  =  E  ; 

{  gen(L.addr.base  '['  L.addr  '}'  '='  E.addr);  } 

E 

Ei  +  E2 

{  E.addr  =  n ew  TempQ; 
gen(E.addr 

'='  Ei.addr 

'+'  E2.addr); 

} 

| 

id 

{  E.addr  — 

top.get(\d.lexeme);  } 

{  E. addr  =  n ew  Temp  (); 

gen(E.addr 

'— 

L.  array.base'[  L.addr']'); 

} 

L  ->• 

id  [  E  ] 

{  L.array  — 

top.get(id.lexeme); 

L.type  =  L.  array, type,  elem; 
L.addr  =  n ew  TempQ; 
gen(L.addr 

'='  E.addr'*'  L.type.  width); 

} 

^ 

I  El 

{  L.array  =  Li.array; 

L.type  =  Li.  type,  elem; 
t  =  n ew  Temp  (); 
L.addr  =  n ew  Temp  (); 
gen(t 
gen(L.addr  '='  Li.addr  '+' 

'='  E.addr'*'  L.type.width); 

} 

t);  } 

Fi  gure  6.22:  Semantic  actions  for  array  references 

Nonterminal  L  has  three  synthesized  attributes: 

1.  L.addr  denotes  a  temporary  t h at  is  used  while  computing  the  offset  for 

the  array  reference  by  summing  the  terms  ij  x  Wj  in  (6.4). 

384 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

2.  L.array  is  a  pointer  to  the  symbol-table  entry  for  the  array  name.  The 
base  address  of the  array,  say,  L.array.base  is  used  to  determine  t he  actual 
/-value  of  an  array  reference  after  all  t he  index  expressions  are  analyzed. 

3.  L.type  is  the  type  of  the  subarray  generated  by  L.  For  any  type  t,  we 
assume  t h at  its  width  is  given  by  t.width.  We  use  types  as  attributes, 
rather  t h an  widths,  since  types  are  needed  anyway  for  type  checking.  For 
any  array  type  t,  suppose  t h at  t.elem  gives  t he  element  type. 

The  production  S  -»  id = E;  represents  an  assignment  to  a  nonarray  vari 
able,  which  is  handled  as  usual.  The  semantic  action  for  S  —?>  L = E;  generates 
an  indexed  copy  instruction  to  assign  t he  value  denoted  by  expression  E  to  t he 
location  denoted  by  the  array  reference  L.  Recall  t h at  a t t r i b u te  L.array  gives 
the  symbol-table  entry  for  the  array.  The  array's  base  address  —  t he  address 
of  its  Oth  element  —  is  given  by  L.array.base.  Attribute  L.addr  denotes  t he 
temporary  t h at  holds  the  offset  for  the  array  reference  generated  by  L.  The 
location  for  the  array  reference  is  therefore  L.array.base[L.addr].  T he  generated 
instruction  copies  the  r-value  from  address  E.addr  into  t he  location  for  L. 

Productions  E 

Ei+E2  and  E  —>  id  are  t he  same  as  before.  T he  se 

mantic  action  for  the  new  production  E  —»•  L  generates  code  to  copy  the 
value  from  t he  location  denoted  by  L  into  a  new  temporary.  This  location  is 
L.array.base[L.addr],  as  discussed  above  for  the  production  S  -¥  L  =  E;.  Again, 
attribute  L.array  gives  the  array  name,  and  L.array.base  gives  its  base  address. 
Attribute  L.addr  denotes  t he  temporary  t h at  holds  the  offset.  The  code  for  t he 
array  reference  places  the  r-value  at  the  location  designated  by  the  base  and 
offset  into  a  new  temporary  denoted  by  E. addr. 

E x a m p le  6 . 1 2:  Let  a  denote  a  2  x  3  array  of  integers,  and  let  c, 
j  all  denote  integers.  Then,  t he  type  of  a  is  array(2,  array(S,  integer)). 
width  w  is  24,  assuming  t h at  the  width  of  an  integer  is  4.  T he  type  of  a [ i]  is 
array(3,  integer),  of  width  w\  =  12.  T he  type  of  a [ i]  [ j]  is  integer. 

i,  and 
Its 

An  annotated  parse  tree  for  t he  expression  c + a [ i]  [ j]  is  shown  in  Fig.  6.23. 
T he  expression  is  translated  into  t he  sequence  of  three-address  instructions  in 
Fig.  6.24.  As  usual,  we  have  used  the  name  of  each  identifier  to  refer  to  its 
symbol-table  entry. 

• 

6.4.5  Exercises  for  Section  6.4 

E x e r c i se  6. 4. 1:  Add  to  the  translation  of  Fig.  6.19  rules  for  the  following 
productions: 

a)  E 

-+  Ei  *  E2. 

b)  E  ->•  +  Ei  (unary  plus). 

E x e r c i se  6. 4. 2:  Repeat  Exercise  6.4.1  for  t he  incremental  translation  of  Fig. 
6.20. 

6.4. 

TRANSLATION  OF  EXPRESSIONS 

385 

E.addr  = 

t$ 

E.addr  —  c 

E.addr  =  t4 

L. array  —  a 
L.type  = 
L.addr  — t3 

integer 

/ 
[ 

\ 

E.addr  =  j 

I 

3 

L. array  —  a 

L.type  =  array(2>,  integer) 
L.addr =  ti 

" 

/ 
[ 

a.  type 
=  array(2,  array(3,  integer)) 

\ 

E.addr  =  i 

] 

Figure  6.23:  Annotated  parse  tree  for  c + a [ i]  [ j] 

ti  =  i  *  12 
t2  =  j  *  4 
t3  =  ti  +  t2 
t4  =  a  [  t3  ] 
ts  =  C  +  t4 

Figure  6.24:  Three-address  code  for  expression  c  + a [ i]  [ j] 

E x e r c i se  6 . 4 . 3:  Use  the  translation  of  Fig.  6.22  to  translate  t he  following 
assignments: 

a)  x  =  a [ i]  +  b [ j ]. 

b)  x  =  a [ i ] [ j]  +  b [ i ] [ j ]. 

!  c)  x  =  a [ b [ i ] [ j ] ] [ c [ k ] ]. 

!  E x e r c i se  6 . 4 . 4:  Revise  the  translation  of  Fig.  6.22  for  array  references  of  the 

Fortran  style,  t h at  is, 

\d[Ei,E2,... 

,  En]  for  an  n-dimensional  array. 

E x e r c i se  6 . 4 . 5:  Generalize  formula  (6.7)  to  multidimensional  arrays,  and  in 
dicate  what  values  can  be  stored  in  t he  symbol  table  and  used  to  compute 
offsets.  Consider  t he  following  cases: 

a)  An  array  A  of  two  dimensions,  in  row-major  form.  T he  first  dimension 
has  indexes  running  from  l\  to  hi,  and  t he  second  dimension  has  indexes 
from  l2  to  h2.  T he  width  of  a  single  array  element  is  w. 

386 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

Symbolic  Type  Widths 

The  intermediate  code  should  be  relatively  independent  of  t he  target  ma 
chine,  so  t he  optimizer  does  not  have  to  change  much  if the  code  generator 
is  replaced  by  one  for  a  different  machine.  However,  as  we  have  described 
the  calculation  of  type  widths,  an  assumption  regarding  how  basic  types 
is  built  into  the  translation  scheme.  For  instance,  Example  6.12  assumes 
t h at  each  element  of  an  integer  array  takes  four  bytes.  Some  intermediate 
codes,  e.g.,  P-code  for  Pascal,  leave  it  to  t he  code  generator  to  fill  in  the 
size  of  array  elements,  so  the  intermediate  code  is  independent  of t he  size 
of a  machine  word.  We  could  have  done  t he  same  in  our  translation  scheme 
if  we  replaced  4  (as  the  width  of  an  integer)  by  a  symbolic  constant. 

b)  The  same  as  (a),  but  with  the  array  stored  in  column-major  form. 

!  c)  An  array  A  of  k  dimensions,  stored  in  row-major  form,  with  elements  of 

size  w.  The  jth.  dimension  has  indexes  running  from  lj  to  hj. 

!  d)  T he  same  as  (c)  but  with  t he  array  stored  in  column-major  form. 

E x e r c i se  6 . 4 . 6:  An  integer  array  A[i, j]  has  index  i  ranging  from  1  to  10  and 
index  j  ranging  from  1  to  20.  Integers  take  4  bytes  each.  Suppose  array  A  is 
stored  starting  at  byte  0.  Find  the  location  of: 

a)  A[4,5]  b)A[10,8] 

c)  A[3,17]. 

E x e r c i se  6 . 4 . 7:  Repeat  Exercise  6.4.6  if  A  is  stored  in  column-major  order. 

E x e r c i se  6 . 4 . 8:  A  real  array  A[i,j,  k]  has  index  i  ranging  from  1  to  4,  index 
j  ranging  from  0  to  4,  and  index  k  ranging  from  5  to  10.  Reals  take  8  bytes 
each.  Suppose  array  A  is  stored  starting  at  byte  0.  Find  the  location  of: 

a)  A[3,4,5]  b ) A [ l , 2 , 7] 

c)  A[4,3,9]. 

E x e r c i se  6 . 4 . 9:  Repeat  Exercise  6.4.8  if  A  is  stored  in  column-major  order. 

6.5  Type  Checking 

To  do  type  checking  a  compiler  needs  to  assign  a  type  expression  to  each  com 
ponent  of  the  source  program.  The  compiler  must  then  determine  t h at  these 
type  expressions  conform  to  a  collection  of  logical  rules  t h at  is  called  the  type 
system  for  t he  source  language. 

Type  checking has  t he potential  for  catching errors in  programs.  In  principle, 
any  check  can  be  done  dynamically,  if  the  target  code  carries  t he  type  of  an 

6.5. 

TYPE  CHECKING 

387 

element  along  with  the  value  of the  element.  A  sound type  system  eliminates  t he 
need  for  dynamic  checking  for  type  errors,  because  it  allows  us  to  determine 
statically  t h at  these  errors  cannot  occur  when  t he  target  program  runs.  An 
implementation  of  a  language  is  strongly  typed  if  a  compiler  guarantees  t h at  t he 
programs  it  accepts  will  run  without  type  errors. 

Besides  their  use  for  compiling,  ideas  from  type  checking  have  been  used 
to  improve  the  security  of  systems  t h at  allow  software  modules  to  be  imported 
and  executed.  Java  programs  compile  into  machine-independent  bytecodes  t h at 
include  detailed  type  information  about  the  operations  in  the  bytecodes.  Im 
ported  code  is  checked  before  it  is  allowed  to  execute,  to  guard  against  b o th 
inadvertent  errors  and  malicious  misbehavior. 

6.5.1  Rules  for  Type  Checking 

Type  checking  can  take  on  two  forms:  synthesis  and  inference.  Type  synthesis 
builds  up  t he  t y pe  of  an  expression  from  the  types  of  its  subexpressions. 
It 
requires  names  to  be  declared  before  they  are  used.  The  type  of  E\  +  E2  is 
defined  in  terms  of  the  types  of  E\  and  E2 •  A  typical  rule  for  type  synthesis 
has  t he  form 

if /  has  type  s  —>•  t  a nd  x  has  type  s, 
t h en  expression  f(x)  has  type  t 

/fi  ^ 

Here,  /  and  x  denote  expressions,  and  s  ->•  t  denotes  a  function  from  s  to  t. 
This  rule  for  functions  with  one  argument  carries  over  to  functions  with  several 
arguments.  The  rule  (6.8)  can  be  adapted  for  E\  +E2  by  viewing  it  as  a  function 
application 

add(Ei,E2).Q 

Type  inference  determines  t he  t y pe  of  a  language  construct  from  t he  way  it 
is  used.  Looking  ahead  to  t he  examples  in  Section  6.5.4,  let  null  be  a  function 
t h at  tests  whether  a  list  is  empty.  Then,  from  t he  usage  null(x),  we  can  tell 
t h at  x  must  be  a  list.  T he  type  of  the  elements  of  x  is  not  known;  all  we  know 
is  t h at  x  must  be  a  list  of  elements  of  some  type  t h at  is  presently  unknown. 

Variables  representing  type  expressions  allow  us  to  talk  about  unknown 
types.  We  shall use  Greek letters  a, (3,  •  •  •  for type variables in  type expressions. 

A  typical  rule  for  type  inference  has  t he  form 

if f(x)  is  an  expression, 
t h en  for  some  a  and  0,  f  has  type  a  —>  (3  a nd  x  has  type  a 

, 

Q^ 

T y pe  inference  is  needed  for  languages  like  ML,  which  check  types,  but  do  not 
require  names  to  be  declared. 

6We  shall  use  the  term  "synthesis"  even  if  some  context  information  is  used  to  determine 
types.  With  overloaded  functions,  where  the  same  name  is  given  to  more  than  one  function, 
the  context  of  E\  +  E2  may  also  need  to  be  considered  in  some  languages. 

388 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

In  this  section,  we  consider  type  checking  of  expressions.  T he  rules  for 
checking  statements  are  similar  to  those  for  expressions.  For  example,  we  treat 
the  conditional  statement  "if (E)  S;"  as  if  it  were  t he  application  of  a  function 
if to  E  and  S.  Let  t he  special  type  void  denote  t he  absence  of  a  value.  Then 
function  if  expects  to  be  applied  to  a  boolean  and  a  void; 
t he  result  of  t he 
application  is  a  void. 

6.5.2  Type  Conversions 

Consider  expressions  like  x  +  i,  where  x  is  of  type  float  and  i  is  of  type  inte 
ger.  Since  the  representation  of integers  and  floating-point  numbers  is  different 
within  a  computer  and  different  machine  instructions  are  used  for  operations 
on  integers  and  floats,  the  compiler  may  need  to  convert  one  of  the  operands  of 
+  to  ensure  t h at  b o th  operands  are  of the  same  type  when  the  addition  occurs. 
Suppose  t h at  integers  are  converted  to  floats  when  necessary,  using  a  unary 
operator  ( f l o a t ).  For  example,  the  integer 2  is  converted  to  a  float  in  the  code 
for  the  expression 2*3.14: 

ti  =  ( f l o a t)  2 
t2  =  ti  *  3.14 

We  can  extend  such  examples  to  consider  integer  and  float  versions  of  the 
operators;  for  example,  i n t*  for  integer  operands  and  f l o a t*  for  floats. 

Type  synthesis  will  be  illustrated  by  extending  the  scheme  in  Section  6.4.2 
for  translating  expressions.  We  introduce  another  a t t r i b u te  E.type,  whose  value 
is  either  integer  or  float.  T he  rule  associated  with  E 
E\  +  E2  builds  on  t he 
pseudocode 

if  (  Ei.type  =  integer  a nd  E2.type  =  integer  ) 
e l se  if  (  Ei.type  =  float  a nd  E2.type  —  integer  ) 

E.type  —  integer, 
•  •  • 

As  the  number  of  types  subject  to  conversion  increases,  t he  number  of  cases 
increases  rapidly.  Therefore  with  large  numbers  of  types,  careful  organization 
of  the  semantic  actions  becomes  important. 

Type  conversion  rules  vary  from  language  to  language.  T he  rules  for  Java 
in  Fig.  6.25  distinguish  between  widening  conversions,  which  are  intended  to 
preserve  information,  and  narrowing  conversions,  which  can  lose  information. 
T he  widening  rules  are  given  by  the  hierarchy  in  Fig.  6.25(a):  any  type  lower 
in  the  hierarchy  can  be  widened  to  a  higher  type.  Thus,  a  char  can  be  widened 
to  an  int  or  to  a  float,  but  a  char  cannot  be  widened  to  a  short.  T he  narrowing 
rules  are  illustrated  by  the  graph  in  Fig.  6.25(b):  a  type  s  can  be  narrowed  to  a 
type  t  if  there  is  a  path  from  s  to  t.  Note  t h at  char,  short,  and  byte  are  pairwise 
convertible  to  each  other. 

Conversion  from  one  type  to  another  is  said  to  be  implicit  if  it  is  done 
automatically  by  the  compiler.  Implicit  type  conversions,  also  called  coercions, 

6.5. 

TYPE  CHECKING 

389 

double 

float 

long 

int 

/  \ 

short 

byte 

char 

(a)  Widening  conversions 

(b)  Narrowing  conversions 

Figure  6.25:  Conversions  between  primitive  types  in  Java 

are  limited  in  many  languages  to  widening  conversions.  Conversion  is  said  to 
be  explicit  if  t he  programmer  must  write  something  to  cause  t he  conversion. 
Explicit  conversions  are  also  called  casts. 

T he  semantic  action  for  checking  E  -»  E\  +  E2  uses  two  functions: 

1.  max(t\,t2)  takes  two  types  ti  and  t2  and  returns  the  maximum  (or  least 
upper  bound)  of  the  two  types  in  t he  widening  hierarchy.  It  declares  an 
error  if either  t\  or  t2  is  not  in  the  hierarchy;  e.g.,  if either  type  is  an  array 
or  a  pointer  type. 

2.  widen(a,  t,  w)  generates  type  conversions  if  needed  to  widen  an  address 
a  of  type  t  into  a  value  of  t y pe  w. 
It  returns  a  itself  if  t  and  w  are  t he 
same  type.  Otherwise,  it  generates  an  instruction  to  do  the  conversion 
and  place  t he  result  in  a  temporary  t,  which  is  returned  as  the  result. 
Pseudocode  for  widen,  assuming  t h at  t he  only  types  are  integer  and  float, 
appears  in  Fig.  6.26. 

Addr  widen(Addr  a,  Type  t,  Type  w) 
if  (  t  =  w )  return  a; 
else  if  (  t  =  integer a nd  w  = 
temp  —  n ew  TempQ; 
gen(temp '='  '(float)'  a); 
return 

temp; 

float)  { 

} 
else  error; 

} 

Figure  6.26:  Pseudocode  for  function  widen 

390 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

The  semantic  action  for  E  -»  E\  +  E2  in  Fig.  6.27  illustrates  how  type 
conversions  can  be  added  to  the  scheme  in  Fig.  6.20  for  translating  expressions. 
In  the  semantic  action,  temporary  variable  a\  is  either  Ei.addr,  if  t he  type  of 
Ei  does  not  need  to  be  converted  to  the  type  of  E,  or  a  new  t e m p o r a ry  variable 
returned  by  widen  if  this  conversion  is  necessary.  Similarly,  a2  is  either  E2.addr 
or  a  new  temporary  holding  the  type-converted  value  of  E2.  Neither  conversion 
is  needed  if  b o th  types  are  integer  or  both  are  float.  In  general,  however,  we 
could  find  t h at  the  only  way  to  add  values  of  two  different  types  is  to  convert 
them  both  to  a  third  type. 

E 

-»  Ei  +  E2 

{  E.type  =  max(Ei.type,  E2.type); 
ai  =  widen(Ei.  dddr,  Ei. type,  E. type); 
a2  —  widen(E2. addr,  E2 • type,  E. type); 
E. addr  —  n ew  Temp  (); 
gen(E.addr  '— 

'+'  a2);  } 

ai 

Figure  6.27:  Introducing  type  conversions  into  expression  evaluation 

6.5.3  Overloading  of  Functions  and  Operators 

An  overloaded  symbol  has  different  meanings  depending  on  its  context.  Over 
loading  is  resolved  when  a  unique  meaning  is  determined  for  each  occurrence 
of  a  name. 
In  this  section,  we  restrict  attention  to  overloading  t h at  can  be 
resolved  by  looking  only  at  t he  arguments  of  a  function,  as  in  Java. 

E x a m p le  6 . 1 3:  T he  +  operator  in  Java  denotes  either  string  concatenation 
or  addition,  depending  on  the  types  of its  operands.  User-defined  functions  can 
be  overloaded  as  well,  as  in 

v o id  e r r ()  {  • • •  } 
v o id  e r r ( S t r i ng  s)  {  •••  } 

Note  t h at  we  can  choose  between  these  two  versions  of a  function  e rr  by  looking 
at  their  arguments. 

• 

The  following  is  a  type-synthesis  rule  for  overloaded  functions: 

if /  can  have  type  Si  -»  U,  for  1  <  i  <  n,  where  Si  ^  Sj  for  i  ^  j 
a nd  x  has  type  Sk,  for  some  1  <  k  <  n 
t h en  expression  f(x)  has  type  tu 

(6.10) 

T he  value-number  method  of  Section  6.1.2  can  be  applied  to  type  expres 
sions  to  resolve  overloading  based  on  argument  types,  efficiently. 
In  a  DAG 
representing  a  type  expression,  we  assign  an  integer  index,  called  a  value  num 
ber,  to  each  node.  Using  Algorithm  6.3,  we  construct  a  signature  for  a  node, 

6.5. 

TYPE  CHECKING 

391 

consisting  of its  label  and  the  value  numbers  of its  children,  in  order  from  left  to 
right.  The  signature  for  a  function  consists  of  t he  function  name  and  the  types 
of  its  arguments.  The  assumption  t h at  we  can  resolve  overloading  based  on 
t he  types  of  arguments  is  equivalent  to  saying  t h at  we  can  resolve  overloading 
based  on  signatures. 

It  is  not  always  possible  to  resolve  overloading  by  looking  only  at  the  argu 

ments  of  a  function.  In  Ada,  instead  of  a  single  type,  a  subexpression  standing 
alone  may  have  a  set  of possible  types  for  which  the  context  must  provide  suffi 
cient  information  to  narrow  the  choice  down  to  a  single  type  (see  Exercise  6.5.2). 

6.5.4  Type  Inference  and  Polymorphic  Functions 

T y pe  inference  is  useful  for  a  language  like  ML,  which  is  strongly  typed,  but 
does  not  require  names  to  be  declared  before  they  are  used.  Type  inference 
ensures  t h at  names  are  used  consistently. 

T he  term  "polymorphic"  refers  to  any  code  fragment  t h at  can  be  executed 
with  arguments  of  different  types.  In  this  section,  we  consider  parametric  poly 
morphism,  where  the  polymorphism  is  characterized  by  parameters  or  type 
variables.  T he  running  example  is  the  ML  program  in  Fig.  6.28,  which  defines 
a  function  length.  T he  type  of  length  can  be  described  as,  "for  any  type  a, 
length  maps  a  list  of  elements  of  type  a  to  an  integer." 

f un  length(x)  = 

if  nullix) 

t h en  0  e l se  length(tl(x))  -f  1; 

Figure  6.28:  ML  program  for  the  length  of  a  list 

E x a m p le  6 . 1 4:  In  Fig.  6.28,  t he  keyword  f un  introduces  a  function  definition; 
functions  can  be  recursive.  The  program  fragment  defines  function  length  with 
one  parameter  x.  T he  body  of  the  function  consists  of  a  conditional  expression. 
T he  predefined  function  null  tests  whether  a  list  is  empty,  and  the  predefined 
function  tl  (short  for  "tail")  returns  the  remainder  of  a  list  after  t he  first  element 
is  removed. 

The  function  length  determines  the  length  or  number  of  elements  of  a  list 
x.  All  elements  of  a  list  must  have  t he  same  type,  but  length  can  be  applied  to 
lists  whose  elements  are  of  any  one  type.  In  the  following  expression,  length  is 
applied  to  two  different  types  of  lists  (list  elements  are  enclosed  within  "["  and 
"]"): 

length{[" sun",  "mon",  " t u e " ])  +  length([10,9,8,  7]) 

(6.11) 

T he  list  of  strings  has  length  3  and  the  list  of  integers  has  length  4,  so  expres 
sion  (6.11)  evaluates  to  7. 

• 

392 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

Using  the  symbol  V  (read  as  "for  any  type")  and  the  type  constructor  list, 

the  type  of  length  can  be  written  as 

Vet.  list(a)  ->•  integer 

(6.12) 

The  V  symbol  is  the  universal  quantifier,  and  the  type  variable  to  which  it 
is  applied  is  said  to  be  bound  by  it.  Bound  variables  can  be  renamed  at  will, 
provided  all  occurrences  of the  variable  are  renamed.  Thus,  the  type  expression 

V/?.  Iist(f3)  -»  integer 

is  equivalent  to  (6.12).  A  type  expression  with  a  V  symbol  in  it  will  be  referred 
to  informally  as  a  "polymorphic  type." 

Each  time  a  polymorphic  function  is  applied,  its  bound  type  variables  can 
denote  a  different  type.  During  type  checking,  at  each  use  of  a  polymorphic 
type  we  replace  the  bound  variables  by  fresh  variables  and  remove  the  universal 
quantifiers. 

The  next  example  informally  infers  a  type  for  length,  implicitly  using  type 

inference  rules  like  (6.9),  which  is  repeated  here: 

if  f(x)  is  an  expression, 
t h en  for  some  a  and  /3,  /  has  type  a  ->  (3  a nd  x  has  type  a 

E x a m p le  6.15  :  T he  abstract  syntax  tree  in  Fig.  6.29  represents  the  definition 
of  length  in  Fig.  6.28.  The  root  of the  tree,  labeled  fun,  represents  the  function 
definition.  T he  remaining  nonleaf nodes  can  be  viewed  as  function  applications. 
T he  node  labeled  -+-  represents  the  application  of  the  operator  +  to  a  pair  of 
children.  Similarly,  the  node  labeled  if represents  the  application  of an  operator 
if to  a  triple  formed  by  its  children  (for  type  checking,  it  does  not  m a t t er  t h at 
either  the  t h en  or  the  else  part  will  be  evaluated,  but  not  both). 

Figure  6.29:  Abstract  syntax  tree  for  the  function  definition  in  Fig.  6.28 

From  the  body  of function  length,  we  can  infer  its  type.  Consider  the  children 
of  the  node  labeled  if,  from  left  to  right.  Since  null  expects  to  be  applied  to 
lists,  x  must  be  a  list.  Let  us  use  variable  a  as  a  placeholder  for  the  type  of the 
list  elements;  t h at  is,  x  has  type  "list  of  a." 

6.5. 

TYPE  CHECKING 

393 

Substitutions,  Instances,  and  Unification 

If t  is  a  type  expression  and  5  is  a  substitution  (a  mapping  from  type  vari 
ables  to  type  expressions),  then  we  write  S(i)  for  the  result  of  consistently 
replacing  all  occurrences  of  each  type  variable  a  in  t  by  S(a). 
S(t)  is 
called  an  instance  of  t.  For  example,  list(integer)  is  an  instance  of  list(a), 
since  it  is  t he  result  of  substituting  integer for  a  in  list(a).  Note,  however, 
t h at  integer —>  float  is  not  an  instance  of a  —>  a,  since  a  substitution  must 
replace  all  occurrences  of  a  by  the  same  type  expression. 

Substitution  5  is  a  unifier  of  type  expressions  t\  and  t2 

if  S(t\)  = 
S(t2).  5  is  the  most  general  unifier  of  t\  and  t2  if  for  any  other  unifier  of 
ri  and  t2,  say  S",  it  is  the  case  t h at  for  any  t,  S'(t)  is  an  instance  of  S(t). 
In  words,  S'  imposes  more  constraints  on  t  t h an  S  does. 

If  null(x) 

is  true,  then  length(x)  is  0.  Thus,  the  type  of  length  must  be 
"function  from  list  of  a  to  integer."  This  inferred  type  is  consistent  with  the 
usage  of  length  in  t he  else  part,  length(tl{x))  +  1. 

• 

Since  variables  can  appear  in  type  expressions,  we  have  to  re-examine  the 
notion  of  equivalence  of  types.  Suppose  E\  of  type  s 
s'  is  applied  to  E2  of 
type  t.  Instead  of  simply  determining  the  equality  of  s  and  t,  we  must  "unify" 
them. 
Informally,  we  determine  whether  s  and  t  can  be  made  structurally 
equivalent  by  replacing  the  type  variables  in  s  and  t  by  type  expressions. 

A  substitution  is  a  mapping  from  type  variables  to  type  expressions.  We 
write  S(t)  for  the  result  of  applying  the  substitution  S  to  the  variables  in  type 
expression  t;  see  t he  box  on  "Substitutions,  Instances,  and  Unification."  Two 
type  expressions  t\  and  t2  unify  if  there  exists  some  substitution  5  such  t h at 
S(ti)  =  S(t2).  In  practice,  we  are  interested  in  the  most  general  unifier,  which 
is  a  substitution  t h at  imposes  the  fewest  constraints  on  the  variables  in  the 
expressions.  See  Section  6.5.5  for  a  unification  algorithm. 

A l g o r i t hm  6 . 1 6:  Type  inference  for  polymorphic  functions. 

I N P U T:  A  program  consisting  of  a  sequence  of function  definitions  followed  by 
an  expression  to  be  evaluated.  An  expression  is  made  up  of function  applications 
and  names,  where  names  can  have  predefined  polymorphic  types. 

O U T P U T:  Inferred  types  for  the  names  in  the  program. 

M E T H O D:  For simplicity,  we shall  deal with unary functions  only.  T he type of a 
function  f(xi,x2)  with  two  parameters  can  be  represented  by  a  t y pe  expression 
si  x  s2  ->•  t,  where  si  and  s2  are  the  types  of x\  and  x2,  respectively,  and  t  is  t he 
type  of  the  result  f(xi,x2).  An  expression  / ( a,  b)  can  be  checked  by  matching 
t he  type  of  a  with  si  and  the  type  of  b  with  s2. 

394 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

Check  the  function  definitions  and  the  expression  in  the  input  sequence.  Use 

the  inferred  type  of  a  function  if  it  is  subsequently  used  in  an  expression. 

•  For  a  function  definition  f un  i d i ( i d2)  =  E,  create  fresh  type  variables  a 
and  (3.  Associate  the  type  a  ->  (3  with  the  function  i d i,  and  t he  type  a 
with  the  parameter  i d2.  Then,  infer  a  type  for  expression  E.  Suppose 
a  denotes  type  s  and  j3  denotes  type  t  after  type  inference  for  E.  The 
inferred  type  of function  i di  is  s  ->  t.  Bind  any  type  variables  t h at  remain 
unconstrained  in  s  -»  t  by  V  quantifiers. 

•  For  a  function  application  Ei(E2),  infer  types  for  E\  and  E2.  Since  Ei  is 
used  as  a  function,  its  type  must  have  the  form  s  -»•  s'.  (Technically,  the 
7,  where  j3  and  7  are  new  type  variables). 
type  of E\  must  unify  with  j3 
Let  t  be  the  inferred  type  of  E\.  Unify  s  and  t. 
If  unification  fails,  the 
expression  has  a  type  error.  Otherwise,  t he  inferred  type  of E\(E2)  is  s'. 

•  For  each  occurrence  of  a  polymorphic  function,  replace  t he  bound  vari 
ables  in  its  type  by  distinct  fresh  variables  and  remove  the  V  quantifiers. 
The  resulting  type  expression  is  the  inferred  type  of  this  occurrence. 

•  For  a name  t h at  is  encountered  for  the  first  time,  introduce  a  fresh  variable 

for  its  type. 

• 

E x a m p le  6 . 1 7:  In  Fig.  6.30,  we  infer  a  type  for  function  length.  T he  root  of 
t he  syntax  tree  in  Fig.  6.29  is  for  a  function  definition,  so  we  introduce  variables 
13  and  7,  associate  the  type  j3 
7  with  function  length,  and  the  type  (3  with  x; 
see  lines  1-2  of  Fig.  6.30. 

At  the  right  child  of  the  root,  we  view  if  as  a  polymorphic  function  t h at  is 
applied  to  a  triple,  consisting  of  a  boolean  and  two  expressions  t h at  represent 
the  t h en  and  e l se  parts.  Its  type  is  VCK.  boolean  x  a  x  a  —>  a. 

Each  application  of  a  polymorphic  function  can  be  to  a  different  type,  so  we 
make  up  a  fresh  variable  ai  (where  i  is  from  "if")  and  remove  the  V;  see  line  3 
of  Fig.  6.30.  The  type  of  the  left  child  of  if  must  unify  with  boolean,  and  the 
types  of  its  other  two  children  must  unify  with  on. 
T he  predefined  function  null  has  type  Vet.  list(a) 

boolean.  We  use  a  fresh 
type  variable  an  (where  n  is  for  "null")  in  place  of  t he  bound  variable  a;  see 
line  4.  From  the  application  of  null  to  x,  we  infer  t h at  the  type  f3  of  x  must 
match  list(an);  see  line  5. 

At  the  first  child  of  if,  t he  type  boolean  for  null(x)  matches  the  type  expected 

by  if.  At  the  second  child,  the  type  a*  unifies  with  integer;  see  line  6. 

Now,  consider  t he  subexpression  length(tl(x))  +  1.  We  make  up  a  fresh 
variable  at  (where  t  is  for  "tail")  for  the  bound  variable  a  in  the  type  of  tl;  see 
line  8.  From  the  application  tl(x),  we  infer  list(at)  =  (3  =  list(an);  see  line  9. 

Since  length(tl(x))  is  an  operand  of  +,  its  type  7  must  unify  with  integer; 
It  follows  t h at  the  type  of  length  is  list(an)  ->•  integer.  After  t he 

see  line  10. 

6.5. 

TYPE  CHECKING 

395 

L I NE 

E X P R E S S I ON 

T Y PE 

U N I FY 

length 

x 
if 
null 
null(x) 

0 
+ 
tl 

1) 
2) 
3) 
4) 
5) 
6) 
7) 
8) 
9) 
10) 

11) 
12) 
13) 

-»  boolean 

/3 
boolean  x  ai  x  ai  —>  ai 
list(an) 
boolean 
integer 
integer  x 
list(at)  —>  list(at) 
list(at) 

integer  -» 

integer 

1 
integer 
integer 
integer 

list(at) 

7 

list(an) 
integer 

Figure  6.30:  Inferring  a  type  for  t he  function  length  of  Fig.  6.28 

function  definition  is  checked,  the  type  variable  an  remains  in  t he  type  of  length. 
Since  no  assumptions  were  made  about  an,  any  type  can  be  substituted  for  it 
when  the  function  is  used.  We  therefore  make  it  a  bound  variable  and  write 

\/an. 

list(an) 

-» 

integer 

for  t he  t y pe  of  length. 

• 

6.5.5  An  Algorithm  for  Unification 

Informally,  unification  is  t he  problem  of  determining  whether  two  expressions 
s  and  t  can  be  made  identical  by  substituting  expressions  for  the  variables  in 
s  and  t.  Testing  equality  of  expressions  is  a  special  case  of  unification;  if  s 
and  t  have  constants  but  no  variables,  then  s  and  t  unify  if  and  only  if  they 
are  identical.  T he  unification  algorithm  in  this  section  extends  to  graphs  with 
cycles,  so  it  can  be  used  to  test  structural  equivalence  of  circular  t y p e s .7 

We  shall  implement  a  graph-theoretic  formulation  of unification,  where  types 
are  represented  by  graphs.  Type  variables  are  represented  by  leaves  and  type 
constructors  are  represented  by  interior  nodes.  Nodes  are  grouped  into  equiv 
alence  classes;  if  two  nodes  are  in  the  same  equivalence  class,  then  t he  type 
expressions  they  represent  must  unify.  Thus,  all  interior  nodes  in  the  same 
class  must  be  for  t he  same  type  constructor,  and  their  corresponding  children 
must  be  equivalent. 

E x a m p le  6.18  :  Consider  t he  two  type  expressions 

7ln  some  applications,  it  is  an  error  to  unify  a  variable  with  an  expression  containing  that 

variable.  Algorithm  6.19  permits  such  substitutions. 

396 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

a2)  x  Ust(a3))  -+  Ust(ct2) 

((ai 
((as -»• 0 : 4) x list(a3)) -»• 0:5 

T he  following  substitution 5  is  the  most  general  unifier  for  these  expressions 

x 
ai 

S(x) 
a.i 

0L2 

0.2 
as 
a4 
a^  Ust(a2) 

CKI 
a2 

This  substitution  maps  the  two  type  expressions  to  the  following  expression 

((ax  -» 0 : 2)  x  /«si(cKi)) —y list(a2) 

T he  two  expressions  are  represented  by  the  two  nodes  labeled  - »:  1  in  Fig.  6.31. 
The  integers  at  the  nodes  indicate  the  equivalence  classes  t h at  the  nodes  belong 
to  after  the  nodes  numbered  1  are  unified. 

• 

-h-  1 

1 

a\  : 

Figure  6.31:  Equivalence  classes  after  unification 

A l g o r i t hm  6 . 1 9:  Unification  of  a  pair  of  nodes  in  a  type  graph. 

I N P U T:  A  graph  representing  a  type  and  a  pair  of nodes  m  and  n  to  be  unified. 

O U T P U T:  Boolean  value  true  if  the  expressions  represented  by  the  nodes  m 
and  n  unify;  false,  otherwise. 

M E T H O D:  A  node  is  implemented  by  a  record  with  fields  for  a binary  operator 
and  pointers  to  the  left  and  right  children.  T he  sets  of  equivalent  nodes  are 
maintained  using the  set  field.  One  node  in  each  equivalence  class  is  chosen to  be 
the  unique  representative  of the  equivalence  class  by  making  its  set field contain 
a  null  pointer.  The  set fields of the  remaining nodes  in  the  equivalence  class  will 
point  (possibly  indirectly  through  other  nodes  in  the  set)  to  the  representative. 
Initially,  each  node  n  is  in  an  equivalence  class  by  itself,  with  n  as  its  own 
representative  node. 

T he  unification  algorithm,  shown  in  Fig.  6.32,  uses  the  following  two  oper 

ations  on  nodes: 

6.5. 

TYPE  CHECKING 

397 

boolean  unify(Node  m,  Node  n)  { 
t  =  find(n); 

s  =  find(m); 
if  (  s  —  t  )  r e t u rn  true; 
e l se  if  (  nodes  s  and  t  represent  the  same  basic  type  )  r e t u rn  true; 
e l se  if  (s  is  an  op-node  with  children  si  and  s2  a nd 

t  is  an  op-node  with  children  t\  and  t2)  { 

union(s, 
r e t u rn 

t); 
unify(s\,t\) 

a nd 

unify(s2,t2); 

} 
e l se  if s  or  t  represents  a  variable  { 

union(s,t); 
r e t u rn 

true; 

} 
e l se  r e t u rn  false; 

} 

Figure  6.32:  Unification  algorithm. 

•  find{n)  returns  the  representative  node  of  t he  equivalence  class  currently 

containing  node  n. 

•  union(m,  n)  merges  the  equivalence  classes  containing  nodes  m  and  n.  If 
one  of the  representatives  for  the  equivalence  classes  of  m  and  n  is  a  non-
variable  node,  union  makes  t h at  nonvariable  node  be  the  representative 
for  the  merged  equivalence  class;  otherwise,  union  makes  one  or  the  other 
of  the  original  representatives  be  t he  new  representative.  This  asymme 
try  in  the  specification  of  union  is  important  because  a  variable  cannot 
be  used  as  the  representative  for  an  equivalence  class  for  an  expression 
containing  a  type  constructor  or  basic  type.  Otherwise,  two  inequivalent 
expressions  may  be  unified  through  t h at  variable. 

T he  union  operation  on  sets  is  implemented  by  simply  changing  the  set  field 

of  t he  representative  of  one  equivalence  class  so  t h at  it  points  to  the  represen 
tative  of  t he  other.  To  find  t he  equivalence  class  t h at  a  node  belongs  to,  we 
follow  t he  set  pointers  of  nodes  until  the  representative  (the  node  with  a  null 
pointer  in  the  set  field)  is  reached. 

Note  t h at  t he  algorithm  in  Fig.  6.32  uses  s  =  find(m)  and  t  =  find(n)  rather 
t h an  m  and  n,  respectively.  T he  representative  nodes  s  and  t  are  equal  if  m 
and  n  are  in  the  same  equivalence  class. 
If  s  and  t  represent  t he  same  basic 
type,  the  call  unify(m,  n)  returns  true.  If  s  and  t  are  b o th  interior  nodes  for  a 
binary  type  constructor,  we  merge  their  equivalence  classes  on  speculation  and 
recursively  check  t h at  their  respective  children  are  equivalent.  By  merging  first, 
we  decrease  the  number  of  equivalence  classes  before  recursively  checking  t he 
children,  so  t he  algorithm  terminates. 

398 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

The  substitution  of  an  expression  for  a  variable  is  implemented  by  adding 
the  leaf  for  the  variable  to  the  equivalence  class  containing  t he  node  for  t h at 
expression.  Suppose  either  m  or  n  is  a  leaf  for  a  variable.  Suppose  also  t h at 
this  leaf  has  been  put  into  an  equivalence  class  with  a  node  representing  an 
expression  with  a  type  constructor  or  a  basic  type.  Then  find  will  r e t u rn 
a  representative  t h at  reflects  t h at  type  constructor  or  basic  type,  so  t h at  a 
variable  cannot  be  unified  with  two  different  expressions. 

• 

E x a m p le  6 . 2 0:  Suppose  t h at  the  two  expressions  in  Example  6.18  are  repre 
sented  by  the  initial  graph  in  Fig.  6.33,  where  each  node  is  in  its  own  equiv 
alence  class.  When  Algorithm  6.19  is  applied  to  compute  unify(l,9),  it  notes 
t h at  nodes  1  and  9  both  represent  the  same  operator.  It  therefore  merges  1  and 
9  into  the  same  equivalence  class  and  calls  unify(2,10)  and  unify(8,14).  T he 
• 
result  of  computing  unify(l,  9)  is  t he  graph  previously  shown  in  Fig.  6.31. 

-K- 1 

-*: 9 

on  :  4 

a.%  :  5 

0:3  :  7 

ct4  :  12 

Figure  6.33:  Initial  graph  with  each  node  in  its  own  equivalence  class 

If  Algorithm  6.19  returns  true,  we  can  construct  a  substitution  S  t h at  acts 
as  t he  unifier,  as  follows.  For  each  variable  a,  find(a)  gives  t he  node  n  t h at 
is  the  representative  of  the  equivalence  class  of  a.  T he  expression  represented 
by  n  is  S(a).  For  example,  in  Fig.  6.31,  we  see  t h at  t he  representative  for 
«3  is  node  4,  which  represents  a\.  The  representative  for  a§  is  node  8,  which 
represents  list(a.2)-  T he  resulting  substitution  S  is  as  in  Example  6.18. 

6.5.6  Exercises  for  Section  6.5 

E x e r c i se  6 . 5 . 1:  Assuming  t h at  function  widen  in  Fig.  6.26  can  handle  any 
of  the  types  in  the  hierarchy  of  Fig.  6.25(a),  translate  t he  expressions  below. 
Assume  t h at  c  and  d  are  characters,  s  and  t  are  short  integers,  i  and  j  are 
integers,  and  £  is  a  float. 

a)  x  =  s  +  c. 

b)  i  =  s  +  c. 

c)  x  =  (s  +  c)  *  (t  +  d ). 

6.6. 

CONTROL  FLOW 

399 

E x e r c i se  6 . 5 . 2:  As  in  Ada,  suppose  t h at  each  expression  must  have  a  unique 
type,  but  t h at  from  a  subexpression,  by  itself,  all  we  can  deduce  is  a  set  of  pos 
sible  types.  T h at  is,  the  application  of  function  Ei  to  argument  E2,  represented 
by  E  —>  Ei  (Ei),  has  the  associated  rule 

E.type  = 

{t  \ 

for  some  s  in  E2.type,  s  ->•  t  is  in  Ei.type  } 

Describe  an  SDD  t h at  determines  a  unique  type  for  each  subexpression  by 
using  an  a t t r i b u te  type  to  synthesize  a  set  of  possible  types  b o t t o m - u p,  and, 
once  t he  unique  type  of t he  overall  expression  is  determined,  proceeds  top-down 
to  determine  a t t r i b u te  unique  for  t he  type  of  each  subexpression. 

6.6  Control  Flow 

T he  translation  of  statements  such  as  if-else-statements  and  while-statements 
is  tied  to  t he  translation  of  boolean  expressions. 
In  programming  languages, 
boolean  expressions  are  often  used  to 

1.  Alter  the 

flow  of  control.  Boolean  expressions  are  used  as  conditional 

expressions  in  statements  t h at  alter  the  flow  of  control.  The  value  of such 
boolean  expressions  is  implicit  in  a  position  reached  in  a  program.  For 
example,  in  if  (E)  5,  the  expression  E  must  be  t r ue  if  statement  S  is 
reached. 

2.  Compute  logical  values.  A  boolean  expression  can  represent  true  Or  false 
as  values.  Such  boolean  expressions  can  be  evaluated  in  analogy  to  arith 
metic  expressions  using  three-address  instructions  with  logical  operators. 

The  intended  use  of  boolean  expressions  is  determined  by  its  syntactic  con 
text.  For  example,  an  expression  following  the  keyword  if  is  used  to  alter  the 
flow  of  control,  while  an  expression  on  the  right  side  of  an  assignment  is  used 
to  denote  a  logical  value.  Such  syntactic  contexts  can  be  specified  in  a  number 
of  ways:  we  may  use  two  different  nonterminals,  use  inherited  attributes,  or 
set  a  flag  during  parsing.  Alternatively  we  may  build  a  syntax  tree  and  invoke 
different  procedures  for  the  two  different  uses  of  boolean  expressions. 

This  section  concentrates  on  the  use  of  boolean  expressions  to  alter  the  flow 
of  control.  For  clarity,  we  introduce  a  new  nonterminal  B  for  this  purpose. 
In  Section  6.6.6,  we  consider  how  a  compiler  can  allow  boolean  expressions  to 
represent  logical  values. 

6.6;1  Boolean  Expressions 

Boolean  expressions  are  composed  of  the  boolean  operators  (which  we  denote 
&&,  I  I,  and  !,  using  the  C  convention  for  the  operators  AND,  OR,  and  N O T, 
respectively)  applied  to  elements  t h at  are  boolean  variables  or  relational  ex 
pressions.  Relational  expressions  are  of  the  form  E±  r el  E2,  where  Ex  and 

400 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

E2  are  arithmetic  expressions.  In  this  section,  we  consider  boolean  expressions 
generated  by  t he  following  grammar: 

B  ->  B I |  B 

|  B  kk  B 

| 

!  B 

| 

(  B  ) 

\  E  rel  E 

|  t r ue 

|  false 

We  use  the  attribute  rel. op  to  indicate  which  of the  six  comparison  operators 
<,  < =,  =,  !  =,  >,  or  >=  is  represented  by  rel.  As  is  customary,  we  assume 
t h at I I  and  &;&  are  left-associative,  and  t h at  I  I  has  lowest  precedence,  then 
&&,  then  !. 

Given  t he  expression  Bi  I I  B2,  if  we  determine  t h at  B\  is  true,  then  we 
can  conclude  t h at  t he  entire  expression  is  true  without  having  to  evaluate  B2. 
Similarly,  given  B\k,kB2,  if  Bi  is  false,  then  the  entire  expression  is  false. 

The  semantic  definition  of  t he  programming  language  determines  whether 
all  parts  of  a  boolean  expression  must  be  evaluated.  If  t he  language  definition 
permits  (or  requires)  portions  of  a  boolean  expression  to  go  unevaluated,  then 
the  compiler  can  optimize  the  evaluation  of  boolean  expressions  by  computing 
only  enough  of  an  expression  to  determine  its  value.  Thus,  in  an  expression 
such  as  B\ 
I  I  B2,  neither  B\  nor  B2  is  necessarily  evaluated  fully.  If  either  B\ 
or  B2  is  an  expression  with  side  effects  (e.g.,  it  contains  a  function  t h at  changes 
a  global  variable),  then  an  unexpected  answer  may  be  obtained. 

6.6.2 

Short-Circuit  Code 

In  short-circuit  (or  jumping)  code,  t he  boolean  operators  &&,  I  I,  and  !  trans 
late  into  jumps.  The  operators  themselves  do  not  appear  in  t he  code;  instead, 
the  value  of  a  boolean  expression  is  represented  by  a  position  in  the  code  se 
quence. 

E x a m p le  6 . 2 1:  T he  statement 

if  (  x  <  100  II  x  >  200  &&  x  !=  y  )  x  =  0; 

might  be  translated  into  t he  code  of  Fig. 6.34.  In  this  translation,  t he  boolean 
expression  is  true  if  control  reaches  label  L2.  If  t he  expression  is  false,  control 
goes  immediately  to  Lu  skipping  L2  and  the  assignment  x  =  0.  • 

if  x  <  100  goto  L2 
i f F a l se  x  >  200 goto Li 
i f F a l se  x 
x  =  0 

!=  y  goto  Li 

L2: 
Li: 

Figure 6.34:  Jumping  code 

6.6. 

CONTROL  FLOW 

401 

6.6.3 

Flow-of-Control  Statements 

We  now  consider  t he  translation  of  boolean  expressions  into  three-address  code 
in  the  context  of  statements  such  as  those  generated  by  t he  following  grammar: 

S 
S 
S 

if  (  B  )  Si 
if  (  B  )  Si  e l se  S2 

-» 
->  w h i le  (  5  )  Si 

In  these  productions,  nonterminal  B  represents  a  boolean  expression  and  non 
terminal  S  represents  a  statement. 

This  g r a m m ar  generalizes  t he  running  example  of  while  expressions  t h at  we 
introduced  in  Example  5.19.  As  in  t h at  example,  b o th  B  and  S  have  a  synthe 
sized  a t t r i b u te  code,  which  gives  the  translation  into  three-address  instructions. 
For  simplicity,  we  build  up  the  translations  B.code  and  S.code  as  strings,  us 
ing  syntax-directed  definitions.  The  semantic  rules  defining  t he  code  attributes 
could  be  implemented  instead  by  building  up  syntax  trees  and  then  emitting 
code  during  a  tree  traversal,  or  by  any  of the  approaches  outlined  in  Section  5.5. 
The  translation  of  if  (B)  Si  consists  of  B.code  followed  by  Si.code,  as  illus 
t r a t ed  in  Fig.  6.35(a).  Within  B.code  are  jumps  based  on  the  value  of  B.  If  B 
is  true,  control  flows  to  t he  first  instruction  of  Si.code,  and  if  B  is  false,  control 
flows  to  t he  instruction  immediately  following  S i. code. 

to  B.true 

to  B.false 

B.  true 

B.false 

S.next 

B.  code 

Si.  code 

goto  S.next 

S2.code 

(b)  if-else 

to  B.true 

to  B.false 

B.true 

: 

B.false 

: 

B.  code 

Si.  code 

(a)  if 

to  B.true 

to  B.false 

begin  : 

B.true 

: 

B.  code 

Si.code 

goto  begin 

B.false 

: 

(c)  while 

Figure  6.35:  Code  for  if-,  if-else-,  and  while-statements 

T he  labels  for  t he  j u m ps  in  B.code  and  S.code  are  managed  using  inherited 
attributes.  W i th  a  boolean  expression  B,  we  associate  two  labels:  B.true,  the 

402 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

label  to  which  control  flows  if  B  is  true,  and  B.false,  t he  label  to  which  control 
flows  if  B  is  false.  With  a  statement  S,  we  associate  an  inherited  a t t r i b u te 
S.next  denoting  a  label  for  the  instruction  immediately  after  the  code  for  S. 
In  some  cases,  the  instruction  immediately  following  S.code  is  a  j u mp  to  some 
label  L.  A  j u mp  to  a  j u mp  to  L  from  within  S.code  is  avoided  using  S.next. 

T he  syntax-directed  definition  in  Fig.  6.36-6.37  produces  three-address  code 

for  boolean  expressions  in  the  context  of  if-,  if-else-,  and  while-statements. 

P R O D U C T I ON 
-»  s 

P 

S E M A N T IC  R U L ES 

S.next  = 

newlabelQ 

P.code  =  S.code  || 

label(S.next) 

S  ->  a s s i gn 

S.code  —  assign, code 

S 

-> 

if(B)S1 

s  ->• 

if  (  B  )  Si  e l se  S2 

s 

w h i le  (  B  )  Si 

B.true  = 
B.false  = 
S.code  =  B.code  ||  labelQB .true)  ||  Si.code 

newlabelQ 
Si.next  = 

S.next 

B.true  = 
B.false  = 
Si.next  = 
S.code  =  B.code 

newlabelQ 
newlabelQ 
S2.next  = 

S.next 

\\  Si.code 

label(B.true) 

|| 
||  gen('goto'  S.next) 
|| 

label(B.false) 

\\  S^.code 

begin  —  newlabelQ 
B.true  = 
B.false  = 
Si.next  — 
S.code  — 

newlabelQ 
S.next 
begin 
label(begin)  ||  B.code 
|| 
||  geniigoto'  &e#m) 

label(B.true) 

\\  Si.code 

s 

Si  S2 

Si.next  = 
S2-next  — 
S.code  =  Si.code  || 

newlabelQ 
S.next 

label(Si.next) 

\\  S2.code 

Figure  6.36:  Syntax-directed  definition  for  flow-of-control  statements. 

We  assume  t h at  newlabelQ  creates  a  new  label  each  time  it  is  called,  and  t h at 
label(L)  attaches  label  L  to  the  next  three-address  instruction  to  be  generated.8 

8If  implemented  literally,  the  semantic  rules  will  generate  lots  of  labels  and  may  attach 
more  than  one  label  to  a  three-address  instruction.  The  backpatching  approach  of Section  6.7 

6.6. 

CONTROL  FLOW 

403 

A  program  consists  of a  statement  generated  by  P  ->  S.  T he  semantic  rules 
associated  with  this  production  initialize  S.next  to  a  new  label.  P.code  consists 
of  S.code  followed  by  t he  new  label  S.next.  Token  a s s i gn  in  t he  production 
S  —>  a s s i gn  is  a  placeholder  for  assignment  statements.  T he  translation  of 
assignments  is  as  discussed  in  Section  6.4;  for  this  discussion  of  control  flow, 
S.code  is  simply  assign.code. 

In  translating  S  ->•  if  (B)  Si,  the  semantic  rules  in  Fig.  6.36  create  a  new 
label  B.true  and  attach  it  to  the  first  three-address  instruction  generated  for 
the  statement  Si,  as  illustrated  in  Fig.  6.35(a).  Thus,  j u m ps  to  B.true  within 
t he  code  for  B  will  go  to  t he  code  for  Si.  Further,  by  setting  B.false  to  S.next, 
we  ensure  t h at  control  will  skip  the  code  for  Si  if  B  evaluates  to  false. 

In  translating  the  if-else-statement  S 

if  (B)  Si  e l se  S2,  the  code  for  the 
boolean  expression  B  has  j u m ps  out  of it  to  the  first  instruction  of  the  code  for 
51  if  B  is  true,  and  to  the  first  instruction  of  the  code  for  S2  if  B  is  false,  as 
illustrated  in  Fig.  6.35(b).  Further,  control  flows  from  both  Si  and  S2  to  t he 
three-address  instruction  immediately  following  the  code  for  S  —  its  label  is 
given  by  the  inherited  attribute  S.next.  An  explicit  g o to  S.next  appears  after 
t he  code  for  Si  to  skip  over  the  code  for  S2.  No  goto  is  needed  after  S2,  since 
Si.next  is  the  same  as  S.next. 

The  code  for  S  —>•  w h i le  (B)  Si  is  formed  from  B.code  and  Si.code  as  shown 

in  Fig.  6.35(c).  We  use  a  local  variable  begin  to  hold  a  new  label  attached  to 
the  first  instruction  for  this  while-statement,  which  is  also  t he  first  instruction 
for  B.  We  use  a  variable  rather  t h an  an  attribute,  because  begin  is  local  to 
t he  semantic  rules  for  this  production.  The  inherited  label  S.next  marks  the 
instruction  t h at  control  must  flow  to  if  B  is  false;  hence,  B.false  is  set  to  be 
S.next.  A  new  label  B.true  is  attached  to  the  first  instruction  for  S i;  the  code 
for  B  generates  a j u mp  to  this  label  if  B  is  true.  After  t he  code  for  Si  we  place 
the  instruction  g o to  begin,  which  causes  a  j u mp  back  to  t he  beginning  of  t he 
code  for  the  boolean  expression.  Note  t h at  Si.next  is  set  to  this  label  begin,  so 
j u m ps  from  within  Si.code  can  go  directly  to  begin. 

T he  code  for  S  -»  Si  S2  consists  of  the  code  for  Si  followed  by  the  code  for 
S2.  T he  semantic  rules  manage  the  labels;  the  first  instruction  after  the  code 
for  Si  is  the  beginning  of the  code  for  S2;  and  the  instruction  after  t he  code  for 
52 

is  also  the  instruction  after  the  code  for  S. 
We  discuss  the  translation  of  flow-of-control  statements  further  in  Section 
6.7.  There  we  shall  see  an  alternative  method,  called  "backpatching,"  which 
emits  code  for  statements  in  one  pass. 

6.6.4  Control-Flow  Translation  of  Boolean  Expressions 

T he  semantic  rules  for  boolean  expressions  in  Fig.  6.37  complement  t he  semantic 
rules  for  statements  in  Fig.  6.36.  As  in  t he  code  layout  of  Fig.  6.35,  a  boolean 
expression  B  is  translated  into  three-address  instructions  t h at  evaluate  B  using 

creates  labels  only  when  they  are  needed.  Alternatively,  unnecessary  labels  can  be  eliminated 
during  a  subsequent  optimization  phase. 

404 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

conditional  and  unconditional  j u m ps  to  one  of  two  labels:  B.true  if  B  is  true, 
and  B.false  if  B  is  false. 

P R O D U C T I ON 

S E M A N T IC  R U L ES 

B  ->  Bi  1 1 B2 

Bi.true  =  B.true 

Bi  .false  =  newlabelQ 
B2.true  =  B.true 
false  =  B.false 
B2. 
B.code  =  Bi.code  ||  label(Bi.  false)  | |  B2.code 

B  ->  Bi 

B2 

B 

! Bi 

Bi.true  =  newlabelQ 
Bi  .false  =  B.false 
B2.true  —  B.true 
B2.false  =  B.false 
B.code  =  Bi.code 

\\ 

Bi.true  =  B.false 
B  i.  false  =  B.true 
B.code  =  Bi.code 

label(Bi.true) 

\\  B2.  code 

B  -* Ei  rel  E2 

B.code  =  Ei.code 

||  E2.code 

||  genQif'  Ei.addr rel.op  E2.ac Idr 'goto'  B.true) 
||  </en('goto'  B.false) 

B  ->  true 

B.code  =  gen('goto'  B.true) 

B 

->  false 

B.code  —  gen('goto'  B.false) 

Figure  6.37:  Generating  three-address  code  for  booleans 

T he  fourth  production  in  Fig.  6.37,  B 

E\ rel  E2,  is  translated  directly 
into  a  comparison  three-address  instruction  with  j u m ps  to  t he  appropriate 
places.  For  instance,  B  of  the  form  a  <  b  translates  into: 

if  a  <  b  goto  B.true 
goto  B.false 

The  remaining  productions  for  B  are  translated  as  follows: 

1.  Suppose  B  is  of  t he  form  f?i  I  I  B2.  If  Bi  is  true,  then  we  immediately 
know  t h at  B  itself  is  true,  so  Bi.true  is  t he  same  as  B.true.  If  Bi  is  false, 
then  B2  must  be  evaluated,  so  we  make  Bi.false  be  t he  label  of  t he  first 
instruction  in  t he  code  for  B2.  T he  true  and  false  exits  of B2  are  t he  same 
as  the  true  and  false  exits  of  B,  respectively. 

6.6. 

CONTROL  FLOW 

405 

2.  The  translation  of  B1  kk  B2 

is  similar. 

3.  No  code  is  needed  for  an  expression  B  of  the  form  \Bi.  just  interchange 

the  true  and  false  exits  of  B  to  get  the  true  and  false  exits  of  B±. 

4.  The  constants  t r ue  and  false  translate  into  jumps  to  B.true  and  B.false, 

respectively. 

E x a m p le  6.22  :  Consider  again  the  following  statement  from  Example  6.21: 

if (  x  <  100  I I  x  >  200  &&  x  !=  y  )  x  =  0; 

(6.13) 

Using  t he  syntax-directed  definitions  in  Figs.  6.36  and  6.37  we  would  obtain 
the  code  in  Fig.  6.38. 

if  x  <  100  g o to  L2 
g o to  L3 
if  x  >  200  g o to  L4 
g o to  Li 
if  x  !=  y  g o to  L2 
g o to  Li 
x  =  0 

L3: 

L4: 

L2: 
L i: 

Figure  6.38:  Control-flow  translation  of  a  simple  if-statement 

T he  statement  (6.13)  constitutes  a  program  generated  by  P  ->  S  from 
Fig.  6.36.  T he  semantic  rules  for  the  production  generate  a  new  label  L\  for 
the  instruction  after  the  code  for  S.  Statement  S  has  t he  form  if  (B)  Si,  where 
Si  is  x  =  0 ;,  so  the  rules  in  Fig.  6.36  generate  a  new  label  L2  and  attach  it  to 
t he  first  (and  only,  in  this  case)  instruction  in  Si.code,  which  is  x  =  0. 

Since  I I  has  lower  precedence  t h an  kk,  the  boolean  expression  in  (6.13) 
\  \  B2,  where  Bi  is  x  <  100.  Following  the  rules  in  Fig.  6.37, 
has  the  form  Bi 
Bi.true  is  L2,  the  label  of  the  assignment  x  =  0 ;.  Bi.false  is  a  new  label  L3, 
attached  to  t he  first  instruction  in  t he  code  for  B2. 

Note  t h at  t he  code  generated  is  not  optimal,  in  t h at  the  translation  has 
three  more  instructions  (goto's)  t h an  the  code  in  Example  6.21.  T he  instruction 
g o to  L3  is  redundant,  since  L3  is  the  label  of  t he  very  next  instruction.  T he 
two  g o to  Li  instructions  can  be  eliminated  by  using  i f F a l se  instead  of  if 
instructions,  as  in  Example  6.21. 

• 

6.6.5  Avoiding  Redundant  Gotos 

In  Example  6.22,  t he  comparison  x  >  200  translates  into  the  code  fragment: 

406 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

if  x  >  200  g o to  L4 
g o to  Li 
••• 

L4: 

Instead,  consider  t he  instruction: 

i f F a l se  x  >  200  g o to  Li 
••• 

L4: 

This  i f F a l se  instruction  takes  advantage  of  t he  natural  flow  from  one  instruc 
tion  to  the  next  in  sequence,  so  control  simply  "falls  through"  to  label  L4  if 
x  >  200  is  false,  thereby  avoiding  a  j u m p. 

In  the  code  layouts  for  if-  and  while-statements  in  Fig.  6.35,  t he  code  for 
statement  S±  immediately  follows  the  code  for  the  boolean  expression  B.  By 
using  a  special  label  fall  (i.e.,  "don't  generate  any  j u m p " ),  we  can  adapt  the 
semantic  rules  in  Fig.  6.36  and  6.37  to  allow  control  to  fall  through  from  t he 
code  for  B  to  the  code  for  S i.  The  new  rules  for  S  -+  if  (B)  Si  in  Fig.  6.36  set 
B.true 

fall: 

to 

fall 

B.true  = 
B.false  =  Si.next  = 
S.code  =  B.code 

S.next 

||  Si.code 

Similarly,  the  rules  for  if-else-  and  while-statements  also  set  B.true  to  fall 

We  now  adapt  the  semantic  rules  for  boolean  expressions  to  allow  control  to 
fall  through  whenever  possible.  T he  new  rules  for  B  —>  E\  r el  E2  in  Fig.  6.39 
generate  two  instructions,  as  in  Fig.  6.37,  if  b o th  B.true  and  B.false  are  explicit 
labels;  t h at  is,  neither  equals  fall.  Otherwise,  if  B.true  is  an  explicit  label,  then 
B.false  must  be  fall,  so  they  generate  an  if  instruction  t h at  lets  control  fall 
through  if  the  condition  is  false.  Conversely,  if  B.false  is  an  explicit  label,  then 
they  generate  an  i f F a l se  instruction.  In  the  remaining  case,  b o th  B.true  and 
B.false  are  fall,  so  no  j u mp  in  generated.9 

In  the  new  rules  for  B 

Bi  II  B2  in  Fig.  6.40,  note  t h at  t he  meaning  of 

label  fall  for  B  is  different  from  its  meaning  for  Bi.  Suppose  B.true  is  fall;  i.e, 
control  falls  through  B,  if  B  evaluates  to  true.  Although  B  evaluates  to  true  if 
Bi  does,  Bi.true  must  ensure  t h at  control  j u m ps  over  t he  code  for  B2  to  get  to 
the  next  instruction  after  B. 

On  t he  other  hand,  if  Bi  evaluates  to  false,  the  truth-value  of  B  is  de 
termined  by  the  value  of  B2,  so  t he  rules  in  Fig.  6.40  ensure  t h at  Bi.false 
corresponds  to  control  falling  through  from  Bi  to  t he  code  for  B2. 

T he  semantic  rules  are  for  B  -»  Bi  kk  B2  are  similar  to  those  in  Fig.  6.40. 

We  leave  them  as  an  exercise. 

E x a m p le  6 . 2 3:  W i th  the  new  rules  using  the  special  label  fall,  t he  program 
(6.13)  from  Example  6.21 

9In  C  and  Java,  expressions  may  contain  assignments  within  them,  so  code  must  be  gen 
erated  for  the  subexpressions  E\  and  E2,  even  if  both  B.true  and  B.false  are  fall.  If  desired, 
dead  code  can  be  eliminated  during  an  optimization  phase. 

6.6. 

CONTROL  FLOW 

407 

test  =  Ei.addr  rel.op  E2.addr 

s  = 

gen('±f' 

if  B.true  ^  fall  a nd  B.false  ^  fall  t h en 
test  'goto'  B.true) 
if  B.true  ^  fall  t h en  gen('±f' 
e l se 
e l se  if  B.false  ^  fall  t h en  gen('if F a l s e' 
e l se  '' 

||  #en('goto'  B.false) 

test  'goto'  B.true) 

test  'goto'  B.false) 

B.code  =  Ei.code 

||  E2.code 

||  s 

Figure  6.39:  Semantic  rules  for  B  ^  Ei  rel  £?2 

if  B.true  ^  fall  t h en  B.true  e l se  newlabelQ 

Bi.true  = 
B  i.  false  =  fall 
B2.true  =  B.true 
B2.  false  =  B.false 

B.code  = 

if  B.true  ^  fall  t h en  Bi.code 
e l se  Bi.code 

\\  B2.code 

\\  B2.code 
label(Bi.true) 

|| 

Figure  6.40:  Semantic  rules  for  5  ->•  Si  I  I  _B2 

i f(  x  <  100  II  x  >  200  &&  x  !=  y  )  x  =  0; 

translates  into  t he  code  of  Fig.  6.41. 

if  x  <  100  g o to  L2 
i f F a l se  x  >  200  g o to  L2 
!=  y  g o to  Li 
i f F a l se  x 
x  =  0 

L2: 
Li: 

Figure  6.41:  If-statement  translated  using  the  fall-through  technique 

As  in  Example 6.22,  t he  rules  for  P  ->•  S  create  label  Li.  T he  difference  from 
Example  6.22  is  t h at  t he  inherited  a t t r i b u te  B.true  is  fall  when  the  semantic 
rules  for  B  -)•  Bi  I I  B2  are  applied  (B.false  is  Li).  The  rules  in  Fig.  6.40 
create  a  new  label  L2  to  allow  a  j u mp  over  the  code  for  B2  if  i?i  evaluates  to 
true.  Thus,  Bi.true  is  L2  and  Bi.false  is  /a//,  since  £?2  must  be  evaluated  if  Bi 
is  false. 

The  production  B  —>•  E±  rel  _E2  t h at  generates  x  <  100  is  therefore  reached 
with  B.true  =  L2  and  B.false  =  /a//.  W i th  these  inherited  labels,  t he  rules  in 
Fig.  6.39  therefore  generate  a  single  instruction  if  x  <  100  g o to  L2. 

• 

408 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

6.6.6  Boolean  Values  and  Jumping  Code 

The  focus  in  this  section  has  been  on  t he  use  of  boolean  expressions  to  alter 
t he  flow  of  control  in  statements.  A  boolean  expression  m ay  also  be  evaluated 
for  its  value,  as  in  assignment  statements  such  as  x  =  t r u e;  or  x  =  a < b ;. 

A  clean  way  of  handling  both  roles  of  boolean  expressions  is  to  first  build  a 

syntax  tree  for  expressions,  using  either  of  the  following  approaches: 

1.  Use  two  passes.  Construct  a  complete  syntax  tree  for  the  input,  and  then 
walk  t he  tree  in  depth-first  order,  computing  the  translations  specified  by 
the  semantic  rules. 

2.  Use  one  pass  for  statements,  but  two  passes  for  expressions.  W i th  this 
approach,  we  would  translate  E  in  w h i le  (E)  Si  before  Si  is  examined. 
The  translation  of  E,  however,  would  be  done  by  building  its  syntax  tree 
and  then  walking  the  tree. 

T he  following  g r a m m ar  has  a  single  nonterminal  E  for  expressions: 

S->id  = 

E; \ i f( E ) S\ 

w h i le 

(E)S 

| 

S  S 

E 

-> 

E\\E 

|  E&&E 

\EYe\E\E  +  E\ 

{E)\id 

\ 

t r ue 

| 

false 

Nonterminal  E  governs  the  flow  of  control  in  S  -»  w h i le  (E)  Si.  T he  same 
nonterminal  E  denotes  a  value  in  5 

id  =  E;  and  E  —>•  E  +  E. 

We  can  handle  these  two  roles  of  expressions  by  using  separate  code-genera 
tion  functions.  Suppose  t h at  a t t r i b u te  E.n  denotes  t he  syntax-tree  node  for  an 
expression  E  and  t h at  nodes  are  objects.  Let  m e t h od  jump  generate  jumping 
code  at  an  expression  node,  and  let  method  rvalue  generate  code  to  compute 
the  value  of  the  node  into  a  temporary. 

When  E  appears  in  S  ->•  w h i le  (E)  Si,  method  jump  is  called  at  node 
E.n.  T he  implementation  of jump  is  based  on  the  rules  for  boolean  expressions 
in  Fig.  6.37.  Specifically,  jumping  code  is  generated  by  calling  E.n.jump(t,  /), 
where  t  is  a  new  label  for  the  first  instruction  of  Si.code  and  /  is  the  label 
S.next. 

When  E  appears  in  S  —v  id  =  E;,  method  rvalue  is  called  at  node  E.n.  If  E 
has  the  form  Ei+E2,  the  method  call  E.n.rvalueQ  generates  code  as  discussed 
in  Section  6.4.  If  E  has  t he  form  E\  hhE2,  we  first  generate  jumping  code  for 
E  and  then  assign  t r ue  or  false  to  a  new  t e m p o r a ry  t  at  the  true  and  false  exits, 
respectively,  from  t he  jumping  code. 

For  example,  the  assignment  x  =  a < b & & c <d  can  be  implemented  by  t he 

code  in  Fig.  6.42. 

6.6.7  Exercises  for  Section  6.6 

E x e r c i se  6 . 6 . 1:  Add  rules  to  t he  syntax-directed  definition  of  Fig.  6.36  for 
the  following  control-flow  constructs: 

a)  A  repeat-statment  r e p e at  S  w h i le  B. 

6.6. 

CONTROL  FLOW 

409 

t r ue 

i f F a l se  a  <  b  g o to  Li 
i f F a l se  c  >  d  g o to  Li 
t  = 
g o to  L2 
t  =  f a l se 
x  =  t 

L i: 
L2: 

Figure  6.42:  Translating  a  boolean  assignment  by  computing  the  value  of  a 
temporary 

!  b)  A  for-loop  for  (Si;  B;  S2)  S3. 

E x e r c i se  6 . 6 . 2:  Modern  machines  try  to  execute  many  instructions  at  the 
same  time,  including  branching  instructions.  Thus,  there  is  a  severe  cost  if  the 
machine  speculatively  follows  one  branch,  when  control  actually  goes  another 
way  (all  t he  speculative  work  is  thrown  away).  It  is  therefore  desirable  to  min 
imize  the  number  of  branches.  Notice  t h at  the  implementation  of  a  while-loop 
in  Fig.  6.35(c)  has  two  branches  per  interation:  one  to  enter  the  body  from 
the  condition  B  and  the  other  to  j u mp  back  to  the  code  for  B.  As  a  result, 
it  is  usually  preferable  to  implement  w h i le  (B)  S  as  if  it  were  if  (B)  {  re 
p e at  S  u n t il  \(B)  }.  Show  what  the  code  layout  looks  like  for  this  translation, 
and  revise  the  rule  for  while-loops  in  Fig.  6.36. 

!  E x e r c i se  6 . 6 . 3:  Suppose  t h at  there  were  an  "exclusive-or"  operator  (true  if 
and  only  if  exactly  one  of  its  two  arguments  is  true)  in  C.  Write  the  rule  for 
this  operator  in  t he  style  of  Fig.  6.37. 

E x e r c i se  6 . 6. 4:  Translate  t he  following  expressions  using  the  goto-avoiding 
translation  scheme  of  Section  6.6.5: 

a)  if 

(a==b  kk  c==d 

|I  e==f)  x  ==  1; 

b)  if 

(a==b 

II  c==d 

||  e==f)  x  ==  1; 

c)  if  (a==b  &&  c==d  kk  e==f)  x  ==  1; 

E x e r c i se  6 . 6 . 5:  Give  a  translation  scheme  based  on  t he  syntax-directed  defi 
nition  in  Figs.  6.36  and  6.37. 

E x e r c i se  6 . 6 . 6:  A d a pt  the  semantic  rules  in  Figs.  6.36  and  6.37  to  allow 
control  to  fall  through,  using  rules  like  the  ones  in  Figs.  6.39  and  6.40. 

!  E x e r c i se  6 . 6 . 7:  T he  semantic  rules  for  statements  in  Exercise  6.6.6  generate 
unnecessary  labels.  Modify  t he  rules  for  statements  in  Fig.  6.36  to  create  labels 
as  needed,  using  a  special  label  deferred  to  mean  t h at  a  label  has  not  yet  been 
created.  Your  rules  must  generate  code  similar  to  t h at  in  Example  6.21. 

410 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

\  E x e r c i se  6 . 6 . 8:  Section  6.6.5  talks  about  using  fall-through  code  to  minimize 
the  number  of j u m ps  in  the  generated  intermediate  code.  However,  it  does  not 
take  advantage  of the  option  to  replace  a  condition  by  its  complement,  e.g.,  re 
place  if  a <b  g o to  Li;  g o to  L2  by  if  b  >=  a  g o to  L2;  g o to  L\.  Develop 
a  SDD  t h at  does  take  advantage  of  this  option  when  needed. 

6.7  Backpatching 

A  key  problem  when  generating  code  for  boolean  expressions  and  flow-of-control 
statements  is  t h at  of  matching  a j u mp  instruction  with  t he  target  of the  j u m p. 
For  example,  the  translation  of  the  boolean  expression  B  in  if  (B)  S  contains 
a  j u m p,  for  when  B  is  false,  to  the  instruction  following  the  code  for  S.  In  a 
one-pass  translation,  B  must  be  translated  before  S  is  examined.  W h at  then 
is  t he  target  of  t he  g o to  t h at  j u m ps  over  t he  code  for  S? 
In  Section  6.6  we 
addressed  this  problem  by  passing  labels  as  inherited  attributes  to  where  the 
relevant  j u mp  instructions  were  generated.  But  a  separate  pass  is  then  needed 
to  bind  labels  to  addresses. 

This  section  takes  a  complementary  approach,  called  backpatching,  in  which 
lists  of  j u m ps  are  passed  as  synthesized  attributes.  Specifically,  when  a  j u mp 
is  generated,  t he  target  of  t he  j u mp  is  temporarily  left  unspecified.  Each  such 
j u mp  is  put  on  a  list  of j u m ps  whose  labels  are  to  be  filled  in  when  the  proper 
label  can  be  determined.  All  of  t he  j u m ps  on  a  list  have  t he  same  target  label. 

6.7.1  One-Pass  Code  Generation  Using  Backpatching 

Backpatching  can  be  used  to  generate  code  for  boolean  expressions  and  flow-
of-control  statements  in  one  pass.  The  translations  we  generate  will  be  of  the 
same  form  as  those  in  Section  6.6,  except  for  how  we  manage  labels. 

In  this  section,  synthesized  attributes  truelist  and  falselist  of  nonterminal  B 

are  used  to  manage  labels  in  jumping  code  for  boolean  expressions.  In  particu 
lar,  B. truelist  will  be  a  list  of j u mp  or  conditional  j u mp  instructions  into  which 
we  must  insert  t he  label  to  which  control  goes  if  B  is  true.  B.falselist  likewise  is 
the  list  of  instructions  t h at  eventually  get  the  label  to  which  control  goes  when 
B  is  false.  As  code  is  generated  for  B,  j u m ps  to  t he  true  and  false  exits  are  left 
incomplete,  with  the  label  field  unfilled.  These  incomplete  jumps  are  placed 
on  lists  pointed  to  by  B.truelist  and  B.falselist,  as  appropriate.  Similarly,  a 
statement  S  has  a  synthesized  a t t r i b u te  S.nextlist,  denoting  a  list  of  j u m ps  to 
the  instruction  immediately  following  the  code  for  S. 

For  specificity,  we  generate  instructions  into  an  instruction  array,  and  labels 
will  be  indices  into  this  array.  To  manipulate  lists  of  jumps,  we  use  three 
functions: 

1.  makelist(i)  creates  a  new  list  containing  only  i,  an  index  into  the  array  of 

instructions;  makelist  returns  a  pointer  to  the  newly  created  list. 

6.7.  BACKPATCHING 

411 

2.  merge(pi,p2)  concatenates  the  lists  pointed  to  by  p\  and  p2,  and  returns 

a  pointer  to  t he  concatenated  list. 

3.  backpatch(p,i)  inserts  i  as  t he  target  label  for  each  of  the  instructions  on 

t he  list  pointed  to  by  p. 

6.7.2  Backpatching  for  Boolean  Expressions 

We  now  construct  a  translation  scheme  suitable  for  generating  code  for  boolean 
expressions  during  b o t t o m - up  parsing.  A  marker  nonterminal  M  in  t he  gram 
m ar  causes  a  semantic  action  to  pick  up,  at  appropriate  times,  the  index  of the 
next  instruction  to  be  generated.  The  g r a m m ar  is  as  follows: 

B  -+  Bx 
M  ->•  e 

I  |  M  B2  |  Bi  kk  M  B2  |  !  Bx 

|  (Bx)  |  Ei  rel  E2  | true | false 

The  translation  scheme  is  in  Fig.  6.43. 

B  ->•  Bi 

|  I  M  B2 

{  backpatch(Bi.falselist,  M.instr); 

B.truelist  —  merge{B\.  truelist,  B2.truelist); 
B.falselist  =  B2.falselist; 

} 

B  ->  Bi  kk  M  B2 

backpatch(Bi.truelist,  M.instr); 

{ 
B.truelist  = 
B.falselist  —  merge(Bi.falselist,  B2.falselist); 

B2.truelist; 

} 

B  —>•  !  Bi 

{ 

B.truelist  =  B\.falselist; 

B.falselist  =  Bi.truelist; 

} 

4) 

B 

(  Bi  ) 

{ 

B.truelist  =  Bx.truelist; 

B.falselist  = 

Bi.falselist;  } 

5) 

B  ->  Ei rel  E2 

{ 

B.truelist  =  makelist(nextinstr); 
B.falselist  =  makelist(nextinstr  +  1); 
emit('±f'  Ei.addr rel.op  E2.addr  ' g o to 
e7m£('goto  _');  } 

_'); 

B —> true 

{ 

B.truelist  =  makelist(nextinstr); 

emit('goto  _');  } 

B -> false 

{ 

B.falselist  —  makelist(nextinstr); 

emit('goto 

_');  } 

M  —>  e 

{  M.instr  —  nextinstr,  } 

Fi  gure  6.43:  Translation  scheme  for  boolean  expressions 

Consider  semantic  action  (1)  for  the  production  B  ->  Bi  I  I  M B2.  If  Bx  is 
true,  then  B  is  also  true,  so  the  j u m ps  on  Bi.truelist  become  part  of  B.truelist. 
is  false,  however,  we  must  next  test  B2,  so  the  target  for  t he  j u m ps 
If  Bi 

412 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

B>i .falselist  must  be  the  beginning  of  t he  code  generated  for  B2 •  This  target  is 
obtained  using  t he  marker  nonterminal  M.  T h at  nonterminal  produces,  as  a 
synthesized  a t t r i b u te  M.instr,  the  index  of  the  next  instruction,  just  before  B2 
code  starts  being  generated. 

To  obtain  t h at  instruction  index,  we  associate  with  t he  production  M  -»  e 

the  semantic  action 

{  M.  instr  =  nextinstr,  } 

The  variable  nextinstr  holds  the  index  of  the  next  instruction  to  follow.  This 
value  will  be  backpatched  onto  the  Bi.falselist  (i.e.,  each  instruction  on  the 
list  B\.falselist  will  receive  M.instr  as  its  target  label)  when  we  have  seen  t he 
remainder  of  the  production  B  ->•  Bi I I  M B2. 

Semantic  action  (2)  for  B  -»  B\  kk  M  B2  is  similar  to  (1).  Action  (3)  for 

B  ->• 

IB  swaps  the  true  and  false  lists.  Action  (4)  ignores  parentheses. 

For  simplicity,  semantic  action  (5)  generates  two  instructions,  a  conditional 

goto  and  an  unconditional  one.  Neither  has  its  target  filled  in.  These  instruc 
tions  are  put  on  new  lists,  pointed  to  by  B.truelist  and  B.falselist,  respectively. 

B.t  =  {100,104} 
B.f  =  {103,105} 

B.t  =  {100} 
B.f  =  {101} 

<  100 

B.t  =  {104} 
B.f  =  {103,105} 

M.i  =  104 

B.t  =  {102} 
B.f  =  {103} 
/  I  \ 

x 

>  200 

B.t  =  {104} 
B.f  =  {105} 

x 

!=  y 

Figure  6.44:  Annotated  parse  tree  for  x  <  100  I I  x  >  200  kk  x  !  =  y 

E x a m p le  6 . 2 4:  Consider  again  t he  expression 

x  <  100  I I  x  >  200  kk  x  !  =  y 

An  annotated  parse  tree  is  shown  in  Fig.  6.44;  for  readability,  attributes  tru-
elist,  falselist,  and  instr  are  represented  by  their  initial  letters.  The  actions  are 
performed  during  a  depth-first  traversal  of  the  tree.  Since  all  actions  appear  at 
t he  ends  of  right  sides,  they  can  be  performed  in  conjunction  with  reductions 
during  a  bottom-up  parse. 
In  response  to  the  reduction  of  x  <  100  to  B  by 
production  (5),  t he  two  instructions 

6.7. 

BACKPATCHING 

413 

100: 
101: 

if  x  <  100  g o to  _ 
g o to  _ 

are  generated.  (We  arbitrarily  start  instruction  numbers  at  100.)  T he  marker 
nonterminal  M  in  the  production 

B^B1\\MB2 

records  the  value  of  nextinstr,  which  at  this  time  is  102.  T he  reduction  of 
x  >  200  to  B  by  production  (5)  generates  the  instructions 

102: 
103: 

if  x  >  200  g o to  _ 
g o to  _ 

T he  subexpression  x  >  200  corresponds  to  B\  in  the  production 

B 

Bi  kk  M  B2 

T he  marker  nonterminal  M  records  the  current  value  of  nextinstr,  which  is  now 
104.  Reducing  x  !  =  y  into  B  by  production  (5)  generates 

104: 
105: 

if  x  !=  y  g o to  _ 
g o to  _ 

We  now  reduce  by  B  —)•  B\  kk  M  B2.  The  corresponding  semantic  ac 
tion  calls  backpatch(Bi.truelist,M.instr) 
to  bind  the  true  exit  of  B\ 
to  the  first 
this  call  to 
instruction  of  B2.  Since  B\.truelist  is  {102}  and  M.instr  is  104, 
backpatch  fills  in  104  in  instruction  102.  T he  six  instructions  generated  so  far 
are  thus  as  shown  in  Fig.  6.45(a). 

The  semantic  action  associated  with  the  final  reduction  by  B  —>  By  \  \MB2 

calls  backpatch({101},102)  which  leaves  the  instructions  as  in  Fig.  6.45(b). 

T he  entire  expression  is  true  if  and  only  if  the  gotos  of  instructions  100 
or  104  are  reached,  and  is  false  if  and  only  if  the  gotos  of  instructions  103  or 
105  are  reached.  These  instructions  will  have  their  targets  filled  in  later  in 
the  compilation,  when  it  is  seen  what  must  be  done  depending  on  the  t r u th  or 
falsehood  of  the  expression. 

• 

6.7.3 

Flow-of-Control  Statements 

We  now  use  backpatching  to  translate  flow-of-control  statements  in  one  pass. 
Consider  statements  generated  by  the  following  grammar: 

5 

-4 

i f ( S)5 

| 

if (B)S  e l se  S 

|  w h i le  (B)  S 

|  {  L  }  \  A  ; 

L  ->>  LS 

|  S 

Here  S  denotes  a  statement,  L  a  statement  list,  A  an  assignment-statement, 
and  B  a  boolean  expression.  Note  t h at  there  must  be  other  productions,  such  as 

414 

CHAPTER  6. 

INTERMEDIATE-CODE  GENERATION 

100 
101 
102 
103 
104 
105 

if  x  <  100  goto  _ 
goto  _ 
if  x  >  200  goto  104 
goto  _ 
if  x  != y goto _ 
goto 

(a)  After  backpatching  104  into  instruction  102. 

100 
101 
102 
103 
104 
105 

if  x  <  100  goto  _ 
goto  102 
if  y  >  200  goto  104 
goto _ 

!=  y  goto  _ 

if  x 
goto _ 

(b)  After  backpatching  102  into  instruction  101. 

Figure  6.45:  Steps  in  t he  backpatch  process 

those  for  assignment-statements.  The  productions  given,  however,  are  sufficient 
to  illustrate  the  techniques  used  to  translate  flow-of-control  statements. 

T he  code  layout  for  if-,  if-else-,  and  while-statements  is  t he  same  as  in 
Section  6.6.  We  make  the  tacit  assumption  t h at  the  code  sequence  in  the 
instruction  array  reflects  the  natural  flow  of  control  from  one  instruction  to  t he 
next. 
If  not,  then  explicit  jumps  must  be  inserted  to  implement  t he  natural 
sequential  flow  of  control. 

The  translation  scheme  in  Fig.  6.46  maintains  lists  of j u m ps  t h at  are  filled  in 
when  their  targets  are  found.  As  in  Fig.  6.43,  boolean  expressions  generated  by 
nonterminal  B  have  two  lists  of j u m p s,  B.truelist  and  B.falselist,  corresponding 
to  the  true  and  false  exits  from  the  code  for  B,  respectively.  Statements  gener 
ated  by  nonterminals  5  and  L  have  a  list  of  unfilled  jumps,  given  by  a t t r i b u te 
nextlist,  t h at  must  eventually  be  completed  by  backpatching.  S.nextlist  is  a  list 
of  all  conditional  and  unconditional  j u m ps  to  the  instruction  following  t he  code 
for  statement  S  in  execution  order.  L.nextlist  is  defined  similarly. 

Consider t he  semantic  action  (3)  in  Fig.  6.46.  T he  code layout for production 
5  -»  w h i le  (B)  S\  is  as  in  Fig.  6.35(c).  T he  two  occurrences  of  the  marker 
nonterminal  M  in  t he  production 

S 

->  w h i le  Mi  (  B  )  M2  Si 

record  t he  instruction  numbers  of  the  beginning  of  the  code  for  B  and  t he 
beginning  of the  code  for  Si.  The  corresponding  labels  in  Fig.  6.35(c)  are  begin 
and  B.true,  respectively. 

6.7. 

BACKPATCHING 

415 

1)  S 

-)• 

if  (B)  MSi 

{  backpatch{B.truelist,  M.instr); 
merge(B.falselist, 
S.nextlist  = 

S\.nextlist); 

} 

2)  5 -> 

if(B)M1S1N 
{ 

e\seM2S2 

backpatch(B  .truelist,  M\.instr); 
backpatch(B  .falselist,  M2.  instr); 
temp 
S.nextlist  =  merge(temp, 

= 

merge(S\.nextlist,  N.nextlist); 

S2.nextlist); 

} 

3)  S 

-> 

w h i le  M1(B)M2S1 
{ 

backpatch(S\.nextlist,  My.instr); 

backpatch(B.  truelist,  M2.  instr); 
S.nextlist  =  B. 
emit('goto'  My.instr); 

falselist; 
} 

4)  S  ->  {  L  } 

{  S.nextlist  =  L.nextlist;  } 

5)  5 

A  ; 

{  S.nextlist  —  null;  } 

6)  M  ->  e 

{  M.instr  — 

nextinstr,  } 

7)  iV 

e 

{  N.nextlist  = 

makelist(nextinstr); 

emit('goto  _');  } 

8)  L  -+  Ly  M  S 

{ 

backpatch(Li.nextlist, 

M.instr); 

L. nextlist  —  S. nextlist;  } 

9)  L  ->  5 

{  L. nextlist  —  S. nextlist;  } 

Figure  6.46:  Translation  of  statements 

Again,  the  only  production  for  Af  is  M  ->  e.  Action  (6)  in  Fig.  6.46  sets 
a t t r i b u te  M.instr  to  the  number  of  the  next  instruction.  After  the  body  Si 
of  the  while-statement  is  executed,  control  flows  to  the  beginning.  Therefore, 
when  we  reduce  w h i le  Mi  (B  )  M2  Si  to  S,  we  backpatch  Sy.nextlist  to  make 
all  targets  on  t h at  list  be  My.instr.  An  explicit  j u mp  to  the  beginning  of  t he 
code  for  B  is  appended  after  the  code  for  Si  because  control  may  also  "fall  out 
t he  bottom."  B. truelist  is  backpatched  to  go  to  the  beginning  of  Si  by  making 
j u m ps  on  B.truelist  go 

to  M2.instr. 

A  more  compelling  argument  for  using  S.nextlist  and  L.nextlist  comes  when 

If  control 
code  is  generated  for  the  conditional  statement  if (B)  Si  e l se  S2. 
"falls  out  the  b o t t o m"  of  Si,  as  when  Si  is  an  assignment,  we  must  include 
at  t he  end  of  t he  code  for  Si  a  j u mp  over  the  code  for  S2-  We  use  another 
marker  nonterminal  to  generate  this  j u mp  after  Si.  Let  nonterminal  N  be  this 

416 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

marker  with  production  N  ->  e.  N  has  a t t r i b u te  N.nextlist,  which  will  be  a  list 
consisting  of  the  instruction  number  of  t he  j u mp  g o to _ 
t h at  is  generated  by 
the  semantic  action  (7)  for  N. 

Semantic  action  (2)  in  Fig.  6.46  deals  with  if-else-statements  with  the  syntax 

S 

-> 

if  (  B  )  Mi  Si  N  e l se  M2  S2 

We  backpatch  the  j u m ps  when  B  is  true  to  the  instruction  Mi.instr;  t he  latter 
is  the  beginning  of  the  code  for  Si.  Similarly,  we  backpatch  j u m ps  when  B  is 
false  to  go  to  the  beginning  of  the  code  for  S2.  T he  list  S.nextlist  includes  all 
jumps  out  of  Si  and  S2,  as  well  as  the  j u mp  generated  by  N.  (Variable  temp  is 
a  temporary  t h at  is  used  only  for  merging  lists.) 

Semantic  actions  (8)  and  (9)  handle  sequences  of  statements.  In 

L-^LxMS 

the  instruction  following  the  code  for  L±  in  order  of  execution  is  t he  beginning 
of  S.  Thus  the  L±.nextlist  list  is  backpatched  to  t he  beginning  of  the  code  for 
S,  which  is  given  by  M.instr.  In  L  —>  S,  L.nextlist  is  the  same  as  S.nextlist. 

Note  t h at  no  new  instructions  are  generated  anywhere  in  these  semantic 
rules,  except  for  rules  (3)  and  (7).  All  other  code  is  generated  by  t he  semantic 
actions  associated  with  assignment-statements  and  expressions.  T he  flow  of 
control  causes  the  proper  backpatching  so  t h at  the  assignments  and  boolean 
expression  evaluations  will  connect  properly. 

6.7.4  Break-,  Continue-,  and  Goto-Statements 

The  most  elementary  programming  language  construct  for  changing  t he  flow  of 
control  in  a  program  is  the  goto-statement.  In  C,  a  statement  like  g o to  L  sends 
control  to  t he  statement  labeled  L  —  there  must  be  precisely  one  statement  with 
label  L  in  this  scope.  Goto-statements  can  be  implemented  by  maintaining  a 
list  of  unfilled  jumps  for  each  label  and  then  backpatching  the  target  when  it 
is  known. 

Java  does  away  with  goto-statements.  However,  Java  does  permit  disci 
plined  j u m ps  called  break-statements,  which  send  control  out  of  an  enclosing 
construct,  and  continue-statements,  which  trigger  t he  next  iteration  of  an  en 
closing  loop.  The  following  excerpt  from  a  lexical  analyzer  illustrates  simple 
break-  and  continue-statements: 

1) 
2) 
3) 
4) 

f or  ( 

; 

;  r e a d c hO  )  { 
' 

' 
i f(  peek  == 

i f(  p e ek  == 
e l se 
e l se  b r e a k; 

II  p e ek  == 
) 
' \ n' 

' \ t' 

)  c o n t i n u e; 

l i ne  =  l i ne  +  1; 

5) 

> 

Control  jumps  from  t he  break-statement  On  line  4  to  t he  next  statement  after 
the  enclosing  for  loop.  Control  j u m ps  from  t he  continue-statement  on  line  2  to 
code  to  evaluate  readchQ  and  then  to  the  if-statement  on  line  2. 

6.7. 

BACKPATCHING 

417 

If  5  is  the  enclosing  construct,  then  a  break-statement  is  a  j u mp  to  the  first 
instruction  after  t he  code  for  S.  We  can  generate  code  for  t he  break  by  (1) 
keeping  track  of  the  enclosing  statement  S,  (2)  generating  an  unfilled  j u mp  for 
t he  break-statement,  and  (3)  putting  this  unfilled  j u mp  on  S.nextlist,  where 
nextlist  is  as  discussed  in  Section  6.7.3. 

In  a  two-pass  front  end  t h at  builds  syntax  trees,  S.nextlist  can  be  imple 
mented  as  a  field  in  the  node  for  S.  We  can  keep  track  of  S  by  using  t he 
symbol  table  to  m ap  a  special  identifier  b r e ak  to  the  node  for  t he  enclosing 
statement  S.  This  approach  will  also  handle  labeled  break-statements  in  Java, 
since  the  symbol  table  can  be  used  to  m ap  t he  label  to  the  syntax-tree  node  for 
t he  enclosing  construct. 

Alternatively,  instead  of  using  the  symbol  table  to  access  t he  node  for  5, 
we  can  put  a  pointer  to  S.nextlist  in  the  symbol  table.  Now,  when  a  break-
statement  is  reached,  we  generate  an  unfilled  j u m p,  look  up  nextlist  through 
t he  symbol  table,  and  add  t he  j u mp  to  the  list,  where  it  will  be  backpatched  as 
discussed  in  Section  6.7.3. 

Continue-statements  can  be  handled  in  a  manner  analogous  to  the  break-
statement.  The  main  difference  between  the  two  is  t h at  t he  target  of  t he  gen 
erated  j u mp  is  different. 

6.7.5  Exercises  for  Section  6.7 

E x e r c i se  6 . 7 . 1:  Using  the  translation  of  Fig.  6.43,  translate  each  of  the  fol 
lowing  expressions.  Show  the  true  and  false  lists  for  each  subexpression.  You 
may  assume  the  address  of  the  first  instruction  generated  is  100. 

a)  a==b  kk 

(c==d 

|I  e==f) 

b)  (a==b  I  I  c==d) 

||  e==f 

c)  (a==b  &&  c==d)  kk  e==f 

E x e r c i se  6 . 7 . 2:  In  Fig.  6.47(a)  is  the  outline  of  a  program,  and  Fig.  6.47(b) 
sketches  the  structure  of the  generated  three-address  code,  using  the  backpatch 
ing  translation  of  Fig.  6.46.  Here,  ix  through  i8  are  the  labels  of  the  generated 
instructions  t h at  begin  each  of  the  "Code"  sections.  When  we  implement  this 
translation,  we  maintain,  for  each  boolean  expression  E,  two  lists  of  places  in 
the  code  for  E,  which  we  denote  by  E.true  and  E.false.  T he  places  on  list 
E.true  are  those  places  where  we  eventually  put  the  label  of  the  statement  to 
which  control  must  flow  whenever  E  is  true;  E.false  similarly  lists  the  places 
where  we  put  t he  label  t h at  control  flows  to  when  E  is  found  to  be  false.  Also, 
we  maintain  for  each  statement  S,  a  list  of  places  where  we  must  put  t he  label 
to  which  control  flows  when  S  is  finished.  Give  the  value  (one  of  h  through  i8) 
t h at  eventually  replaces  each  place  on  each  of  the  following  lists: 

(a)  Ez.false 

(b)  S2.next 

(c)  EA.false 

(d)  Si.next 

(e)  E2.true 

418 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

w h i le  (E^  { 
(E2) 
if 

w h i le  (E3) 

Si; 

e l se  { 

if  ( E4) 

s3 

} 

} 

(a) 

«'i:  Code  for  E\ 
12- Code  for  E2 
«3-'  Code  for  E3 
z4:  Code  for  Si 
Code  for  E4 
«6 = Code  for  S2 
z7:  Code  for  £3 

(b) 

Figure  6.47:  Control-flow  structure  of  program  for  Exercise  6.7.2 

E x e r c i se  6 . 7 . 3:  When  performing t he  translation  of Fig.  6.47 using  the  scheme 
of  Fig.  6.46,  we  create  lists  S.next  for  each  statement,  starting  with  the  assign 
ment-statements  S i,  S2,  and  S 3,  and  proceeding  to  progressively  larger  if-
statements,  if-else-statements,  while-statements,  and  statement  blocks.  There 
are  five  constructed  statements  of  this  type  in  Fig.  6.47: 

S4:  w h i le  (E3)  S i. 

S5:  if  ( J S 4)  S2-

S&:  T he  block  consisting  of S5  and  S 3. 

S 7: T he  statement  if  S4  e l se  Se-

S$:  The  entire  program. 

For  each  of  these  constructed  statements,  there  is  a  rule  t h at  allows  us 
to  construct  Si.next  in  terms  of  other  Sj.next  lists,  and  t he  lists  E^.true  and 
Ek-false  for  the  expressions  in  the  program.  Give  the  rules  for 

(a)  S^-next 

(b)  Si.next 

(c)  Si.next 

(d)  Si.next 

(e)  Si.next 

6.8  Switch-Statements 

T he  "switch"  or  "case"  statement  is  available  in  a  variety  of  languages.  Our 
switch-statement  syntax  is  shown  in  Fig.  6.48.  There  is  a  selector  expression 
E,  which  is  to  be  evaluated,  followed  by  n  constant  values  Vi,  V2,  •  •  •  ,Vn  t h at 
t he  expression  might  take,  perhaps  including  a  default  "value,"  which  always 
matches  the  expression  if  no  other  value  does. 

6.8. 

SWITCH-STATEMENTS 

419 

s w i t ch  (  E  )  { 

c a se  V\.  Si 
c a se W- S2 

c a se  Vn_ i:  »Sn-i 
default:  5n 

} 

Figure  6.48:  Switch-statement  syntax 

6.8.1  Translation  of  Switch-Statements 
T he  intended  translation  of  a  switch  is  code  to: 

1.  Evaluate  the  expression  E. 

2.  Find  t he  value  V}  in  the  list  of  cases  t h at  is  the  same  as  t he  value  of  t he 

expression.  Recall  t h at  t he  default  value  matches  the  expression  if  none 
of  the  values  explicitly  mentioned  in  cases  does. 

3.  Execute  the  statement  Sj  associated  with  the  value  found. 

Step  (2)  is  an  n-way  branch,  which  can  be  implemented  in  one  of  several 
ways.  If  the  number  of  cases  is  small,  say  10  at  most,  then  it  is  reasonable  to 
use  a  sequence  of  conditional  jumps,  each  of which  tests  for  an  individual  value 
and  transfers  to  t he  code  for  the  corresponding  statement. 

A  compact  way  to  implement  this  sequence  of  conditional  jumps  is  to  create 
a  table  of pairs,  each  pair  consisting  of  a  value  and  a  label  for  t he  corresponding 
statement's  code.  The  value  of the  expression  itself,  paired  with  t he  label  for  t he 
default  statement  is  placed  at  t he  end  of  t he  table  at  run  time.  A  simple  loop 
generated  by  the  compiler  compares  t he  value  of t he  expression  with  each  value 
in  t he  table,  being  assured  t h at  if  no  other  match  is  found,  t he  last  (default) 
entry  is  sure  to  match. 

If  the  number  of  values  exceeds  10  or  so,  it  is  more  efficient  to  construct  a 
hash  table  for  t he  values,  with  the  labels  of  the  various  statements  as  entries. 
If  no  entry  for  the  value  possessed  by  the  switch  expression  is  found,  a  j u mp  to 
t he  default  statement  is  generated. 

There  is  a  common  special  case  t h at  can  be  implemented  even  more  effi 
ciently  t h an  by  an  n-way  branch. 
If  t he  values  all  lie  in  some  small  range, 
say  min  to  max,  and  the  number  of  different  values  is  a  reasonable  fraction  of 
max  —  min,  then  we  can  construct  an  array  of  max  —  min  "buckets,"  where 
bucket  j  —  min  contains  the  label  of  t he  statement  with  value  j;  any  bucket 
t h at  would  otherwise  remain  unfilled  contains  the  default  label. 

To  perform  t he  switch,  evaluate  the  expression  to  obtain  t he  value  j;  check 
t h at  it  is  in  the  range  min  to  max  and  transfer  indirectly  to  the  table  entry  at 
offset  j  —  min.  For  example,  if  the  expression  is  of  type  character,  a  table  of, 

420 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

say,  128  entries  (depending  on  the  character  set)  may  be  created  and  transferred 
through  with  no  range  testing. 

6.8.2 

Syntax-Directed  Translation  of  Switch-Statements 

T he  intermediate  code  in  Fig.  6.49  is  a  convenient  translation  of  t he  switch-
statement  in  Fig.  6.48.  The  tests  all  appear  at  the  end  so  t h at  a  simple  code 
generator  can  recognize  the  multiway  branch  and  generate  efficient  code  for  it, 
using  the  most  appropriate  implementation  suggested  at  t he  beginning  of  this 
section. 

Li: 

L2: 

code  to  evaluate  E  into t 
goto  test 
code  for  S\ 
goto  next 
code  for  52 
goto  next 

Ln: 

Ln_ i: 

code  for  5n_i 
goto  next 
code  for  Sn 
goto  next 
test:  if  t  =  Vi  goto  Li 
if  t  =  V2  goto  L2 

if  t  =  Vn-i  goto  Ln_i 
goto  Ln 

next: 

Figure  6.49:  Translation  of  a  switch-statement 

T he  more  straightforward  sequence  shown  in  Fig.  6.50  would  require  the 
compiler  to  do  extensive  analysis  to  find  t he  most  efficient  implementation.  Note 
t h at  it  is  inconvenient  in  a  one-pass  compiler  to  place  the  branching  statements 
at  the  beginning,  because  t he  compiler  could  not  t h en  emit  code  for  each  of t he 
statements  Si  as  it  saw  them. 

To  translate  into  the  form  of Fig.  6.49,  when  we  see t he  keyword switch,  we 
generate  two  new  labels test  and next,  and  a  new  temporary  t.  Then,  as  we 
parse  the  expression  E,  we  generate  code  to  evaluate  E  into  t.  After  processing 
E,  we  generate  the  j u mp goto test. 

Then,  as  we  see each case  keyword,  we  create  a new  label  Li  and  enter it  into 
t he  symbol  table.  We  place  in  a  queue,  used  only  to  store  cases,  a  value-label 
pair  consisting  of  the  value  Vi  of  t he  case  constant  and  Li  (or  a  pointer  to  t he 
symbol-table  entry  for  Li).  We  process  each  statement case  Vi:  Si  by  emitting 
the  label  Li  attached  to  t he  code  for  Si,  followed  by  t he  j u mp goto next. 

6.8. 

SWITCH-STATEMENTS 

421 

t 

code  to  evaluate  E  into  t 
if 
!=  Vi  g o to  Li 
code  for  Si 
g o to  n e xt 
if  t 
code  for  S2 
g o to  n e xt 

!=  V2  g o to  L2 

Li: 

L2: 

Ln_2: 

if  t  !=  K_i  g o to  Ln_i 

code  for  Sn_i 
g o to  n e xt 
code  for  Sn 

Ln_ i: 
n e x t: 

Figure  6.50:  Another  translation  of  a  switch  statement 

W h en  t he  end  of  t he  switch  is  found,  we  are  ready  to  generate  the  code  for 
the  n-way  branch.  Reading  the  queue  of  value-label  pairs,  we  can  generate  a 
sequence  of  three-address  statements  of  t he  form  shown  in  Fig.  6.51.  There,  t 
is  the  temporary  holding  t he  value  of  the  selector  expression  E,  and  hn  is  the 
label  for  t he  default  statement. 

c a se  t  Vi  Li 
c a se  t  V2  L2 

t  Vn-i  Ln_i 
c a se 
c a se 
t  t  Ln 
l a b el  n e xt 

Figure  6.51:  Case  three-address-code  instructions  used  to  translate  a  switch-
statement 

T he  c a se  t  Vi  hi  instruction  is  a  synonym  for  if  t  = Vi  g o to  hi  in  Fig.  6.49, 
but  t he  c a se  instruction  is  easier  for  the  final  code  generator  to  detect  as  a 
candidate  for  special  treatment.  At  t he  code-generation  phase,  these  sequences 
of  c a se  statements  can  be  translated  into  an  n-way  branch  of t he  most  efficient 
type,  depending  on  how  many  there  are  and  whether  t he  values  fall  into  a  small 
range. 

6.8.3  Exercises  for  Section  6.8 

!  E x e r c i se  6 . 8. 1:  In  order  to  translate  a  switch-statement  into  a  sequence  of 
c a s e - s t a t e m e n ts  as  in  Fig.  6.51,  t he  translator  needs  to  create  the  list  of  value-

422 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

label  pairs,  as  it  processes  the  source  code  for  t he  switch.  We  can  do  so,  using 
an  additional  translation  t h at  accumulates  just  the  pairs.  Sketch  a  syntax-
direction  definition  t h at  produces  the  list  of  pairs,  while  also  emitting  code  for 
t he  statements  Si  t h at  are  t he  actions  for  each  case. 

6.9 

Intermediate  Code  for  Procedures 

Procedures  and  their  implementation  will  be  discussed  at  length  in  Chapter  7, 
along  with  t he  run-time  management  of  storage  for  names.  We  use  t he  t e rm 
function  in  this  section  for  a  procedure  t h at  returns  a  value.  We  briefly  discuss 
function  declarations  and  three-address  code  for  function  calls.  In  three-address 
code,  a  function  call  is  unraveled  into  the  evaluation  of  parameters  in  prepa 
ration  for  a  call,  followed  by  the  call  itself.  For  simplicity,  we  assume  t h at 
parameters  are  passed  by  value;  parameter-passing  methods  are  discussed  in 
Section  1.6.6. 

E x a m p le  6 . 2 5:  Suppose  t h at  a  is  an  array  of integers,  and  t h at  f  is  a  function 
from  integers  to  integers.  Then,  the  assignment 

might  translate  into  the  following  three-address  code: 

n  =  f ( a [ i ] ); 

1) 
2) 
3) 
4) 
5) 

ti  =  i  *  4 
t2  =  a  [  ti  ] 
param 
t2 
t3  =  c a ll  f,  1 
n  =  t3 

into  temporary 
The  first  two  lines  compute  t he  value  of  the  expression  a [ i] 
t2,  as  discussed  in  Section  6.4.  Line  3  makes  t2  an  actual  parameter  for  the 
call  on  line  4  of  f  with  one  parameter.  Line  5  assigns  the  value  returned  by  t he 
function  call  to  t3.  Line  6  assigns  t he  returned  value  to  n. 

• 

The  productions  in  Fig.  6.52  allow  function  definitions  and  function  calls. 
(The  syntax  generates  unwanted  commas  after  the  last  parameter,  but  is  good 
enough  for  illustrating  translation.)  Nonterminals  D  and  T  generate  declara 
tions  and  types,  respectively,  as  in  Section  6.3.  A  function  definition  gener 
ated  by  D  consists  of  keyword  d e f i n e,  a  return  type,  t he  function  name,  for 
mal  parameters  in  parentheses  and  a  function  body  consisting  of  a  statement. 
Nonterminal  F  generates  zero  or  more  formal  parameters,  where  a  formal  pa 
rameter  consists  of  a  type  followed  by  an  identifier.  Nonterminals  S  and  E 
generate  statements  and  expressions,  respectively.  The  production  for  S  adds  a 
statement  t h at  returns  t he  value  of  an  expression.  T he  production  for  E  adds 
function  calls,  with  actual  parameters  generated  by  A.  An  actual  parameter  is 
an  expression. 

6.9. 

INTERMEDIATE  CODE  FOR  PROCEDURES 

423 

D 

F 

S 

E 

A 

-> 

define  T  id  (  F ) { 5 } 

e 

|  T  id  ,  F 

-> 

-» 

-> 

r e t u rn 

; 

id  (  A  ) 

e  !  E  ,  A 

Figure  6.52:  Adding  functions  to  t he  source  language 

Function  definitions  and  function  calls  can  be  translated  using  concepts  t h at 

have  already  been  introduced  in  this  chapter. 

•  Function  types.  The  type  of  a  function  must  encode  the  return  type  and 
the  types  of  the  formal  parameters.  Let  void  be  a  special  type  t h at  repre 
sents  no  parameter  or  no  return  type.  T he  type  of  a  function  pop()  t h at 
returns  an  integer  is  therefore  "function  from  void  to  integer."  Function 
types  can  be  represented  by  using  a  constructor  fun  applied  to  t he  r e t u rn 
type  and  an  ordered  list  of  types  for  the  parameters. 

•  Symbol  tables.  Let  s  be  t he  top  symbol  table  when  t he  function  definition 
is  reached.  T he  function  name  is  entered  into  s  for  use  in  the  rest  of  t he 
program.  T he  formal  parameters  of  a  function  can  be  handled  in  analogy 
with  field  names  in  a  record  (see  Fig.  6.18.  In  t he  production  for  D,  after 
seeing  define  and  the  function  name,  we  push  s  and  set  up  a  new  symbol 
table 

Env.push(top)] 

top  =  n ew  Env(top); 

Call  t he  new  symbol  table,  t.  Note  t h at  top  is  passed  as  a  parameter  in 
n ew  Env(top),  so  t he  new  symbol  table  t  can  be  linked  to  the  previous 
one,  s.  T he  new  table  t  is  used  to  translate  the  function  body.  We  revert 
to  t he  previous  symbol  table  s  after  the  function  body  is  translated. 

•  Type  checking.  Within  expressions,  a  function  is  treated  like  any  other 
operator.  T he  discussion  of type  checking in  Section  6.5.2  therefore  carries 
over,  including  t he  rules  for  coercions.  For  example,  i f / is  a  function  with 
a  parameter  of type  real,  then  the  integer  2  is  coerced  to  a  real  in  the  call 
/ ( 2 ). 

•  Function  calls.  When  generating  three-address  instructions  for  a  function 

call  id(E,  E,... 
,  E),  it  is  sufficient  to  generate  t he  three-address  instruc 
tions  for  evaluating  or  reducing  the  parameters  E  to  addresses,  followed 
If  we  do  not  want  to  mix 
by  a  param  instruction  for  each  parameter. 
t he  parameter-evaluating  instructions  with  t he  param  instructions, 
the 
a t t r i b u te  E.addr  for  each  expression  E  can  be  saved  in  a  d a ta  structure 

424 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

such  as  a  queue.  Once  all  the  expressions  are  translated,  t he  param  in 
structions  can  be  generated  as  t he  queue  is  emptied. 

The  procedure  is  such  an  important  and  frequently  used  programming  con 
struct  t h at  it  is  imperative  for  a  compiler  to  good  code  for  procedure  calls  and 
returns.  T he  run-time  routines  t h at  handle  procedure  p a r a m e t er  passing,  calls, 
and  returns  are  part  of t he  run-time  support  package.  Mechanisms  for  run-time 
support  are  discussed  in  Chapter  7. 

6.10  Summary  of  Chapter  6 

The  techniques  in  this  chapter  can  be  combined  to  build  a  simple  compiler  front 
end,  like  t he  one  in  Appendix  A.  The  front  end  can  be  built  incrementally: 

•  Pick  an 

intermediate  representation 

intermediate  representation:  An 

is 
typically  some  combination  of  a  graphical  notation  and  three-address 
code.  As  in  syntax  trees,  a  node  in  a  graphical  notation  represents  a 
construct;  the  children  of  a  node  represent  its  subconstructs.  Three  ad 
dress  code  takes  its  name  from  instructions  of  the  form  x  —  y  op  z,  with 
at  most  one  operator  per  instruction.  There  are  additional  instructions 
for  control  flow. 

4-  Translate  expressions:  Expressions  with  built-up  operations  can  be  un 
wound  into  a  sequence  of  individual  operations  by  attaching  actions  to 
each  production  of  t he  form  E  —>  E\  op  E2.  T he  action  either  creates 
a  node  for  E  with  t he  nodes  for  E\  and  E2  as  children,  or  it  generates 
a  three-address  instruction  t h at  applies  op  to  the  addresses  for  E\  and 
E2  and  puts  the  result  into  a  new  temporary  name,  which  becomes  t he 
address  for  E. 

•  Check  types:  The  type  of  an  expression  E\  op  E2  is  determined  by  t he 
operator  op  and  the  types  of  E\  and  E2.  A  coercion  is  an  implicit  type 
conversion,  such  as  from  integer  to  float.  Intermediate  code  contains  ex 
plicit  type  conversions  to  ensure  an  exact  match  between  operand  types 
and  the  types  expected  by  an  operator. 

•  Use  a  symbol  table  to  implement  declarations:  A  declaration  specifies  the 
type  of  a  name.  T he  width  of  a  type  is  the  amount  of  storage  needed  for 
a  name  with  t h at  type.  Using  widths,  t he  relative  address  of  a  name  at 
run  time  can  be  computed  as  an  offset  from  t he  start  of  a  d a ta  area.  T he 
type  and  relative  address  of  a  name  are  put  into  t he  symbol  table  due  to 
a  declaration,  so  t he  translator  can  subsequently  get  t h em  when  t he  name 
appears  in  an  expression. 

4-  Flatten  arrays:  For  quick  access,  array  elements  are  stored  in  consecutive 
locations.  Arrays  of  arrays  are  flattened  so  they  can  be  treated  as  a  one-

6.11. 

REFERENCES  FOR  CHAPTER  6 

425 

dimensional  array  of  individual  elements.  The  type  of  an  array  is  used  to 
calculate  the  address  of  an  array  element  relative  to  the  base  of the  array. 

Generate  jumping  code  for  boolean  expressions: 
In  short-circuit  or  j u m p 
ing  code,  the  value  of  a  boolean  expression  is  implicit  in  t he  position 
reached  in  t he  code.  Jumping  code  is  useful  because  a  boolean  expression 
B  is  typically  used  for  control  flow,  as  in  if  (B)  S.  Boolean  values  can  be 
computed  by  jumping  to  t  = t r ue  or  t  = f a l s e,  as  appropriate,  where  t  is 
a  temporary  name.  Using  labels  for  jumps,  a  boolean  expression  can  be 
translated  by  inheriting  labels  corresponding  to  its  true  and  false  exits. 
T he  constants  true  and  false  translate  into  a  j u mp  to  t he  t r ue  and  false 
exits,  respectively. 

• 

flow:  Statements  can  be  translated 
Implement  statements  using  control 
by  inheriting  a  label  next,  where  next  marks  the  first  instruction  after  t he 
code  for  this  statement.  T he  conditional  S  -> 
if  (B)  Si  can  be  translated 
by  attaching  a  new  label  marking  the  beginning  of  the  code  for  Si  and 
passing  the  new  label  and  S.next  for  t he  t r ue  and  false  exits,  respectively, 
oiB. 

•  Alternatively,  use  backpatching:  Backpatching  is  a  technique  for  generat 
ing  code  for  boolean  expressions  and  statements  in  one  pass.  T he  idea 
is  to  maintain  lists  of  incomplete  jumps,  where  all  the  j u mp  instructions 
on  a  list  have  t he  same  target.  When  t he  target  becomes  known,  all  t he 
instructions  on  its  list  are  completed  by  filling  in  t he  target. 

• 

Implement  records:  Field  names  in  a  record  or  class  can  be  treated  as  a 
sequence  of  declarations.  A  record  type  encodes  the  types  and  relative 
addresses  of t he  fields.  A  symbol  table  object  can  be  used  for  this  purpose. 

6.11  References  for  Chapter  6 

Most  of  t he  techniques  in  this  chapter  stem  from  the  flurry  of  design  and  im 
plementation  activity  around  Algol  60.  Syntax-directed  translation  into  inter 
mediate  code  was  well  established  by  t he  time  Pascal  [11]  and  C  [6,  9]  were 
created. 

U N C OL  (for  Universal  Compiler  Oriented  Language)  is  a  mythical  universal 

intermediate  language,  sought  since  t he  mid  1950's.  Given  an  UNCOL,  com 
pilers  could  be  constructed  by  hooking  a  front  end  for  a  given  source  language 
with  a  back  end  for  a  given  target  language  [10].  T he  bootstrapping  techniques 
given  in  the  report  [10]  are  routinely  used  to  retarget  compilers. 

T he  UNCOL  ideal  of  mixing  and  matching  front  ends  with  back  ends  has 
been  approached  in  a  number  of  ways.  A  retargetable  compiler  consists  of  one 
front  end  t h at  can  be  put  together  with  several  back  ends  to  implement  a  given 
language  on  several  machines.  Neliac  was  an  early  example  of  a  language  with 
a  retargetable  compiler  [5]  written  in  its  own  language.  Another  approach  is  to 

426 

CHAPTER 

6. 

INTERMEDIATE-CODE  GENERATION 

retrofit  a  front  end  for  a  new  language  onto  an  existing  compiler.  Feldman  [2] 
describes  t he  addition  of  a  Fortran  77  front  end  to  t he  C  compilers  [6]  and 
[9].  G C C,  the  GNU  Compiler  Collection  [3],  supports  front  ends  for  C,  C + +, 
Objective-C,  Fortran,  Java,  and  Ada. 

Value  numbers  and  their  implementation  by  hashing  are  from  Ershov  [1]. 
The  use  of  type  information  to  improve  t he  security  of  Java  bytecodes  is 

described  by  Gosling  [4]. 

Type  inference  by  using  unification  to  solve  sets  of  equations  has  been  re 
discovered  several  times;  its  application  to  ML  is  described  by  Milner  [7].  See 
Pierce  [8]  for  a  comprehensive  treatment  of  types. 

1.  Ershov,  A.  P.,  "On  programming  of  arithmetic  operations,"  Comm.  ACM 

1:8  (1958),  pp.  3-6.  See  also  Comm.  ACM  1:9  (1958),  p.  16. 

2.  Feldman,  S.  I.,  "Implementation  of  a  portable  Fortran  77  compiler  using 

modern  tools,"  ACM  SIGPLAN  Notices  14:8  (1979),  pp.  98-106 

3.  GCC  home  page  h t t p: / / g c c. gnu.  o r g /,  Free  Software  Foundation. 

4.  Gosling,  J.,  "Java  intermediate  bytecodes,"  Proc.  ACM  SIGPLAN  Work 

shop  on  Intermediate  Representations  (1995),  pp.  111-118. 

5.  Huskey,  H.  D.,  M.  H.  Halstead,  and  R.  McArthur,  "Neliac  —  a  dialect  of 

Algol,"  Comm.  ,4CM 3:8  (1960),  pp.  463-468. 

6.  Johnson,  S.  C,  "A  tour  through  the  portable  C  compiler,"  Bell  Telephone 

Laboratories,  Inc.,  Murray  Hill,  N.  J.,  1979. 

7.  Milner,  R.,  "A  theory  of  type  polymorphism  in  programming,"  J.  Com 

puter  and  System  Sciences  17:3  (1978),  pp.  348-375. 

8.  Pierce,  B . C .,  Types  and  Programming  Languages,  M IT  Press,  Cambridge, 

Mass.,  2002. 

9.  Ritchie,  D.  M.,  "A  tour  through  the  UNIX  C  compiler,"  Bell  Telephone 

Laboratories,  Inc.,  Murray  Hill,  N.  J.,  1979. 

10.  Strong,  J.,  J.  Wegstein,  A.  Tritter,  J.  Olsztyn,  0.  Mock,  and  T.  Steel, 
"The  problem  of  programming  communication  with  changing  machines: 
a  proposed  solution,"  Comm.  ACM  1:8  (1958),  pp.  12-18.  P a rt  2:  1:9 
(1958),  p p.  9-15.  Report  of  t he  Share  Ad-Hoc  committee  on  Universal 
Languages. 

11.  Wirth,  N.  "The  design  of  a  Pascal  compiler,"  Software—Practice  and 

Experience  1:4  (1971),  pp.  309-333. 

Chapter  7 

Run-Time  Environments 

A  compiler  must  accurately  implement  the  abstractions  embodied  in  the  source-
language  definition.  These  abstractions  typically  include  the  concepts  we  dis 
cussed  in  Section  1.6  such  as  names,  scopes,  bindings,  d a ta  types,  operators, 
procedures,  parameters,  and flow-of-control constructs.  The  compiler  must  co 
operate  with  the  operating  system  and  other  systems  software  to  support  these 
abstractions  on  t he  target  machine. 

To  do  so,  the  compiler  creates  and  manages  a  run-time  environment  in  which 
it  assumes  its  target  programs  are  being  executed.  This  environment  deals  with 
a  variety  of  issues  such  as  the  layout  and  allocation  of  storage  locations  for  t he 
objects  named  in  the  source  program,  the  mechanisms  used  by  t he  target  pro 
gram  to  access  variables,  the  linkages  between  procedures,  the  mechanisms  for 
passing  parameters,  and  the  interfaces  to  the  operating  system,  i n p u t / o u t p ut 
devices,  and  other  programs. 

T he  two  themes  in  this  chapter  are  the  allocation  of  storage  locations  and 
access  to  variables  and  data.  We  shall  discuss  memory  management  in  some 
detail,  including  stack  allocation,  heap  management,  and  garbage  collection.  In 
the  next  chapter,  we  present  techniques  for  generating  target  code  for  many 
common  language  constructs. 

7.1  Storage  Organization 

From  t he  perspective  of  the  compiler  writer,  the  executing  target  program  runs 
in  its  own  logical  address  space  in  which  each  program  value  has  a location.  T he 
management  and  organization  of  this  logical  address  space  is  shared  between 
the  compiler,  operating  system,  and  target  machine.  T he  operating  system 
maps  t he  logical  addresses  into  physical  addresses,  which  are  usually  spread 
throughout  memory. 

T he  run-time  representation  of  an  object  program  in  the  logical  address 
space  consists  of  d a ta  and  program  areas  as  shown  in  Fig.  7.1.  A  compiler  for  a 

427 

428 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

language  like  C ++  on  an  operating  system  like  Linux  might  subdivide  memory 
in  this  way. 

Code 

Static 

Heap 

Free  Memory 

t 

Stack 

Figure  7.1:  Typical  subdivision  of  run-time  memory  into  code  and  d a ta  areas 

Throughout  this  book,  we  assume  the  run-time  storage  comes  in  blocks  of 
contiguous  bytes,  where  a  byte  is  the  smallest  unit  of  addressable  memory.  A 
byte  is  eight  bits  and  four  bytes  form  a  machine  word.  Multibyte  objects  are 
stored  in  consecutive  bytes  and  given  the  address  of  the  first  byte. 

As  discussed  in  Chapter  6,  the  amount  of  storage  needed  for  a  name  is  de 
termined  from  its  type.  An  elementary  d a ta  type,  such  as  a  character,  integer, 
or  float,  can  be  stored  in  an  integral  number  of  bytes.  Storage  for  an  aggre 
gate  type,  such  as  an  array  or  structure,  must  be  large  enough  to  hold  all  its 
components. 

T he  storage  layout  for  d a ta  objects  is  strongly  influenced  by  the  addressing 
constraints  of  the  target  machine.  On  many  machines,  instructions  to  add 
integers  may  expect  integers  to  be  aligned,  t h at  is,  placed  at  an  address  divisible 
by  4.  Although  an  array  of  ten  characters  needs  only  enough  bytes  to  hold  ten 
characters,  a  compiler  may  allocate  12  bytes  to  get  the  proper  alignment,  leaving 
2  bytes  unused.  Space  left  unused  due  to  alignment  considerations  is  referred 
to  as  padding.  W h en  space  is  at  a  premium,  a  compiler  may  pack  d a ta  so  t h at 
no  padding  is  left;  additional  instructions  may  then  need  to  be  executed  at  run 
time  to  position  packed  d a ta  so  t h at  it  can  be  operated  on  as  if it  were  properly 
aligned. 

T he  size  of  t he  generated  target  code  is  fixed  at  compile  time,  so  t he  com 

piler  can  place  t he  executable  target  code  in  a  statically  determined  area  Code, 
usually  in  t he  low  end  of  memory.  Similarly,  t he  size  of  some  program  d a ta 
objects,  such  as  global  constants,  and  d a ta  generated  by  t he  compiler,  such  as 
information  to  support  garbage  collection,  may  be  known  at  compile  time,  and 
these  d a ta  objects  can  be  placed  in  another  statically  determined  area  called 
Static.  One  reason  for  statically  allocating  as  many  d a ta  objects  as  possible  is 

7.1. 

STORAGE  ORGANIZATION 

429 

t h at  the  addresses  of  these  objects  can  be  compiled  into  the  target  code. 
early  versions  of  Fortran,  all  d a ta  objects  could  be  allocated  statically. 

In 

To  maximize  t he  utilization  of  space  at  run  time,  t he  other  two  areas,  Stack 
and  Heap,  are  at  t he  opposite  ends  of t he  remainder  of the  address  space.  These 
areas  are  dynamic;  their  size  can  change  as  the  program  executes.  These  areas 
grow  towards  each  other  as  needed.  The  stack  is  used  to  store  d a ta  structures 
called  activation  records  t h at  get  generated  during  procedure  calls. 

In  practice,  the  stack  grows  towards  lower  addresses,  t he  heap  towards 
higher.  However,  throughout  this  chapter  and  t he  next  we  shall  assume  t h at 
t he  stack  grows  towards  higher  addresses  so  t h at  we  can  use  positive  offsets  for 
notational  convenience  in  all  our  examples. 

As  we  shall  see  in  the  next  section,  an  activation  record  is  used  to  store 
information  about  the  status  of  the  machine,  such  as  the  value  of  t he  program 
counter  and  machine  registers,  when  a  procedure  call  occurs.  W h en  control 
returns  from  the  call,  the  activation  of  the  calling  procedure  can  be  restarted 
after  restoring  the  values  of  relevant  registers  and  setting  the  program  counter 
to  t he  point  immediately  after  the  call.  D a ta  objects  whose  lifetimes  are  con 
tained  in  t h at  of  an  activation  can  be  allocated  on  the  stack  along  with  other 
information  associated  with  the  activation. 

Many  programming  languages  allow  the  programmer  to  allocate  and  deal 
locate  d a ta  under  program  control.  For  example,  C  has  t he  functions  m a l l oc 
and  f r ee  t h at  can  be  used  to  obtain  and  give  back  arbitrary  chunks  of  stor 
age.  T he  heap  is  used  to  manage  this  kind  of  long-lived  data.  Section  7.4  will 
discuss  various  memory-management  algorithms  t h at  can  be  used  to  maintain 
the  heap. 

7.1.1 

Static  Versus  Dynamic  Storage  Allocation 

T he  layout  and  allocation  of  d a ta  to  memory  locations  in  the  run-time  envi 
ronment  are  key  issues  in  storage  management.  These  issues  are  tricky  because 
the  same  name  in  a  program  text  can  refer  to  multiple  locations  at  run  time. 
The  two  adjectives  static  and  dynamic  distinguish  between  compile  time  and 
run  time,  respectively.  We  say  t h at  a  storage-allocation  decision  is  static,  if  it 
can  be  made  by  t he  compiler  looking  only  at  the  text  of  the  program,  not  at 
what  t he  program  does  when  it  executes.  Conversely,  a  decision  is  dynamic  if 
it  can  be  decided  only  while  the  program  is  running.  Many  compilers  use  some 
combination  of  the  following  two  strategies  for  dynamic  storage  allocation: 

1.  Stack  storage.  Names  local  to  a  procedure  are  allocated  space  on  a  stack. 
We  discuss  t he  "run-time  stack"  starting  in  Section  7.2.  The  stack  sup 
ports  t he  normal  call/return  policy  for  procedures. 

2.  Heap  storage.  D a ta  t h at  may  outlive  the  call  to  the  procedure  t h at  cre 

ated  it  is  usually  allocated  on  a  "heap"  of  reusable  storage.  We  discuss 
heap  management  starting  in  Section  7.4.  The  heap  is  an  area  of  virtual 

430 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

memory  t h at  allows  objects  or  other  d a ta  elements  to  obtain  storage  when 
they  are  created  and  to  return  t h at  storage  when  they  are  invalidated. 

To  support  heap  management,  "garbage  collection"  enables  the  run-time 

system  to  detect  useless  d a ta  elements  and  reuse  their  storage,  even  if  t he  pro 
grammer  does  not  return  their  space  explicitly.  Automatic  garbage  collection 
is  an  essential  feature  of  many  modern  languages,  despite  it  being  a  difficult 
operation  to  do  efficiently;  it  may  not  even  be  possible  for  some  languages. 

7.2  Stack  Allocation  of  Space 

Almost  all  compilers  for  languages  t h at  use  procedures,  functions,  or  methods 
as  units  of  user-defined  actions  manage  at  least  part  of  their  run-time  memory 
as  a  stack.  Each  time  a  procedure1  is  called,  space  for  its  local  variables  is 
pushed  onto  a  stack,  and  when  the  procedure  terminates,  t h at  space  is  popped 
off  the  stack.  As  we  shall  see,  this  arrangement  not  only  allows  space  to  be 
shared  by  procedure  calls  whose  durations  do  not  overlap  in  time,  but  it  allows 
us  to  compile  code  for  a  procedure  in  such  a  way  t h at  t he  relative  addresses  of its 
nonlocal  variables  are  always  t he  same,  regardless  of the  sequence  of  procedure 
calls. 

7.2.1  Activation  Trees 

Stack  allocation  would  not  be  feasible  if  procedure  calls,  or  activations  of  pro 
cedures,  did  not  nest  in  time.  The  following  example  illustrates  nesting  of 
procedure  calls. 

E x a m p le  7 . 1:  Figure  7.2  contains  a  sketch  of  a  program  t h at  reads  nine  inte 
gers  into  an  array  a  and  sorts  t h em  using  t he  recursive  quicksort  algorithm. 

The  main  function  has  three  tasks.  It  calls  readArray,  sets  t he  sentinels,  and 
then  calls  quicksort  on  the  entire  d a ta  array.  Figure  7.3  suggests  a  sequence  of 
calls  t h at  might  result  from  an  execution  of t he  program.  In  this  execution,  t he 
call  to  partition(l,9)  returns  4,  so  a[l]  through  a[3]  hold  elements  less  t h an  its 
chosen  separator  value  v,  while  the  larger  elements  are  in  a  [5]  through  a  [9].  • 

In  this  example,  as  is  t r ue  in  general,  procedure  activations  are  nested  in 
time.  If  an  activation  of  procedure  p  calls  procedure  q,  then  t h at  activation  of 
q  must  end  before  t he  activation  of p  can  end.  There  are  three  common  cases: 

1.  The  activation  of q  terminates  normally.  Then  in  essentially  any  language, 
control  resumes  just  after  the  point  of p  at  which  t he  call  to  q  was  made. 

2.  T he  activation  of  q,  or  some  procedure  q  called,  either  directly  or  indi 
rectly,  aborts;  i.e.,  it  becomes  impossible  for  execution  to  continue. 
t h at  case,  p  ends  simultaneously  with  q. 

In 

1 Recall  we  use  "procedure"  as  a  generic  term  for  function,  procedure,  method,  or  subrou 

tine. 

7.2. 

STACK  ALLOCATION  OF  SPACE 

431 

i nt  a [ 1 1 ]; 
v o id  r e a d A r r a yO  { 
i; 

i nt 

/*  Reads  9  integers  into  o[l],  ...,o[9].  */ 

} 
i nt  p a r t i t i o n ( i nt  m, 

i nt  n)  { 

/*  Picks  a  separator  value  v,  and  partitions  a[m  ..n]  so  t h at 
a[m  ..p  —  1]  are  less  t h an  v,  a\p]  =  v,  and  a\p +  1.. n]  are 
equal  to  or  greater  t h an  v.  Returns  p.  */ 

} 
v o id  q u i c k s o r t ( i nt  m, 

i nt  n)  { 

i; 

i nt 
if  (n  >  m)  { 

i  =  p a r t i t i o n ( m,  n ); 
q u i c k s o r t ( m, 
i - 1 ); 
q u i c k s o r t ( i + 1,  n ); 

} 

} 
m a i nQ  { 

r e a d A r r a yO  ; 
a [ 0]  =  - 9 9 9 9; 
a [10]  =  9 9 9 9; 
q u i c k s o r t ( 1 , 9 ); 

} 

Figure  7.2:  Sketch  of  a  quicksort  program 

3.  T he  activation  of q  terminates  because  of  an  exception  t h at  q  cannot  han 
dle.  Procedure  p  may  handle  the  exception,  in  which  case  the  activation 
of  q  has  terminated  while  t he  activation  of p  continues,  although  not  nec 
essarily  from  t he  point  at  which  the  call  to  q  was  made.  If p  cannot  handle 
t he  exception,  then  this  activation  of p  terminates  at  the  same  time  as  t he 
activation  of  q,  and  presumably  the  exception  will  be  handled  by  some 
other  open  activation  of  a  procedure. 

We  therefore  can  represent  the  activations  of procedures  during  t he  running 
of  an  entire  program  by  a  tree,  called  an  activation  tree.  Each  node  corresponds 
to  one  activation,  and  the  root  is  the  activation  of  t he  "main"  procedure  t h at 
initiates  execution  of  the  program.  At  a  node  for  an  activation  of  procedure  p, 
the  children  correspond  to  activations  of t he  procedures  called  by  this  activation 
of p.  We  show  these  activations  in  t he  order  t h at  they  are  called,  from  left  to 
right.  Notice  t h at  one  child  must  finish  before  t he  activation  to  its  right  can 
begin. 

432 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

A  Version  of  Quicksort 

T he  sketch  of a  quicksort  program  in  Fig.  7.2  uses  two  auxiliary  functions 
readArray  and  partition.  T he  function  readArray  is  used  only  to  load  the 
d a ta  into  the  array  a.  T he  first  and  last  elements  of  a  are  not  used  for 
data,  but  rather  for  "sentinels"  set  in  the  main  function.  We  assume  a[0] 
is  set  to  a  value  lower  t h an  any  possible  d a ta  value,  and  a[10]  is  set  to  a 
value  higher  t h an  any  d a ta  value. 

The  function  partition  divides  a  portion  of  the  array,  delimited  by  t he 
arguments  m  and  n,  so  the  low  elements  of  a[m]  through  a[n]  are  at  t he 
beginning,  and  the  high  elements  are  at  the  end,  although  neither  group  is 
necessarily  in  sorted  order.  We  shall  not  go  into  the  way  partition  works, 
except  t h at  it  may  rely  on  t he  existence  of  t he  sentinels.  One  possible 
algorithm  for  partition  is  suggested  by  the  more  detailed  code  in  Fig.  9.1. 
Recursive  procedure  quicksort  first  decides  if  it  needs  to  sort  more 
t h an  one  element  of  t he  array.  Note  t h at  one  element  is  always  "sorted," 
so  quicksort  has  nothing  to  do  in  t h at  case.  If  there  are  elements  to  sort, 
quicksort  first  calls  partition,  which  returns  an  index  i  to  separate  t he  low 
and  high  elements.  These  two  groups  of  elements  are  then  sorted  by  two 
recursive  calls  to  quicksort. 

E x a m p le  7 . 2:  One  possible  activation  tree  t h at  completes  the  sequence  of 
calls  and  returns  suggested  in  Fig.  7.3  is  shown  in  Fig.  7.4.  Functions  are 
represented  by  t he  first  letters  of their  names.  Remember  t h at  this  tree  is  only 
one  possibility,  since  t he  arguments  of subsequent  calls,  and  also  t he  number  of 
calls  along  any  branch  is  influenced  by  the  values  returned  by  partition. 

• 

T he  use  of a  run-time  stack  is  enabled  by  several  useful  relationships  between 

t he  activation  tree  and  t he  behavior  of t he  program: 

1.  T he  sequence  of procedure  calls  corresponds  to  a  preorder  traversal  of the 

activation  tree. 

2.  T he  sequence  of  returns  corresponds  to  a  postorder  traversal  of  t he  acti 

vation  tree. 

3.  Suppose  t h at  control  lies  within  a  particular  activation  of some  procedure, 
corresponding  to  a  node  N  of  t he  activation  tree.  T h en  t he  activations 
t h at  are  currently  open  (live)  are  those  t h at  correspond  to  node  N  and  its 
ancestors.  T he  order  in  which  these  activations  were  called  is  the  order 
in  which  they  appear  along  t he  p a th  to  N,  starting  at  t he  root,  and  they 
will  return  in  the  reverse  of  t h at  order. 

7.2. 

STACK  ALLOCATION  OF  SPACE 

433 

e n t er  m a i nQ 
e n t er 
l e a ve 
e n t er  q u i c k s o r t ( 1 , 9) 

r e a d A r r a yO 
r e a d A r r a yO 

e n t er  p a r t i t i o n ( 1 , 9) 
l e a ve  p a r t i t i o n ( l , 9) 
e n t er  q u i c k s o r t ( 1 , 3) 

l e a ve  q u i c k s o r t ( 1 , 3) 
e n t er  q u i c k s o r t ( 5 , 9) 

l e a ve  q u i c k s o r t ( 5 , 9) 

l e a ve  q u i c k s o r t ( 1 , 9) 

l e a ve  m a i n () 

Figure  7.3:  Possible  activations  for  the  program  of  Fig.  7.2 

,<2f(l,9) 

P( l , 9) 

(7(1,3) 

^ 9 ( 5 , 9) 

p ( l , 3)  g ( l , 0 ^ ( 2 , 3^ 

p(5,9) 

0 ( 5 , 5 ^ g ( 7 , 9^ 

p(2,3)  0(2,1)  g(3,3) 

p(7,9)  0(7,7)  0(9,9) 

Figure  7.4:  Activation  tree  representing  calls  during  an  execution  of  quicksort 

7.2.2  Activation  Records 

Procedure  calls  and  returns  are  usually  managed  by  a  run-time  stack  called  the 
control  stack.  Each  live  activation  has  an  activation  record  (sometimes  called  a 
frame)  on  the  control  stack,  with  the  root  of  the  activation  tree  at  t he  b o t t o m, 
and  the  entire  sequence  of  activation  records  on  t he  stack  corresponding  to  the 
p a th  in  t he  activation  tree  to  t he  activation  where  control  currently  resides. 
The  latter  activation  has  its  record  at  t he  top  of  t he  stack. 

E x a m p le  7 . 3: 
If  control  is  currently  in  t he  activation  0(2,3)  of  the  tree  of 
Fig.  7.4,  then  the  activation  record  for  q(2,3)  is  at  the  top  of  the  control  stack. 
J u st  below  is  t he  activation  record  for  0(1,3),  t he  parent  of  0(2,3)  in  the  tree. 
Below  t h at  is  the  activation  record  0(1,9),  and  at  the  b o t t om  is  t he  activation 
record  for  m,  the  main  function  and  root  of  the  activation  tree. 

• 

434 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

We  shall  conventionally  draw  control  stacks  with  the  b o t t om  of  t he  stack 
higher  t h an  the  top,  so  the  elements  in  an  activation  record  t h at  appear  lowest 
on  t he  page  are  actually  closest  to  t he  top  of  t he  stack. 

The  contents  of  activation  records  vary  with  t he  language  being  imple 
mented.  Here  is  a  list  of  t he  kinds  of  d a ta  t h at  might  appear  in  an  activation 
record  (see  Fig.  7.5  for  a  summary  and  possible  order  for  these  elements): 

Actual  parameters 

Returned  values 

Control  link 

Access  link 

Saved  machine  status 

Local  d a ta 

Temporaries 

Figure  7.5:  A  general  activation  record 

1.  Temporary  values,  such  as  those  arising  from  the  evaluation  of  expres 

sions,  in  cases  where  those  temporaries  cannot  be  held  in  registers. 

2.  Local  d a ta  belonging  to  the  procedure  whose  activation  record  this  is. 

3.  A  saved  machine  status,  with  information  about  the  s t a te  of  t he  machine 
just  before  t he  call  to  t he  procedure.  This  information  typically  includes 
the  return  address  (value  of  t he  program  counter,  to  which  t he  called 
procedure  must  return)  and  t he  contents  of  registers  t h at  were  used  by 
the  calling  procedure  and  t h at  must  be  restored  when  t he  return  occurs. 

4.  An  "access  link"  may  be  needed  to  locate  d a ta  needed  by  t he  called  proce 

dure  but  found  elsewhere,  e.g.,  in  another  activation  record.  Access  links 
are  discussed  in  Section  7.3.5. 

5.  A  control  link,  pointing  to  t he  activation  record  of  t he  caller. 

6.  Space  for  the  return  value  of  the  called  function,  if  any.  Again,  not  all 
called  procedures  return  a  value,  and  if  one  does,  we  may  prefer  to  place 
t h at  value  in  a  register  for  efficiency. 

7.  T he  actual  parameters  used  by  the  calling  procedure.  Commonly,  these 
values  are  not  placed  in  t he  activation  record  but  rather  in  registers,  when 
possible,  for  greater  efficiency.  However,  we  show  a  space  for  t h em  to  be 
completely  general. 

7.2. 

STACK  ALLOCATION  OF  SPACE 

435 

E x a m p le  7 . 4:  Figure  7.6  shows  snapshots  of  the  run-time  stack  as  control 
flows  through  t he  activation  tree  of  Fig.  7.4.  Dashed  lines  in  t he  partial  trees 
go  to  activations  t h at  have  ended.  Since  array  a  is  global,  space  is  allocated  for 
it  before  execution  begins  with  an  activation  of  procedure  main,  as  shown  in 
Fig.  7.6(a). 

integer 

q[ll] 

integer 

a[ll] 

mam 

mam 

main 

(a)  Frame  for  main 

integer 

o[ll] 

mam 

mam 

9(1,9) 

integer_  m2  n_ 

9(1,9) 

integer 

i 

integer 

(b)  r  is  activated 

integer 

a[ll] 

mam 

integer^  m,  n_ 

9(1,9) 

integer 

i 

integer^  m,  n_ 

9(1,3) 

integer 

i 

r 

g(l,9) 
/  j 

p(l,9)  g(l,3) 
/ 

i 
i 

/ 

p(l,3)  q(l,0) 

(c)  r  has  been  popped  and  q(l,9)  pushed 

(d)  Control  returns  to  g ( l , 3) 

Figure  7.6:  Downward-growing  stack  of  activation  records 

W h en  control  reaches  the  first  call  in  the  body  of  main,  procedure  r  is 
activated,  and  its  activation  record  is  pushed  onto  the  stack  (Fig.  7.6(b)).  T he 
activation  record  for  r  contains  space  for  local  variable  i.  Recall  t h at  t he  t op  of 
stack  is  at  the  b o t t om  of  diagrams.  When  control  returns  from  this  activation, 
its  record  is  popped,  leaving  just  the  record  for  main  on  the  stack. 

Control  then  reaches  the  call  to  q  (quicksort)  with  actual  parameters  1  and 
9,  and  an  activation  record  for  this  call  is  placed  on  the  top  of  the  stack,  as  in 
Fig.  7.6(c).  T he  activation  record  for  q  contains  space  for  t he  parameters  m 
and  n  and  the  local  variable  i,  following  the  general  layout  in  Fig.  7.5.  Notice 
t h at  space  once  used  by  the  call  of  r  is  reused  on  t he  stack.  No  trace  of  d a ta 
local  to  r  will  be  available  to  q(l,  9).  When  q(l,  9)  returns,  t he  stack  again  has 
only  t he  activation  record  for  main. 

Several  activations  occur  between  t he  last  two  snapshots  in  Fig.  7.6.  A 
recursive  call  to  g ( l , 3)  was  made.  Activations  p ( l , 3)  and  q(l,0)  have  begun 
and  ended  during  t he  lifetime  of  q(l,  3),  leaving  the  activation  record  for  q(l,  3) 

436 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

on  top  (Fig.  7.6(d)).  Notice  t h at  when  a  procedure  is  recursive,  it  is  normal  to 
have  several  of  its  activation  records  on  the  stack  at  the  same  time. 

• 

7.2.3  Calling  Sequences 

Procedure  calls  are  implemented  by  what  are  known  as  calling  sequences,  which 
consists  of  code  t h at  allocates  an  activation  record  on  t he  stack  and  enters 
information  into  its  fields.  A  return  sequence  is  similar  code  to  restore  t he  state 
of the  machine  so  the  calling  procedure  can  continue  its  execution  after  t he  call. 
Calling  sequences  and  the  layout  of  activation  records  may  differ  greatly, 
even  among  implementations  of  the  same  language.  The  code  in  a  calling  se 
quence  is  often  divided  between  the  calling  procedure  (the  "caller")  and  t he 
procedure  it  calls  (the  "callee").  There  is  no  exact  division  of  run-time  tasks 
between  caller  and  callee;  the  source  language,  the  target  machine,  and  the  op 
erating  system  impose  requirements  t h at  may  favor  one  solution  over  another. 
In  general,  if  a  procedure  is  called  from  n  different  points,  then  t he  portion  of 
the  calling  sequence  assigned  to  the  caller  is  generated  n  times.  However,  t he 
portion  assigned  to  t he  callee  is  generated  only  once.  Hence,  it  is  desirable  to 
put  as  much  of  t he  calling  sequence  into  t he  callee  as  possible  —  whatever  the 
callee  can  be  relied  upon  to  know.  We  shall  see,  however,  t h at  the  callee  cannot 
know  everything. 

When  designing  calling  sequences  and  t he  layout  of  activation  records,  t he 

following  principles  are  helpful: 

1.  Values  communicated  between  caller  and  callee  are  generally  placed  at  t he 
beginning  of the  callee's  activation  record,  so  they  are  as  close  as  possible 
to  the  caller's  activation  record.  T he  motivation  is  t h at  the  caller  can 
compute  t he  values  of  t he  actual  parameters  of  the  call  and  place  them 
on  top  of  its  own  activation  record,  without  having  to  create  the  entire 
activation  record  of  t he  callee,  or  even  to  know  t he  layout  of  t h at  record. 
Moreover,  it  allows  for  the  use  of  procedures  t h at  do  not  always  take 
t he  same  number  or  type  of  arguments,  such  as  C's  p r i n tf  function. 
The  callee  knows  where  to  place  t he  return  value,  relative  to  its  own 
activation  record,  while  however  many  arguments  are  present  will  appear 
sequentially  below  t h at  place  on  the  stack. 

2.  Fixed-length  items  are  generally  placed  in  t he  middle.  From  Fig.  7.5,  such 
items  typically  include  t he  control  link,  the  access  link,  and  t he  machine 
status  fields.  If  exactly  t he  same  components  of  the  machine  status  are 
saved  for  each  call,  then  the  same  code  can  do  the  saving  and  restoring 
for  each.  Moreover,  if  we  standardize  t he  machine's  status  information, 
then  programs  such  as  debuggers  will  have  an  easier  time  deciphering  t he 
stack  contents  if  an  error  occurs. 

3.  Items  whose  size  may  not  be  known  early  enough  are  placed  at  t he  end 
of  t he  activation  record.  Most  local  variables  have  a  fixed  length,  which 

7.2.  STACK  ALLOCATION  OF  SPACE 

437 

can  be  determined  by  the  compiler  by  examining  t he  type  of the  variable. 
However,  some  local  variables  have  a  size  t h at  cannot  be  determined  until 
the  program  executes;  the  most  common  example  is  a  dynamically  sized 
array,  where  t he  value  of  one  of  t he  callee's  parameters  determines  t he 
length  of  t he  array.  Moreover,  the  amount  of  space  needed  for  tempo 
raries  usually  depends  on  how  successful  the  code-generation  phase  is  in 
keeping  temporaries  in  registers.  Thus,  while  the  space  needed  for  tem 
poraries  is  eventually  known  to  the  compiler,  it  may  not  be  known  when 
the  intermediate  code  is  first  generated. 

4.  We  must  locate  the  top-of-stack  pointer  judiciously.  A  common  approach 
is  to  have  it  point  to  the  end  of  the  fixed-length  fields  in  the  activation 
record.  Fixed-length  d a ta  can  then  be  accessed  by  fixed  offsets,  known  to 
the  intermediate-code  generator,  relative  to  the  top-of-stack  pointer.  A 
consequence  of this  approach  is  t h at  variable-length  fields  in  the  activation 
records  are  actually  "above"  the  top-of-stack.  Their  offsets  need  to  be 
calculated  at  run  time,  but  they  too  can  be  accessed  from  the  top-of-
stack  pointer,  by  using  a  positive  offset. 

Parameters  and  returned  value 

Control 

link 

Links  and  saved  status 

Temporaries  and  local  data 

Parameters  and  returned  value 

Control 

link 

Links  and  saved  status 

Temporaries  and  local  data 

Caller's 
activation 
record 

Caller's 
responsibility 

Callee's 
activation 
record 

Callee's 
responsibility 

Figure  7.7:  Division  of  tasks  between  caller  and  callee 

An  example  of how  caller  and  callee  might  cooperate  in  managing  the  stack 
is  suggested  by  Fig.  7.7.  A  register  topsp  points  to  t he  end  of  t he  machine-
status field in  the  current  top  activation  record.  This  position  within  the  callee's 
activation  record  is  known  to  t he  caller,  so  t he  caller  can  be  made  responsible 
for  setting  topsp  before  control  is  passed  to  the  callee.  The  calling  sequence 
and  its  division  between  caller  and  callee  is  as  follows: 

1.  T he  caller  evaluates  t he  actual  parameters. 

438 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

2.  The  caller  stores  a  return  address  and  the  old  value  of  topsp  into  the 
callee's  activation  record.  The  caller  then  increments  topsp  to  the  po 
sition  shown  in  Fig.  7.7.  T h at  is,  topsp  is  moved  past  t he  caller's  local 
d a ta  and  temporaries  and  the  callee's  parameters  and  status  fields. 

3.  T he  callee  saves  the  register  values  and  other  status  information. 

4.  The  callee  initializes  its  local  d a ta  and  begins  execution. 

A  suitable,  corresponding  return  sequence  is: 

1.  The  callee  places  the  return  value  next  to  the  parameters,  as  in  Fig.  7.5. 

2.  Using  information  in  t he  machine-status  field,  t he  callee  restores  topsp 
and  other  registers,  and  then  branches  to  the  return  address  t h at  the 
caller  placed  in  t he  status  field. 

3.  Although  topsp  has  been  decremented,  t he  caller  knows  where  t he  return 
value  is,  relative  to  the  current  value  of  topsp;  the  caller  therefore  may 
use  t h at  value. 

The  above  calling  and  return  sequences  allow  the  number  of  arguments  of 
the  called  procedure  to  vary  from  call  to  call  (e.g.,  as  in  C's  p r i n tf  function). 
Note  t h at  at  compile  time,  t he  target  code  of t he  caller  knows  t he  number  and 
types  of  arguments  it  is  supplying  to  t he  callee.  Hence  the  caller  knows  the  size 
of the  parameter  area.  T he  target  code  of t he  callee,  however,  must  be  prepared 
to  handle  other  calls  as  well,  so  it  waits  until  it  is  called  and  then  examines  t he 
parameter  field.  Using  the  organization  of  Fig.  7.7,  information  describing  the 
parameters  must  be  placed  next  to  the  status  field,  so  t he  callee  can  find  it. 
For  example,  in  t he  p r i n tf  function  of  C,  the  first  argument  describes  t he 
remaining  arguments,  so  once  the  first  argument  has  been  located,  t he  caller 
can  find  whatever  other  arguments  there  are. 

7.2.4  Variable-Length  Data  on  the  Stack 

The  run-time  memory-management  system  must  deal  frequently  with  the  allo 
cation  of  space  for  objects  t he  sizes  of  which  are  not  known  at  compile  time, 
but  which  are  local  to  a  procedure  and  thus  may  be  allocated  on  t he  stack.  In 
modern  languages,  objects  whose  size  cannot  be  determined  at  compile  time  are 
allocated  space  in  the  heap,  the  storage  structure  t h at  we  discuss  in  Section  7.4. 
However,  it  is  also  possible  to  allocate  objects,  arrays,  or  other  structures  of 
unknown  size  on  the  stack,  and  we  discuss  here  how  to  do  so.  T he  reason  to 
prefer  placing  objects  on  t he  stack  if  possible  is  t h at  we  avoid  t he  expense  of 
garbage  collecting  their  space.  Note  t h at  the  stack  can  be  used  only  for  an 
object  if it  is  local  to  a  procedure  and  becomes  inaccessible  when  the  procedure 
returns. 

A  common  strategy  for  allocating  variable-length  arrays  (i.e.,  arrays  whose 
size  depends  on  t he  value  of  one  or  more  parameters  of the  called  procedure)  is 

7.2. 

STACK  ALLOCATION  OF  SPACE 

439 

shown  in  Fig.  7.8.  T he  same  scheme  works  for  objects  of  any  type  if  they  are 
local  to  the  procedure  called  and  have  a  size  t h at  depends  on  t he  parameters 
of  the  call. 

In  Fig.  7.8,  procedure p has three  local  arrays,  whose  sizes  we  suppose  cannot 
be  determined  at  compile  time.  T he  storage  for  these  arrays  is  not  p a rt  of  t he 
activation  record  for  p,  although  it  does  appear  on  t he  stack.  Only  a  pointer 
to  the  beginning  of  each  array  appears  in  t he  activation  record  itself.  Thus, 
when  p  is  executing,  these  pointers  are  at  known  offsets  from  t he  top-of-stack 
pointer,  so  t he  target  code  can  access  array  elements  through  these  pointers. 

Control  link  and  saved  status 

Pointer  to  a 
Pointer  to  b 
Pointer  to  c 

Array  a 

Array  b 

Array  c 

Activation  record 
for  p 

Arrays  of  p 

Control  link  and  saved  status 

Activation  record  for 
procedure  q  called  by  p 

Arrays  of  q 

topsp 

top 

Figure  7.8:  Access  to  dynamically  allocated  arrays 

Also  shown  in  Fig.  7.8  is  the  activation  record  for  a  procedure  q,  called  by p. 
The  activation  record  for  q  begins  after  t he  arrays  of p,  and  any  variable-length 
arrays  of  q  are  located  beyond  t h a t. 

Access  to  the  d a ta  on  t he  stack  is  through  two  pointers, 

top  and  topsp. 
top  marks  t he  actual  top  of  stack;  it  points  to  the  position  at  which 
Here, 
the  next  activation  record  will  begin.  T he  second,  topsp  is  used  to  find  local, 
fixed-length  fields  of  t he  top  activation  record.  For  consistency  with  Fig.  7.7, 
we  shall  suppose  t h at  topsp  points  to  t he  end  of  the  machine-status  field. 
In 
Fig.  7.8,  topsp  points  to  t he  end  of  this  field  in  the  activation  record  for  q. 
From  there,  we  can  find  t he  control-link  field  for  q,  which  leads  us  to  the  place 
in  t he  activation  record  for  p  where  topsp  pointed  when  p  was  on  top. 

T he  code  to  reposition  top  and  topsp  can  be  generated  at  compile  time, 

440 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

in  terms  of  sizes  t h at  will  become  known  at  run  time.  When  q  returns,  topsp 
can  be  restored  from  t he  saved  control  link  in  t he  activation  record  for  q.  T he 
new  value  of  top  is  (the  old  unrestored  value  of)  topsp  minus  the  length  of  t he 
machine-status,  control  and  access  link,  return-value,  and  parameter  fields  (as 
in  Fig.  7.5)  in  q's  activation  record.  This  length  is  known  at  compile  time  to 
the  caller,  although  it  may  depend  on  t he  caller,  if  the  number  of  parameters 
can  vary  across  calls  to  q. 

7.2.5  Exercises  for  Section  7.2 

E x e r c i se  7 . 2 . 1:  Suppose  t h at  the  program  of  Fig.  7.2  uses  a  partition  function 
t h at  always  picks  a[m]  as  the  separator  v.  Also,  when  t he  array  a[m],...  ,a[n] 
is  reordered,  assume  t h at  the  order  is  preserved  as  much  as  possible.  T h at  is, 
first  come  all  t he  elements  less  t h an  v,  in  their  original  order,  then  all  elements 
equal  to  v,  and  finally  all  elements  greater  t h an  v,  in  their  original  order. 

a)  Draw  t he  activation  tree  when  the  numbers  9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 ,1  are  sorted. 

b)  W h at  is  the  largest  number  of activation  records  t h at  ever  appear  together 

on  the  stack? 

E x e r c i se  7 . 2 . 2:  Repeat  Exercise  7.2.1  when  t he  initial  order  of  t he  numbers 
is  1,3,5,7,9,2,4,6,8. 

E x e r c i se  7 . 2 . 3:  In  Fig.  7.9  is  C  code  to  compute  Fibonacci  numbers  recur 
sively.  Suppose  t h at  the  activation  record  for  /  includes  the  following  elements 
in  order: 
(return  value,  argument  n,  local  s,  local  t);  there  will  normally  be 
other  elements  in  t he  activation  record  as  well.  T he  questions  below  assume 
t h at  the  initial  call  is  / ( 5 ). 

a)  Show  the  complete  activation  tree. 

b)  W h at  does  the  stack  and  its  activation  records  look  like  t he  first  time  / ( l) 

is  about  to  return? 

!  c)  W h at  does  the  stack  and  its  activation  records  look  like  t he  fifth  time 

/ ( l)  is  about  to  return? 

E x e r c i se  7 . 2 . 4:  Here  is  a  sketch  of  two  C  functions  /  and  g: 

int  f(int x)  {  int  i; ••• return i+1; •••  } 

int g(int y)  {  int j; ••• f ( j +D •••  1 

T h at  is,  function  g  calls  /.  Draw  the  top  of  the  stack,  starting  with  the  acti 
vation  record  for  g,  after  g  calls  /,  and  /  is  about  to  return.  You  can  consider 
only  return  values,  parameters,  control  links,  and  space  for  local  variables;  you 
do  not  have  to  consider  stored  state  or  temporary  or  local  values  not  shown  in 
the  code  sketch.  However,  you  should  indicate: 

7.3. 

ACCESS  TO  NONLOCAL  DATA  ON  THE  STACK 

441 

(n  <  2)  r e t u rn  1; 

s; 

f ( i nt  n)  { 
i nt 
t, 
if 
s  =  f ( n - l ); 
t  =  f ( n - 2 ); 
r e t u rn  s + t; 

i nt 

} 

Figure  7.9:  Fibonacci  program  for  Exercise  7.2.3 

a)  Which  function  creates  the  space  on  the  stack  for  each  element? 

b)  Which  function  writes  the  value  of  each  element? 

c)  To  which  activation  record  does  the  element  belong? 

E x e r c i se  7.2.5  :  In  a  language  t h at  passes  parameters  by  reference,  there  is  a 
function  f(x,y) 

t h at  does  the  following: 

x = x + l ; y =y 

+  2; 

r e t u rn  x+y; 

If  a  is  assigned  the  value  3,  and  then  / ( a, a)  is  called,  what  is  returned? 

E x e r c i se  7 . 2 . 6:  T he  C  function  /  is  defined  by: 

i nt  f ( i nt  x,  *py,  **ppz)  { 

**ppz  +=  1;  *py  + = 2;  x  +=  3;  r e t u rn  x+y+z; 

} 

Variable  a  is  a  pointer  to  6;  variable  6  is  a  pointer  to  c,  and  c  is  an  integer 
currently  with  value  4.  If we  call  / ( c, 6, a),  what  is  returned? 

7.3  Access  to  Nonlocal  Data  on  the  Stack 

In  this  section,  we  consider  how  procedures  access  their  data.  Especially  im 
portant  is  t he  mechanism  for  finding  d a ta  used  within  a  procedure  p  but  t h at 
does  not  belong  to  p.  Access  becomes  more  complicated  in  languages  where 
procedures  can  be  declared  inside  other  procedures.  We  therefore  begin  with 
the  simple  case  of C  functions,  and  then  introduce  a  language,  ML,  t h at  permits 
both  nested  function  declarations  and  functions  as  "first-class  objects;"  t h at  is, 
functions  can  take  functions  as  arguments  and  return  functions  as  values.  This 
capability  can  be  supported  by  modifying  the  implementation  of  the  run-time 
stack,  and  we  shall  consider  several  options  for  modifying  the  stack  frames  of 
Section  7.2. 

442 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

7.3.1  Data  Access  Without  Nested  Procedures 

In  the  C  family  of  languages,  all  variables  are  defined  either  within  a  single 
function  or  outside  any  function  ("globally").  Most  importantly,  it  is  impossible 
to  declare  one  procedure  whose  scope  is  entirely  within  another  procedure. 
Rather,  a  global  variable  v  has  a  scope  consisting  of all  the  functions  t h at  follow 
the  declaration  of  v,  except  where  there  is  a  local  definition  of  the  identifier  v. 
Variables  declared  within  a  function  have  a  scope  consisting  of  t h at  function 
only,  or  part  of it,  if the  function  has  nested  blocks,  as  discussed  in  Section  1.6.3. 
For  languages  t h at  do  not  allow  nested  procedure  declarations,  allocation  of 

storage  for  variables  and  access  to  those  variables  is  simple: 

1.  Global  variables  are  allocated  static  storage.  T he  locations  of  these  vari 
ables  remain  fixed  and  are  known  at  compile  time.  So  to  access  any 
variable  t h at  is  not  local  to  the  currently  executing  procedure,  we  simply 
use  the  statically  determined  address. 

2.  Any  other  name  must  be  local  to  the  activation  at  t he  top  of  the  stack. 
We  may  access  these  variables  through  the  topsp  pointer  of  the  stack. 

An  important  benefit  of  static  allocation  for  globals  is  t h at  declared  proce 
dures  may  be  passed  as  parameters  or  returned  as  results  (in  C,  a  pointer  to 
the  function  is  passed),  with  no  substantial  change  in  the  data-access  strategy. 
W i th  the  C  static-scoping  rule,  and  without  nested  procedures,  any  name  non 
local  to  one  procedure  is  nonlocal  to  all  procedures,  regardless  of  how  they  are 
activated.  Similarly,  if  a  procedure  is  returned  as  a  result,  then  any  nonlocal 
name  refers  to  the  storage  statically  allocated  for  it. 

7.3.2 

Issues  With  Nested  Procedures 

Access  becomes  far  more  complicated  when  a  language  allows  procedure  dec 
larations  to  be  nested  and  also  uses  t he  normal  static  scoping  rule;  t h at  is,  a 
procedure  can  access  variables  of  the  procedures  whose  declarations  surround 
its  own  declaration,  following  the  nested  scoping  rule  described  for  blocks  in 
Section  1.6.3.  T he  reason  is  t h at  knowing  at  compile  time  t h at  t he  declaration 
of  p  is  immediately  nested  within  q  does  not  tell  us  t he  relative  positions  of 
their  activation  records  at  run  time.  In  fact,  since  either  p  or  q  or  both  may  be 
recursive,  there  may  be  several  activation  records  of p  a n d / or  q  on  the  stack. 

Finding  t he  declaration  t h at  applies  to  a  nonlocal  name  x  in  a  nested  pro 
cedure  p  is  a  static  decision;  it  can  be  done  by  an  extension  of  the  static-scope 
rule  for  blocks.  Suppose  x  is  declared  in  the  enclosing  procedure  q.  Finding 
the  relevant  activation  of  q  from  an  activation  of p  is  a  dynamic  decision;  it  re 
quires  additional  run-time  information  about  activations.  One  possible  solution 
to  this  problem  is  to  use  "access  links,"  which  we  introduce  in  Section  7.3.5. 

7.3. 

ACCESS  TO  NONLOCAL  DATA  ON  THE  STACK 

443 

7.3.3  A  Language  With  Nested  Procedure  Declarations 

T he  C  family  of  languages,  and  many  other  familiar  languages  do  not  support 
nested  procedures,  so  we  introduce  one  t h at  does.  The  history  of  nested  pro 
cedures  in  languages  is  long.  Algol  60,  an  ancestor  of  C,  had  this  capability, 
as  did  its  descendant  Pascal,  a  once-popular  teaching  language.  Of  the  later 
languages  with  nested  procedures,  one  of  the  most  influential  is  ML,  and  it 
is  this  language  whose  syntax  and  semantics  we  shall  borrow  (see  the  box  on 
"More  about  ML"  for  some  of  the  interesting  features  of  ML): 

•  ML  is  a  functional  language,  meaning  t h at  variables,  once  declared  and 
initialized,  are  not  changed.  There  are  only  a  few  exceptions,  such  as  t he 
array,  whose  elements  can  be  changed  by  special  function  calls. 

•  Variables  are  defined,  and  have  their  unchangeable  values  initialized,  by 

a  statement  of  t he  form: 

v al  (name)  =  (expression) 

•  Functions  are  defined  using  the  syntax: 

fun  (name)  (  (arguments)  )  =  (body) 

•  For  function  bodies  we  shall  use  let-statements  of  the  form: 

l et  (list  of  definitions)  in  (statements)  end 

The  definitions  are  normally  v al  or  fun  statements.  T he  scope  of  each 
such  definition  consists  of all  following  definitions,  up  to  t he  i n,  and  all  t he 
statements  up  to  the  end.  Most  importantly,  function  definitions  can  be 
nested.  For  example,  the  body  of  a  function  p  can  contain  a  let-statement 
t h at  includes  the  definition  of  another  (nested)  function  q.  Similarly,  q 
can  have  function  definitions  within  its  own  body,  leading  to  arbitrarily 
deep  nesting  of  functions. 

7.3.4  Nesting  Depth 

Let  us  give  nesting  depth  1  to  procedures  t h at  are  not  nested  within  any  other 
procedure.  For  example,  all  C  functions  are  at  nesting  depth  1.  However,  if  a 
procedure  p  is  defined  immediately  within  a  procedure  at  nesting  depth  i,  then 
give  p  the  nesting  depth  i  + 

E x a m p le  7 . 5:  Figure  7.10  contains  a  sketch  in  ML  of  our  running  quicksort 
example.  The  only  function  at  nesting  depth  1  is  the  outermost  function,  sort, 
which  reads  an  array  a  of  9  integers  and  sorts  t h em  using  t he  quicksort  algo 
rithm.  Defined  within  sort,  at  line  (2),  is  the  array  a  itself.  Notice  t he  form 

444 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

More  About  ML 

In  addition  to  being  almost  purely  functional,  ML  presents  a  number  of 
other  surprises  to  the  programmer  who  is  used  to  C  and  its  family. 

•  ML  supports  higher-order  functions.  T h at  is,  a  function  can  take 
functions  as  arguments,  and  can  construct  and  return  other  func 
tions.  Those  functions,  in  t u r n,  can  take  functions  as  arguments,  to 
any  level. 

•  ML  has  essentially  no  iteration,  as  in  C's  for-  and  while-statements, 
for  instance.  Rather,  the  effect  of  iteration  is  achieved  by  recur 
sion.  This  approach  is  essential  in  a  functional  language,  since 
we  cannot  change 
in 
" f o r ( i = 0;  i < 1 0;  i + + )"  of  C.  Instead,  ML  would  make  i  a  function 
argument,  and  the  function  would  call  itself with  progressively  higher 
values  of  i  until  t he  limit  was  reached. 

iteration  variable 

the  value  of  an 

like 

i 

•  ML  supports  lists  and  labeled  tree  structures  as  primitive  d a ta types. 

•  ML  does  not  require  declaration  of variable  types.  Rather,  it  deduces 
types  at  compile  time,  and  treats  it  as  an  error  if  it  cannot.  For 
example,  v al  x  =  1  evidently  makes  x  have  integer  type,  and  if  we 
also  see  v al  y  =  2*x,  then  we  know  y  is  also  an  integer. 

of  the  ML  declaration.  The  first  argument  of  a r r ay  says  we  want  t he  array 
to  have  11  elements;  all  ML  arrays  are  indexed  by  integers  starting  with  0,  so 
this  array  is  quite  similar  to  the  C  array  a  from  Fig.  7.2.  T he  second  argument 
of  a r r ay  says  t h at  initially,  all  elements  of  the  array  a  hold  t he  value  0.  This 
choice  of  initial  value  lets  the  ML  compiler  deduce  t h at  a  is  an  integer  array, 
since  0  is  an  integer,  so  we  never  have  to  declare  a  type  for  a. 

Also  declared  within  sort  are  several  functions: 

readArray,  exchange,  and 
quicksort.  On  lines  (4)  and  (6)  we  suggest  t h at  readArray  and  exchange  each 
access  the  array  a.  Note  t h at  in  ML,  array  accesses  can  violate  t he  functional 
n a t u re  of  the  language,  and  b o th  these  functions  actually  change  values  of  a's 
elements,  as  in  t he  C  version  of quicksort.  Since  each  of these  three  functions  is 
defined  immediately  within  a  function  at  nesting  depth  1,  their  nesting  depths 
are  all  2. 

Lines  (7)  through  (11)  show  some  of  the  detail  of  quicksort.  Local  value  v, 
the  pivot  for  the  partition,  is  declared  at  line  (8).  Function  partition  is  defined 
at  line  (9). 
In  line  (10)  we  suggest  t h at  partition  accesses  both  the  array  a 
and  the  pivot  value  v,  and  also  calls  the  function  exchange.  Since  p a r t i t i on  is 
defined  immediately  within  a  function  at  nesting  depth  2,  it  is  at  depth  3.  Line 

7.3. 

ACCESS  TO  NONLOCAL  DATA  ON  THE  STACK 

445 

1)  fun  s o r t ( i n p u t F i l e,  o u t p u t F i l e)  = 

l et 

2) 
3) 
4) 
5) 
6) 
7) 

8) 
9) 
10) 

11) 

12) 

v al  a  =  a r r a y ( 1 1 , 0 ); 
fun  r e a d A r r a y ( i n p u t F i l e)  =  ••• 

; 

• • •  a  • • •  ; 

fun  e x c h a n g e d , j)  = 
a 
fun  q u i c k s o r t ( m , n)  = 

. .. 

. .. 

; 

l et 

in 

end 

v al  v  =  • • • 
fun  p a r t i t i o n ( y , z)  = 

; 

• • •  a  • • •  v  • ••  e x c h a n ge  • • • 

•••  a  •••  v  •••  p a r t i t i on  •••  q u i c k s o rt 

in 

end; 

• • •  a  • • •  r e a d A r r ay  • • •  q u i c k s o rt  • • • 

Figure  7.10:  A  version  of  quicksort,  in  ML  style,  using  nested  functions 

(11)  suggests  t h at  quicksort  accesses  variables  a  and  v,  the  function  partition, 
and  itself  recursively. 

Line  (12)  suggests  t h at  the  outer  function  sort  accesses  a  and  calls  the  two 
• 

procedures  readArray  and  quicksort. 

7.3.5  Access  Links 

A  direct  implementation  of  the  normal  static  scope  rule  for  nested  functions  is 
obtained  by  adding  a  pointer  called  t he  access  link  to  each  activation  record.  If 
procedure  p  is  nested  immediately  within  procedure  q  in  t he  source  code,  then 
t he  access  link  in  any  activation  of p  points  to  t he  most  recent  activation  of  q. 
Note  t h at  the  nesting  depth  of q  must  be  exactly  one  less  t h an  the  nesting  depth 
of p.  Access  links  form  a  chain  from  the  activation  record  at  the  top  of the  stack 
to  a  sequence  of  activations  at  progressively  lower  nesting  depths.  Along  this 
chain  are  all  the  activations  whose  d a ta  and  procedures  are  accessible  to  the 
currently  executing  procedure. 

Suppose  t h at  the  procedure  p  at  the  top  of  the  stack  is  at  nesting  depth  np, 
and  p  needs  to  access  x,  which  is  an  element  defined  within  some  procedure  q 
t h at  surrounds  p  and  has  nesting  depth  nq.  Note  t h at  nq  <  np,  with  equality 
only  if  p  and  q  are  the  same  procedure.  To  find  x,  we  start  at  t he  activation 
record  for  p  at  the  top  of  the  stack  and  follow  the  access  link  np  —  nq  times, 
from  activation  record  to  activation  record.  Finally,  we  wind  up  at  an  activation 
record  for  q,  and  it  will  always  be  the  most  recent  (highest)  activation  record 

446 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

for  q  t h at  currently  appears  on  the  stack.  This  activation  record  contains  the 
element  x  t h at  we  want.  Since  the  compiler  knows  t he  layout  of  activation 
records,  x  will  be  found  at  some  fixed  offset  from  the  position  in  g's  activation 
record  t h at  we  can  reach  by  following  the  last  access  link. 

E x a m p le  7 . 6:  Figure  7.11  shows  a  sequence  of  stacks  t h at  might  result  from 
execution  of  the  function  sort  of  Fig.  7.10.  As  before,  we  represent  function 
names  by  their  first  letters,  and  we  show  some  of the  d a ta  t h at  might  appear  in 
the  various  activation  records,  as  well  as  t he  access  link  for  each  activation.  In 
Fig.  7.11(a),  we  see  the  situation  after  sort  has  called  readArray  to  load  input 
into  the  array  a  and  then  called  quicksort(l,  9)  to  sort  t he  array.  The  access  link 
from  quicksort(l,  9)  points  to  t he  activation  record  for  sort,  not  because  sort 
called  quicksort  but  because  sort is  the  most  closely  nested  function  surrounding 
quicksort  in  the  program  of  Fig.  7.10. 

access 

link 

access 

link 

access 

link 

a 

a 

a 

__g(i_,9)_ 

access 

link 

access 

link 

access 

link 

(a) 

9(1,3) 

9(1,3) 

access 

link 

access 

link 

v 

(b) 

v 

P ( l , 3) 

access 

link 

(c) 

Figure  7.11:  Access  links  for  finding  nonlocal  d a ta 

In  successive  steps  of  Fig.  7.11  we  see  a  recursive  call  to  quicksort(l, 3), 
followed  by  a  call  to  partition,  which  calls  exchange.  Notice  t h at  quicksort(l,  3)'s 
access  link  points  to  sort,  for  t he  same  reason  t h at  quicksort(l,  9)'s  does. 

In  Fig.  7.11(d),  the  access  link  for  exchange  bypasses  the  activation  records 
for  quicksort  and  partition,  since  exchange  is  nested  immediately  within  sort. 
T h at  arrangement  is  fine,  since  exchange  needs  to  access  only  t he  array  a,  and 
• 
t he  two  elements  it  must  swap  are  indicated  by  its  own  parameters  i  and  j. 

7.3. 

ACCESS  TO  NONLOCAL  DATA  ON  THE  STACK 

447 

7.3.6  Manipulating  Access  Links 

How  are  access  links  determined?  T he  simple  case  occurs  when  a  procedure 
call  is  to  a particular  procedure  whose  n a me  is  given  explicitly  in  the  procedure 
call.  T he  harder  case  is  when  t he  call  is  to  a  procedure-parameter;  in  t h at 
case,  t he  particular  procedure  being  called  is  not  known  until  run  time,  and  t he 
nesting  depth  of  the  called  procedure  may  differ  in  different  executions  of  t he 
call.  Thus,  let  us  first  consider  what  should  happen  when  a  procedure  q  calls 
procedure  p,  explicitly.  There  are  three  cases: 

1.  Procedure  p  is  at  a  higher  nesting  depth  t h an  q.  T h en  p  must  be  defined 
immediately  within  q,  or  the  call  by  q  would  not  be  at  a  position  t h at 
is  within  the  scope  of t he  procedure  name  p.  Thus,  t he  nesting  depth  of 
p  is  exactly  one  greater  t h an  t h at  of  q,  and  t he  access  link  from  p  must 
lead  to  q.  It  is  a  simple  m a t t er  for  t he  calling  sequence  to  include  a  step 
t h at  places  in  t he  access  link  for  p  a  pointer  to  the  activation  record  of  q. 
Examples  include  the  call  of  quicksort  by  sort  to  set  up  Fig.  7.11(a),  and 
t he  call  of  partition  by  quicksort  to  create  Fig.  7.11(c). 

2.  T he  call  is  recursive,  t h at  is,  p  —  q?  Then  the  access  link  for the  new  acti 
vation  record  is  the  same  as  t h at  of the  activation  record  below  it.  An  ex 
ample  is  the  call  of  quicksort(l,  3)  by  quicksort(l,  9)  to  set  up  Fig.  7.11(b). 

3.  The  nesting  depth  np  of  p  is  less  t h an  the  nesting  depth  nq  of  q. 

In 
order  for  the  call  within  q  to  be  in  the  scope  of  n a me  p,  procedure  q 
must  be  nested  within  some  procedure  r,  while  p  is  a  procedure  defined 
immediately  within  r.  T he  top  activation  record  for  r  can  therefore  be 
found  by  following  t he  chain  of  access  links,  starting  in  the  activation 
record  for  q,  for  nq  —  np  +  1  hops.  Then,  t he  access  link  for  p  must  go  to 
this  activation  of  r. 

E x a m p le  7 . 7:  For  an  example  of case  (3),  notice  how  we-go  from  Fig.  7.11(c) 
to  Fig.  7.11(d).  The  nesting  depth  2  of  the  called  function  exchange  is  one 
less  t h an  the  depth  3  of  the  calling  function  partition.  Thus,  we  start  at  the 
activation  record  for  partition  and  follow  3 -2  +  1  =  2  access  links,  which  takes 
us  from  partition's  activation  record  to  t h at  of  quicksort(l,S) 
to  t h at  of  sort. 
The  access  link  for  exchange  therefore  goes  to  the  activation  record  for  sort,  as 
we  see  in  Fig.  7.11(d). 

An  equivalent  way  to  discover  this  access  link  is  simply  to  follow  access  links 

for  nq- np  hops,  and  copy  t he  access  link  found  in  t h at  record.  In  our  example, 
we  would  go  one  hop  to  t he  activation  record  for  quicksort(l,  3)  and  copy  its 
access  link  to  sort.  Notice  t h at  this  access  link  is  correct  for  exchange,  even 
though  exchange  is  not  in  the  scope  of  quicksort,  these  being  sibling  functions 
nested  within  sort. 

• 

2ML  allows  mutually  recursive  functions,  which  would  be  handled  the  same  way. 

448 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

7.3.7  Access  Links  for  Procedure  Parameters 

When  a  procedure p  is  passed  to  another  procedure  q  as  a  parameter,  and  q  then 
calls  its  parameter  (and  therefore  calls  p  in  this  activation  of  q),  it  is  possible 
t h at  q  does  not  know  t he  context  in  which  p  appears  in  t he  program.  If so,  it  is 
impossible  for  q  to  know  how  to  set  t he  access  link  for  p.  T he  solution  to  this 
problem  is  as  follows:  when  procedures  are  used  as  parameters,  the  caller  needs 
to  pass,  along  with  the  name  of the  procedure-parameter,  the  proper  access  link 
for  t h at  parameter. 

T he  caller  always  knows  t he  link,  since  if p  is  passed  by  procedure  r  as  an 
actual  parameter,  then  p  must  be  a  name  accessible  to  r,  and  therefore,  r  can 
determine  the  access  link  for  p  exactly  as  if  p  were  being  called  by  r  directly. 
T h at  is,  we  use  t he  rules  for  constructing  access  links  given  in  Section  7.3.6. 

E x a m p le  7 . 8: 
In  Fig.  7.12  we  see  a  sketch  of  an  ML  function  a  t h at  has 
functions  b  and  c  nested  within  it.  Function  b  has  a  function-valued  parameter 
/,  which  it  calls.  Function  c  defines  within  it  a  function  d,  and  c  then  calls  b 
with  actual  parameter  d. 

fun  a ( x)  = 
l et 

fun  b ( f)  = 
...  f  ... 
fun  c ( y)  = 
l et 

. 

fun  d ( z)  =  • • • 

. .. 

b(d) 

. .. 

in 

end 

in 

end; 

. .. 

C( i) 

. .. 

Figure  7.12:  Sketch  of  ML  program  t h at  uses  function-parameters 

Let  us  trace  what  happens  when  a  is  executed.  First,  a  calls  c,  so  we  place 
an  activation  record  for  c  above  t h at  for  a  on  t he  stack.  T he  access  link  for 
c  points  to  the  record  for  a,  since  c  is  defined  immediately  within  a.  T h en  c 
calls  b(d).  The  calling  sequence  sets  up  an  activation  record  for  b,  as  shown  in 
Fig.  7.13(a). 

Within  this  activation  record  is  the  actual  parameter  d  and  its  access  link, 
which  together  form  t he  value  of  formal  parameter  /  in  the  activation  record 
for  b.  Notice  t h at  c  knows  about  d,  since  d  is  defined  within  c,  and  therefore 
c  passes  a  pointer  to  its  own  activation  record  as  t he  access  link.  No  m a t t er 
where  d  was  defined,  if  c  is  in  t he  scope  of t h at  definition,  then  one  of the  three 
rules  of  Section  7.3.6  must  apply,  and  c  can  provide  t he  link. 

7.3. 

ACCESS  TO  NONLOCAL  DATA  ON  THE  STACK 

449 

Figure  7.13:  Actual  parameters  carry  their  access  link  with  them 

(b) 

Now,  let  us  look  at  w h at  b  does.  We  know  t h at  at  some  point,  it  uses 
its  parameter  /,  which  has  the  effect  of  calling  d.  An  activation  record  for  d 
appears  on  the  stack,  as  shown  in  Fig.  7.13(b).  The  proper  access  link  to  place 
in  this  activation  record  is  found  in  the  value  for  parameter  /;  the  link  is  to 
t he  activation  record  for  c,  since  c  immediately  surrounds  t he  definition  of  d. 
Notice  t h at  b  is  capable  of  setting  up  t he  proper  link,  even  though  b  is  not  in 
the  scope  of  c's  definition. 

• 

7.3.8  Displays 

One  problem  with  the  access-link  approach  to  nonlocal  d a ta  is  t h at  if t he  nesting 
depth  gets  large,  we  may  have  to  follow  long  chains  of  links  to  reach  t he  d a ta 
we  need.  A  more  efficient  implementation  uses  an  auxiliary  array  d,  called  the 
display,  which  consists  of  one  pointer  for  each  nesting  depth.  We  arrange  t h a t, 
at  all  times,  d[i]  is  a  pointer  to  the  highest  activation  record  on  the  stack  for 
any  procedure  at  nesting  depth  i.  Examples  of a  display  are  shown  in  Fig.  7.14. 
For  instance,  in  Fig.  7.14(d),  we  see  the  display  d,  with  d[l]  holding  a  pointer 
to  t he  activation  record  for  s o r t,  t he  highest  (and  only)  activation  record  for  a 
function  at  nesting  depth  1.  Also,  d[2]  holds  a  pointer  to  t he  activation  record 
for  exchange,  the  highest  record  at  depth  2,  and  d[3]  points  to  partition,  t he 
highest  record  at  depth  3. 

T he  advantage  of  using  a  display  is  t h at  if  procedure  p  is  executing,  and 
it  needs  to  access  element  x  belonging  to  some  procedure  q,  we  need  to  look 
only  in  d[i],  where  i  is  the  nesting  depth  of  q;  we  follow  the  pointer  d[i]  to  t he 
activation  record  for  q,  wherein  x  is  found  at  a  known  offset.  T he  compiler 
knows  what  i  is,  so  it  can  generate  code  to  access  x  using  d[i]  and  t he  offset  of 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

.A(k9L. 
saved d[2] 

saved d[2] 

saved d[2] 

sawed  d[3] 

Figure  7.14:  Maintaining  the  display 

7.3. 

ACCESS  TO  NONLOCAL  DATA  ON  THE  STACK 

451 

x  from  t he  t op  of  t he  activation  record  for  q.  Thus,  the  code  never  needs  to 
follow  a  long  chain  of  access  links. 

In  order  to  maintain  t he  display  correctly,  we  need  to  save  previous  values 
of display  entries  in  new  activation  records.  If procedure p  at  depth  np  is  called, 
and  its  activation  record  is  not  the  first  on  the  stack  for  a  procedure  at  depth 
np,  then  the  activation  record  for  p  needs  to  hold  the  previous  value  of  d[np], 
while  d[np]  itself  is  set  to  point  to  this  activation  of p.  When  p  returns,  and  its 
activation  record  is  removed  from  the  stack,  we  restore  d[np]  to  have  its  value 
prior  to  the  call  of p. 

E x a m p le  7 . 9:  Several  steps  of  manipulating  the  display  are  illustrated  in 
Fig.  7.14.  In  Fig.  7.14(a),  sort  at  depth  1  has  called  quicksort(l,  9)  at  depth  2. 
T he  activation  record  for  quicksort  has  a  place  to  store  the  old  value  of  d[2], 
indicated  as  saved d[2],  although  in  this  case  since  there  was  no  prior  activation 
record  at  depth  2,  this  pointer  is  null. 

In  Fig.  7.14(b),  quicksort(l,  9)  calls  quicksort(l,  3). 

Since  the  activation 
records  for  b o th  calls  are  at  depth  2,  we  must  store  the  pointer  to  quicksort(l,  9), 
which  was  in  d[2],  in  the  record  for  quicksort(l,  3).  Then,  d[2]  is  made  to  point 
to  quicksort(l,  3). 

Next,  partition  is  called.  This  function  is  at  depth  3,  so  we  use  the  slot  d[3] 
in  the  display  for  the  first  time,  and  make  it  point  to  the  activation  record  for 
partition.  T he  record  for  partition  has  a  slot  for  a  former  value  of  d[3],  but  in 
this  case  there  is  none,  so  the  pointer  remains  null.  The  display  and  stack  at 
this  time  are  shown  in  Fig.  7.14(c). 

Then,  partition  calls  exchange.  T h at  function  is  at  depth  2,  so  its  activa 
tion  record  stores  t he  old  pointer  d[2],  which  goes  to  the  activation  record  for 
quicksort(l,  3).  Notice  t h at  the  display  pointers  "cross";  t h at  is,  d[3]  points 
further  down  the  stack  t h an  d[2]  does.  However,  t h at  is  a  proper  situation; 
exchange  can  only  access  its  own  d a ta  and  t h at  of  sort,  via  d[l]. 

• 

7.3.9  Exercises  for  Section  7.3 

E x e r c i se  7 . 3 . 1:  In  Fig.  7.15  is  a  ML  function  main  t h at  computes  Fibonacci 
numbers  in  a  nonstandard  way.  Function  f ibO  will  compute  the  n th  Fibonacci 
number  for  any  n  >  0.  Nested  within  in  is  f i b l,  which  computes  the  n th 
Fibonacci  number  on  the  assumption  n  >  2,  and  nested  within  f i bl  is  f i b 2, 
which  assumes  n  >  4.  Note  t h at  neither  f i bl  nor  f i b2  need  to  check  for  the 
basis  cases.  Show  the  stack  of activation  records  t h at  result  from  a  call  to  main, 
up  until  the  time  t h at  the  first  call  (to  f i b O ( l ))  is  about  to  return.  Show  t he 
access  link  in  each  of  t he  activation  records  on  the  stack. 

E x e r c i se  7 . 3 . 2:  Suppose  t h at  we  implement  the  functions  of  Fig.  7.15  using 
a  display.  Show  the  display  at  the  moment  the  first  call  to  f i b O ( l)  is  about  to 
return.  Also,  indicate  the  saved  display  entry  in  each  of  t he  activation  records 
on  t he  stack  at  t h at  time. 

452 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

fun  main 

()  { 

l et 

fun  f i b O ( n)  = 

l et 

fun  f i b l ( n)  = 

l et 

in 

end 

fun  f i b 2 ( n)  =  f i b l ( n - l)  +  f i b l ( n - 2) 

if  n  >=  4  t h en  f i b 2 ( n) 
e l se  f i b O ( n - l)  +  f i b 0 ( n - 2) 

if  n  >=  2  t h en  f i b l ( n) 
e l se  1 

in 

end 

in 

end; 

f i b 0 ( 4) 

Figure  7.15:  Nested  functions  computing  Fibonacci  numbers 

7.4  Heap  Management 

T he  heap  is  the  portion  of the  store  t h at  is  used  for  d a ta t h at  lives  indefinitely,  or 
until  t he  program  explicitly  deletes  it.  While  local  variables  typically  become 
inaccessible  when  their  procedures  end,  many  languages  enable  us  to  create 
objects  or  other  d a ta  whose  existence  is  not  tied  to  the  procedure  activation 
t h at  creates  them.  For  example,  b o th  C ++  and  Java  give  t he  programmer  new 
to  create  objects  t h at  may  be  passed  —  or  pointers  to  t h em  may  be  passed  — 
from  procedure  to  procedure,  so  they  continue  to  exist  long  after  the  procedure 
t h at  created  t h em  is  gone.  Such  objects  are  stored  on  a  heap. 

In  this  section,  we  discuss  the  memory  manager,  the  subsystem  t h at  allo 
cates  and  deallocates  space  within  t he  heap;  it  serves  as  an  interface  between 
application  programs  and  the  operating  system.  For  languages  like  C  or  C ++ 
t h at  deallocate  chunks  of  storage  manually  (i.e.,  by  explicit  statements  of  t he 
program,  such  as  f r ee  or  d e l e t e ),  t he  memory  manager  is  also  responsible  for 
implementing  deallocation. 

In  Section  7.5,  we  discuss  garbage  collection,  which  is  t he  process  of  finding 

spaces  within  the  heap  t h at  are  no  longer  used  by  t he  program  and  can  therefore 
be  reallocated  to  house  other  d a ta  items.  For  languages  like  Java,  it  is  t he 
garbage  collector  t h at  deallocates  memory.  When  it  is  required,  t he  garbage 
collector  is  an  important  subsystem  of  t he  memory  manager. 

7.4. 

HEAP  MANAGEMENT 

453 

7.4.1  The  Memory  Manager 

The  memory  manager  keeps  track  of  all  the  free  space  in  heap  storage  at  all 
times.  It  performs  two  basic  functions: 

•  Allocation.  W h en  a  program  requests  memory  for  a  variable  or  object,3 
t he  memory  manager  produces  a  chunk  of  contiguous  heap  memory  of 
t he  requested  size.  If  possible,  it  satisfies  an  allocation  request  using  free 
space  in  t he  heap;  if  no  chunk  of  t he  needed  size  is  available,  it  seeks  to 
increase  t he  heap  storage  space  by  getting  consecutive  bytes  of  virtual 
memory  from  the  operating  system. 
If  space  is  exhausted,  t he  memory 
manager  passes  t h at  information  back  to  the  application  program. 

•  Deallocation.  T he  memory  manager  returns  deallocated  space  to  the  pool 
of free  space,  so  it  can  reuse  the  space  to  satisfy  other  allocation  requests. 
Memory  managers  typically  do  not  return  memory  to  the  operating  sys 
tem,  even  if  t he  program's  heap  usage  drops. 

Memory  management  would  be  simpler  if  (a)  all  allocation  requests  were 
for  chunks  of  the  same  size,  and  (b)  storage  were  released  predictably,  say, 
first-allocated  first-deallocated.  There  are  some  languages,  such  as  Lisp,  for 
which  condition  (a)  holds;  pure  Lisp  uses  only  one  d a ta  element  —  a  two-
pointer  cell  —  from  which  all  d a ta  structures  are  built.  Condition  (b)  also 
holds  in  some  situations,  the  most  common  being  d a ta  t h at  can  be  allocated 
on  t he  run-time  stack.  However,  in  most  languages,  neither  (a)  nor  (b)  holds 
in  general.  Rather,  d a ta  elements  of  different  sizes  are  allocated,  and  there  is 
no  good  way  to  predict  t he  lifetimes  of  all  allocated  objects. 

Thus,  the  memory  manager  must  be  prepared  to  service,  in  any  order,  allo 
cation  and  deallocation  requests  of  any  size,  ranging  from  one  byte  to  as  large 
as  the  program's  entire  address  space. 

Here  are  t he  properties  we  desire  of  memory  managers: 

•  Space  Efficiency.  A  memory  manager  should  minimize  the  total  heap 
space  needed  by  a  program.  Doing  so  allows  larger  programs  to  run  in 
a  fixed  virtual  address  space.  Space  efficiency  is  achieved  by  minimizing 
"fragmentation,"  discussed  in  Section  7.4.4. 

•  Program  Efficiency.  A  memory  manager  should  make  good  use  of  t he 
memory  subsystem  to  allow  programs  to  run  faster.  As  we  shall  see  in 
Section  7.4.2,  the  time  taken  to  execute  an  instruction  can  vary  widely 
depending  on  where  objects  are  placed  in  memory.  Fortunately,  programs 
tend  to  exhibit  "locality,"  a  phenomenon  discussed  in  Section  7.4.3,  which 
refers  to  t he  nonrandom  clustered  way  in  which  typical  programs  access 
memory.  By  attention  to  the  placement  of objects  in  memory,  the  memory 
manager  can  make  better  use  of  space  and,  hopefully,  make  the  program 
run  faster. 

3In  what  follows,  we  shall  refer  to  things  requiring  memory  space  as  "objects,"  even  if they 

are  not  true  objects  in  the  "object-oriented  programming"  sense. 

454 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

•  Low  Overhead.  Because  memory  allocations  and  deallocations  are  fre 
quent  operations  in  many  programs,  it  is  important  t h at  these  operations 
be  as  efficient  as  possible.  T h at  is,  we  wish  to  minimize  the  overhead  — 
the  fraction  of  execution  time  spent  performing  allocation  and  dealloca 
tion.  Notice  t h at  the  cost  of  allocations  is  dominated  by  small  requests; 
the  overhead  of  managing  large  objects  is  less  important,  because  it  usu 
ally  can  be  amortized  over  a  larger  amount  of  computation. 

7.4.2  The  Memory  Hierarchy  of  a  Computer 

Memory  management  and  compiler  optimization  must  be  done  with  an  aware 
ness  of  how  memory  behaves.  Modern  machines  are  designed  so  t h at  program 
mers  can  write  correct  programs  without  concerning  themselves  with  t he  details 
of  the  memory  subsystem.  However,  the  efficiency  of  a  program  is  determined 
not  just  by  the  number  of  instructions  executed,  but  also  by  how  long  it  takes 
to  execute  each  of these  instructions.  The  time  taken  to  execute  an  instruction 
can  vary  significantly,  since  the  time  taken  to  access  different  parts  of  memory 
can  vary  from  nanoseconds  to  milliseconds.  Data-intensive  programs  can  there 
fore  benefit  significantly  from  optimizations  t h at  make  good  use  of t he  memory 
subsystem.  As  we  shall  see  in  Section  7.4.3,  they  can  take  advantage  of  t he 
phenomenon  of  "locality"  —  the  nonrandom  behavior  of  typical  programs. 

T he  large  variance  in  memory  access  times  is  due  to  the  fundamental  limi 
tation  in  hardware  technology;  we  can  build  small  and  fast  storage,  or  large  and 
slow  storage,  but  not  storage  t h at  is  both  large  and  fast.  It  is  simply  impos 
sible  today  to  build  gigabytes  of  storage  with  nanosecond  access  times,  which 
is  how  fast  high-performance  processors  run.  Therefore,  practically  all  modern 
computers  arrange  their  storage  as  a  memory  hierarchy.  A  memory  hierarchy, 
as  shown  in  Fig.  7.16,  consists  of  a  series  of  storage  elements,  with  t he  smaller 
faster  ones  "closer"  to  the  processor,  and  the  larger  slower  ones  further  away. 

Typically,  a  processor  has  a  small  number  of  registers,  whose  contents  are 
under  software  control.  Next,  it  has  one  or  more  levels  of  cache,  usually  made 
out  of  static  RAM,  t h at  are  kilobytes  to  several  megabytes  in  size.  The  next 
level  of  t he  hierarchy  is  the  physical  (main)  memory,  made  out  of  hundreds  of 
megabytes  or  gigabytes  of  dynamic  R A M.  T he  physical  memory  is  then  backed 
up  by  virtual  memory,  which  is  implemented  by  gigabytes  of  disks.  Upon  a 
memory  access,  the  machine  first  looks  for  t he  d a ta  in  t he  closest  (lowest-level) 
storage  and,  if t he  d a ta  is  not  there,  looks  in  t he  next  higher  level,  and  so  on. 

Registers  are  scarce,  so  register  usage  is  tailored  for  the  specific  applications 
and  managed  by  t he  code  t h at  a  compiler  generates.  All  the  other  levels  of  t he 
hierarchy  are  managed  automatically;  in  this  way,  not  only  is  the  programming 
task  simplified,  but  the  same  program  can  work  effectively  across  machines 
with  different  memory  configurations.  W i th  each  memory  access,  the  machine 
searches  each  level  of  the  memory  in  succession,  starting  with  t he  lowest  level, 
until  it  locates  the  data.  Caches  are  managed  exclusively  in  hardware,  in  order 
to  keep  up  with  t he  relatively  fast  RAM  access  times.  Because  disks  are  rela-

7.4. 

HEAP  MANAGEMENT 

455 

Typical  Sizes 

Typical  Access  Times 

>  2GB 

Virtual  Memory  (Disk) 

3  -  15  ms 

256MB  -  2GB 

Physical  Memory 

100  -  150  ns 

128KB  -  4MB 

2nd-Level  Cache 

40  -  60  ns 

16  -  64KB 

lst-Level  Cache 

5  -  10  ns 

32  Words 

Registers  (Processor) 

1  ns 

Figure  7.16:  Typical  Memory  Hierarchy  Configurations 

tively  slow,  the  virtual  memory  is  managed  by  the  operating  system,  with  the 
assistance  of  a  hardware  structure  known  as  the  "translation  lookaside  buffer." 
D a ta  is  transferred  as  blocks  of  contiguous  storage.  To  amortize  t he  cost 
of  access,  larger  blocks  are  used  with  the  slower  levels  of  the  hierarchy.  Be 
tween  main  memory  and  cache,  d a ta  is  transferred  in  blocks  known  as  cache 
lines,  which  are  typically  from  32  to  256  bytes  long.  Between  virtual  memory 
(disk)  and  main  memory,  d a ta  is  transferred  in  blocks  known  as  pages,  typically 
between  4K  and  64K  bytes  in  size. 

7.4.3  Locality  in  Programs 

Most  programs  exhibit  a  high  degree  of  locality;  t h at  is,  they  spend  most  of 
their  time  executing  a  relatively  small  fraction  of  the  code  and  touching  only 
a  small  fraction  of  the  data.  We  say  t h at  a  program  has  temporal  locality  if 
t he  memory  locations  it  accesses  are  likely  to  be  accessed  again  within  a  short 
period  of  time.  We  say  t h at  a  program  has  spatial  locality  if  memory  locations 
close  to  t he  location  accessed  are  likely  also  to  be  accessed  within  a  short  period 
of  time. 

T he  conventional  wisdom  is  t h at  programs  spend  90%  of their  time  executing 

10%  of  the  code.  Here  is  why: 

•  Programs  often  contain  many  instructions  t h at  are  never  executed.  P r o 
grams  built  with  components  and  libraries  use  only  a  small  fraction  of t he 
provided  functionality.  Also  as  requirements  change  and  programs  evolve, 
legacy  systems  often  contain  many  instructions  t h at  are  no  longer  used. 

456 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

Static  and  Dynamic  RAM 

Most  random-access  memory  is  dynamic,  which  means  t h at  it  is  built  of 
very  simple  electronic  circuits  t h at  lose  their  charge  (and  thus  "forget" 
the  bit  they  were  storing)  in  a  short  time.  These  circuits  need  to  be 
refreshed  —  t h at  is,  their  bits  read  and  rewritten  —  periodically.  On 
the  other  hand,  static  RAM  is  designed  with  a  more  complex  circuit  for 
each  bit,  and  consequently  t he  bit  stored  can  stay  indefinitely,  until  it  is 
changed.  Evidently,  a  chip  can  store  more  bits  if  it  uses  dynamic-RAM 
circuits  t h an  if  it  uses  static-RAM  circuits,  so  we  tend  to  see  large  main 
memories  of t he  dynamic  variety,  while  smaller  memories,  like  caches,  are 
made  from  static  circuits. 

•  Only  a small  fraction  of t he  code  t h at  could  be  invoked  is  actually  executed 
in  a  typical  run  of  t he  program.  For  example,  instructions  to  handle 
illegal  inputs  and  exceptional  cases,  though  critical  to  t he  correctness  of 
t he  program,  are  seldom  invoked  on  any  particular  run. 

•  T he  typical  program  spends  most  of  its  time  executing  innermost  loops 

and  tight  recursive  cycles  in  a  program. 

Locality  allows  us  to  take  advantage  of  the  memory  hierarchy  of  a  modern 
computer,  as  shown  in  Fig.  7.16.  By  placing  t he  most  common  instructions  and 
d a ta  in  the  fast-but-small  storage,  while  leaving  t he  rest  in  t he  slow-but-large 
storage,  we  can  lower t he  average memory-access time  of a  program  significantly. 
It  has  been  found  t h at  many  programs  exhibit  b o th  temporal  and  spatial 
locality  in  how  they  access  b o th  instructions  and  d a t a.  Data-access  p a t t e r n s, 
however,  generally  show  a  greater  variance  t h an  instruction-access  p a t t e r n s. 
Policies  such  as  keeping  the  most  recently  used  d a ta  in  the  fastest  hierarchy 
work  well  for  common  programs  but  may  not  work  well  for  some  data-intensive 
programs  —  ones  t h at  cycle  through  very  large  arrays,  for  example. 

We  often  cannot  tell,  just  from  looking  at  t he  code,  which  sections  of  the 
code  will  be  heavily  used,  especially  for  a  particular  input.  Even  if  we  know 
which  instructions  are  executed  heavily,  t he  fastest  cache  often  is  not  large 
enough  to  hold  all  of  t h em  at  t he  same  time.  We  must  therefore  adjust  t he 
contents  of  t he  fastest  storage  dynamically  and  use  it  to  hold  instructions  t h at 
are  likely  to  be  used  heavily  in  the  near  future. 

O p t i m i z a t i on  U s i ng  t he  M e m o ry  H i e r a r c hy 

T he  policy  of  keeping  the  most  recently  used  instructions  in  t he  cache  tends 
to  work  well;  in  other  words,  the  past  is  generally  a  good  predictor  of  future 
memory  usage.  When  a  new  instruction  is  executed,  there  is  a  high  proba 
bility  t h at  the  next  instruction  also  will  be  executed.  This  phenomenon  is  an 

7.4. 

HEAP  MANAGEMENT 

457 

Cache  Architectures 

How  do  we  know  if  a  cache  line  is  in  a  cache?  It  would  be  too  expensive 
to  check  every  single  line  in  the  cache,  so  it  is  common  practice  to  restrict 
t he  placement  of  a  cache  line  within  t he  cache.  This  restriction  is  known 
as  set  associativity.  A  cache  is  k-way  set  associative  if  a  cache  line  can 
reside  only  in  k  locations.  The  simplest  cache  is  a  1-way  associative  cache, 
also  known  as  a  direct-mapped  cache.  In  a  direct-mapped  cache,  d a ta  with 
memory  address  n  can  be  placed  only  in  cache  address  n  mod  s,  where  s 
is  the  size  of  the  cache.  Similarly,  a  ft-way  set  associative  cache  is  divided 
into  k  sets,  where  a  d a t um  with  address  n  can  be  m a p p ed  only  to  the 
location  n  mod  (s/k)  in  each  set.  Most  instruction  and  d a ta  caches  have 
associativity  between  1  and  8.  W h en  a  cache  line  is  brought  into  the 
cache,  and  all  the  possible  locations  t h at  can  hold  the  line  are  occupied, 
it  is  typical  to  evict  the  line  t h at  has  been  t he  least  recently  used. 

example  of  spatial  locality.  One  effective  technique  to  improve  t he  spatial  lo 
cality  of  instructions  is  to  have  t he  compiler  place  basic  blocks  (sequences  of 
instructions  t h at  are  always  executed  sequentially)  t h at  are  likely  to  follow  each 
other  contiguously  —  on  the  same  page,  or  even  the  same  cache  line,  if  possi 
ble.  Instructions  belonging  to  the  same  loop  or  same  function  also  have  a  high 
probability  of  being  executed  together.4 

We  can  also  improve  the  temporal  and  spatial  locality  of  d a ta  accesses  in 
a  program  by  changing  the  d a ta  layout  or  the  order  of  t he  computation.  For 
example,  programs  t h at  visit  large  amounts  of  d a ta  repeatedly,  each  time  per 
forming  a  small  amount  of  computation,  do  not  perform  well.  It  is  better  if  we 
can  bring  some  d a ta  from  a  slow  level  of  the  memory  hierarchy  to  a  faster  level 
(e.g.,  disk  to  main  memory)  once,  a nd  perform  all  t he  necessary  computations 
on  this  d a ta  while  it  resides  at  the  faster  level.  This  concept  can  be  applied 
recursively  to  reuse  d a ta  in  physical  memory,  in  the  caches  and  in  the  registers. 

7.4.4  Reducing  Fragmentation 

At  t he  beginning  of  program  execution,  the  heap  is  one  contiguous  unit  of  free 
space.  As  t he  program  allocates  and  deallocates  memory,  this  space  is  broken 
up  into  free  and  used  chunks  of memory,  and  t he  free  chunks  need  not  reside  in 
a  contiguous  area  of  t he  heap.  We  refer  to  the  free  chunks  of  memory  as  holes. 
W i th  each  allocation  request,  the  memory  manager  must  place  t he  requested 
chunk  of  memory  into  a  large-enough  hole.  Unless  a  hole  of  exactly  t he  right 
size  is  found,  we  need  to  split  some  hole,  creating  a  yet  smaller  hole. 

4As  a  machine  fetches  a  word  in  memory,  it  is  relatively  inexpensive  to  prefetch  the  next 
several  contiguous  words  of  memory  as  well.  Thus,  a  common  memory-hierarchy  feature  is 
that  a  multiword  block  is  fetched  from  a  level  of  memory  each  time  that  level  is  accessed. 

458 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

W i th  each  deallocation  request,  the  freed  chunks  of memory  are  added  back 
to  the  pool  of free  space.  We  coalesce  contiguous  holes  into  larger  holes,  as  the 
holes  can  only  get  smaller  otherwise.  If  we  are  not  careful,  the  memory  may 
end  up  getting  fragmented,  consisting  of  large  numbers  of  small,  noncontiguous 
holes.  It  is  then  possible  t h at  no  hole  is  large  enough  to  satisfy  a  future  request, 
even  though  there  may  be  sufficient  aggregate  free  space. 

B e s t - F it  a nd  N e x t - F it  O b j e ct  P l a c e m e nt 

We  reduce  fragmentation  by  controlling  how  the  memory  manager  places  new 
objects  in  the  heap.  It  has  been  found  empirically  t h at  a  good  strategy  for  mini 
mizing  fragmentation  for  real-life  programs  is  to  allocate  t he  requested  memory 
in  t he  smallest  available  hole  t h at  is  large  enough.  This  best-fit algorithm  tends 
to  spare  the  large  holes  to  satisfy  subsequent,  larger  requests.  An  alternative, 
called  first-fit,  where  an  object  is  placed  in  the  first  (lowest-address)  hole  in 
which  it  fits,  takes  less  time  to  place  objects,  but  has  been  found  inferior  to 
best-fit  in  overall  performance. 

To  implement  best-fit  placement  more  efficiently,  we  can  separate  free  space 
into  bins,  according  to  their  sizes.  One  practical  idea  is  to  have  many  more  bins 
for  the  smaller  sizes,  because  there  are  usually  many  more  small  objects.  For 
example,  the  Lea  memory  manager,  used  in  the  GNU  C  compiler  g c c,  aligns 
all  chunks  to  8-byte  boundaries.  There  is  a  bin  for  every  multiple  of  8-byte 
chunks  from  16  bytes  to  512  bytes.  Larger-sized  bins  are  logarithmically  spaced 
(i.e.,  t he  minimum  size  for  each  bin  is  twice  t h at  of  the  previous  bin),  and 
within  each  of  these  bins  the  chunks  are  ordered  by  their  size.  There  is  always 
a  chunk  of  free  space  t h at  can  be  extended  by  requesting  more  pages  from  t he 
operating  system.  Called  the  wilderness  chunk,  this  chunk  is  treated  by  Lea  as 
the  largest-sized  bin  because  of  its  extensibility. 

Binning  makes  it  easy  to  find  the  best-fit  chunk. 

•  If,  as  for  small  sizes  requested  from  t he  Lea  memory  manager,  there  is  a 
bin  for  chunks  of t h at  size  only,  we  may  take  any  chunk  from  t h at  bin. 

•  For  sizes  t h at  do  not  have  a  private  bin,  we  find  t he  one  bin  t h at  is 
allowed  to  include  chunks  of the  desired  size.  Within  t h at  bin,  we  can  use 
either  a  first-fit  or  a  best-fit  strategy;  i.e.,  we  either  look  for  and  select 
the  first  chunk  t h at  is  sufficiently  large  or,  we  spend  more  time  and  find 
t he  smallest  chunk  t h at  is  sufficiently  large.  Note  t h at  when  the  fit  is  not 
exact,  the  remainder  of  t he  chunk  will  generally  need  to  be  placed  in  a 
bin  with  smaller  sizes. 

•  However,  it  may  be  t h at  the  target  bin  is  empty,  or  all  chunks  in  t h at 
bin  are  too  small  to  satisfy  t he  request  for  space.  In  t h at  case,  we  simply 
repeat  t he  search,  using  the  bin  for  the  next  larger  size(s).  Eventually, 
we  either  find  a  chunk  we  can  use,  or  we  reach  t he  "wilderness"  chunk, 
from  which  we  can  surely  obtain  the  needed  space,  possibly  by  going  to 
the  operating  system  and  getting  additional  pages  for  the  heap. 

7.4. 

HEAP  MANAGEMENT 

459 

While  best-fit  placement  tends  to  improve  space  utilization,  it  may  not  be 
the  best  in  terms  of spatial  locality.  Chunks  allocated  at  about  t he  same  time  by 
a  program  tend  to  have  similar  reference  p a t t e r ns  and  to  have  similar  lifetimes. 
Placing  t h em  close  together  thus  improves  the  program's  spatial  locality.  One 
useful  adaptation  of  the  best-fit  algorithm  is  to  modify  the  placement  in  t he 
case  when  a  chunk  of t he  exact  requested  size  cannot  be  found.  In  this  case,  we 
use  a  next-fit  strategy,  trying  to  allocate  t he  object  in  the  chunk  t h at  has  last 
been  split,  whenever  enough  space  for  the  new  object  remains  in  t h at  chunk. 
Next-fit  also  tends  to  improve  the  speed  of  the  allocation  operation. 

M a n a g i ng  a nd  C o a l e s c i ng  Free  S p a ce 

W h en  an  object  is  deallocated  manually,  the  memory  manager  must  make  its 
chunk  free,  so  it  can  be  allocated  again.  In  some  circumstances,  it  may  also  be 
possible  to  combine  (coalesce)  t h at  chunk  with  adjacent  chunks  of  the  heap,  to 
form  a  larger  chunk.  There  is  an  advantage  to  doing  so,  since  we  can  always 
use  a  large  chunk  to  do  the  work  of  small  chunks  of  equal  total  size,  but  many 
small  chunks  cannot  hold  one  large  object,  as  the  combined  chunk  could. 

If  we  keep  a  bin  for  chunks  of  one  fixed  size,  as  Lea  does  for  small  sizes, 
then  we  may  prefer  not  to  coalesce  adjacent  blocks  of  t h at  size  into  a  chunk  of 
double  the  size.  It  is  simpler  to  keep  all  the  chunks  of one  size  in  as  many  pages 
as  we  need,  and  never  coalesce  them.  Then,  a  simple  allocation/deallocation 
scheme  is  to  keep  a bitmap,  with  one  bit  for  each  chunk in  the  bin.  A  1  indicates 
the  chunk  is  occupied;  0  indicates  it  is  free.  When  a  chunk  is  deallocated,  we 
change  its  1  to  a  0.  When  we  need  to  allocate  a  chunk,  we  find  any  chunk  with 
a  0  bit,  change  t h at  bit  to  a  1,  and  use  the  corresponding  chunk.  If  there  are 
no  free  chunks,  we  get  a  new  page,  divide  it  into  chunks  of the  appropriate  size, 
and  extend  the  bit  vector. 

Matters  are  more  complex  when  the  heap  is  managed  as  a  whole,  without 
binning,  or  if  we  are  willing  to  coalesce  adjacent  chunks  and  move  the  resulting 
chunk  to  a  different  bin  if  necessary.  There  are  two  d a ta  structures  t h at  are 
useful  to  support  coalescing  of  adjacent  free  blocks: 

•  Boundary  Tags.  At  both  the  low  and  high  ends  of  each  chunk,  whether 
free  or  allocated,  we  keep  vital  information.  At  b o th  ends,  we  keep  a 
free/used  bit  t h at  tells  whether  or  not  the  block  is  currently  allocated 
(used)  or  available  (free).  Adjacent  to  each  free/used  bit  is  a  count  of t he 
total  number  of  bytes  in  the  chunk. 

•  A  Doubly  Linked,  Embedded  Free  List.  T he  free  chunks  (but  not 

the 
allocated  chunks)  are  also  linked  in  a  doubly  linked  list.  T he  pointers  for 
this  list  are  within  t he  blocks  themselves,  say  adjacent  to  the  boundary 
tags  at  either  end.  Thus,  no  additional  space  is  needed  for  the  free  list, 
although  its  existence  does  place  a  lower  bound  on  how  small  chunks  can 
get;  they  must  accommodate  two  boundary  tags  and  two  pointers,  even 
if  the  object  is  a  single  byte.  T he  order  of  chunks  on  the  free  list  is  left 

460 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

unspecified.  For  example,  the  list  could  be  sorted  by  size,  thus  facilitating 
best-fit  placement. 

E x a m p le  7 . 1 0:  Figure  7.17  shows  part  of  a  heap  with  three  adjacent  chunks, 
A,  B,  and  C.  Chunk  B:  of  size  100,  has  just  been  deallocated  and  returned  to 
the  free  list.  Since  we  know  the  beginning  (left  end)  of  5,  we  also  know  the 
end  of  the  chunk  t h at  happens  to  be  immediately  to  B's  left,  namely  A  in  this 
example.  T he  free/used  bit  at  the  right  end  of  A  is  currently  0,  so  A  too  is  free. 
We  may  therefore  coalesce  A  and  B  into  one  chunk  of  300  bytes. 

Chunk  A 

Chunk  B 

Chunk  C 

Figure  7.17:  P a rt  of  a  heap  and  a  doubly  linked  free  list 

It  might  be  the  case  t h at  chunk  C,  the  chunk  immediately  to  B's  right, 
is  also  free,  in  which  case  we  can  combine  all  of  A,  B,  and  C.  Note  t h at  if 
we  always  coalesce  chunks  when  we  can,  then  there  can  never  be  two  adjacent 
free  chunks,  so  we  never  have  to  look  further  t h an  the  two  chunks  adjacent  to 
t he  one  being  deallocated.  In  the  current  case,  we  find  t he  beginning  of  C  by 
starting  at  the  left  end  of  B,  which  we  know,  and  finding  the  total  number  of 
bytes  in  B,  which  is  found  in  t he  left  boundary  tag  of  B  and  is  100  bytes.  W i th 
this  information,  we  find  the  right  end  of  B  and  the  beginning  of  the  chunk  to 
its  right.  At  t h at  point,  we  examine  t he  free/used  bit  of  C  and  find  t h at  it  is  1 
for  used;  hence,  C  is  not  available  for  coalescing. 

Since  we  must  coalesce  A  and  B,  we  need  to  remove  one  of t h em  from  t he  free 
list.  The  doubly  linked  free-list  structure  lets  us  find  t he  chunks  before  and  after 
each  of  A  and  B.  Notice  t h at  it  should  not  be  assumed  t h at  physical  neighbors 
A  and  B  are  also  adjacent  on  t he  free  list.  Knowing  t he  chunks  preceding  and 
following  A  and  B  on  t he  free  list,  it  is  straightforward  to  manipulate  pointers 
on  the  list  to  replace  A  and  B  by  one  coalesced  chunk. 

• 

Automatic  garbage  collection  can  eliminate  fragmentation  altogether  if  it 
moves  all  the  allocated  objects  to  contiguous  storage.  T he  interaction  between 
garbage  collection  and  memory  management  is  discussed  in  more  detail  in  Sec 
tion  7.6.4. 

7.4.5  Manual  Deallocation  Requests 

We  close  this  section  with  manual  memory  management,  where  t he  programmer 
must  explicitly  arrange  for  the  deallocation  of  data,  as  in  C  and  C + +.  Ideally, 
any  storage  t h at  will  no  longer  be  accessed  should  be  deleted.  Conversely,  any 
storage  t h at  may  be  referenced  must  not  be  deleted.  Unfortunately,  it  is  hard  to 
enforce  either  of these  properties.  In  addition  to  considering  t he  difficulties  with 

7.4. 

HEAP  MANAGEMENT 

461 

manual  deallocation,  we  shall  describe  some  of the  techniques  programmers  use 
to  help  with  the  difficulties. 

P r o b l e ms  w i th  M a n u al  D e a l l o c a t i on 

Manual  memory  management  is  error-prone.  T he  common  mistakes  take  two 
forms:  failing  ever  to  delete  d a ta  t h at  cannot  be  referenced  is  called  a  memory-
leak  error,  and  referencing  deleted  d a ta  is  a  dangling-pointer-dereference  error. 
It  is  hard  for  programmers  to  tell  if  a  program  will  never  refer  to  some  stor 
age  in  the  future,  so  the  first  common  mistake  is  not  deleting  storage  t h at  will 
never  be  referenced.  Note  t h at  although  memory  leaks  may  slow  down  the  exe 
cution  of  a  program  due  to  increased  memory  usage,  they  do  not  affect  program 
correctness,  as  long  as  the  machine  does  not  run  out  of  memory.  Many  pro 
grams  can  tolerate  memory  leaks,  especially  if the  leakage  is  slow.  However,  for 
long-running  programs,  and  especially  nonstop  programs  like  operating  systems 
or  server  code,  it  is  critical  t h at  they  not  have  leaks. 

Automatic  garbage  collection  gets  rid  of  memory  leaks  by  deallocating  all 
t he  garbage.  Even  with  automatic  garbage  collection,  a  program  may  still  use 
more  memory  t h an  necessary.  A  programmer  may  know  t h at  an  object  will 
never  be  referenced,  even  though  references  to  t h at  object  exist  somewhere.  In 
t h at  case,  t he  programmer  must  deliberately  remove  references  to  objects  t h at 
will  never  be  referenced,  so  the  objects  can  be  deallocated  automatically. 

Being  overly  zealous  about  deleting  objects  can  lead  to  even  worse  problems 
t h an  memory  leaks.  T he  second  common  mistake  is  to  delete  some  storage  and 
then  try  to  refer  to  t he  d a ta  in  the  deallocated  storage.  Pointers  to  storage  t h at 
has  been  deallocated  are  known  as  dangling  pointers.  Once  the  freed  storage 
has  been  reallocated  to  a  new  variable,  any  read,  write,  or  deallocation  via 
t he  dangling  pointer  can  produce  seemingly  random  effects.  We  refer  to  any 
operation,  such  as  read,  write,  or  deallocate,  t h at  follows  a  pointer  and  tries  to 
use  the  object  it  points  to,  as  dereferencing  t he  pointer. 

Notice  t h at  reading  through  a  dangling  pointer  may  return  an  arbitrary 
value.  Writing  through  a  dangling  pointer  arbitrarily  changes  the  value  of  the 
new  variable.  Deallocating  a  dangling  pointer's  storage  means  t h at  the  storage 
of  the  new  variable  may  be  allocated  to  yet  another  variable,  and  actions  on 
the  old  and  new  variables  may  conflict  with  each  other. 

Unlike  memory  leaks,  dereferencing  a  dangling  pointer  after  the  freed  storage 
is  reallocated  almost  always  creates  a  program  error  t h at  is  hard  to  debug.  As 
a  result,  programmers  are  more  inclined  not  to  deallocate  a  variable  if  they  are 
not  certain  it  is  unreferencable. 

A  related  form  of programming error  is  to  access  an  illegal  address.  Common 
examples  of  such  errors  include  dereferencing  null  pointers  and  accessing  an 
out-of-bounds  array  element.  It  is  better  for  such  errors  to  be  detected  t h an  to 
have  the  program  silently  corrupt  t he  results.  In  fact,  many  security  violations 
exploit  programming  errors  of  this  type,  where  certain  program  inputs  allow 
unintended  access  to  data,  leading  to  a  "hacker"  taking  control  of the  program 

462 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

An  Example:  Purify 

Rational's  Purify  is  one  of  the  most  popular  commercial  tools  t h at  helps 
programmers  find  memory  access  errors  and  memory  leaks  in  programs. 
Purify  instruments  binary  code  by  adding  additional  instructions  to  check 
for  errors  as  the  program  executes.  It  keeps  a  m ap  of  memory  to  indicate 
where  all  the  freed  and  used  spaces  are.  Each  allocated  object  is  bracketed 
with  extra  space;  accesses  to  unallocated  locations  or  to  spaces  between 
objects  are  flagged  as  errors.  This  approach  finds  some  dangling  pointer 
references,  but  not  when  the  memory  has  been  reallocated  and  a  valid 
object  is  sitting  in  its  place.  This  approach  also  finds  some  out-of-bound 
array  accesses,  if  they  happen  to  land  in  the  space  inserted  at  the  end  of 
the  objects. 

Purify  also  finds  memory  leaks  at  the  end  of  a  program  execution.  It 
searches  the  contents  of all  the  allocated  objects  for  possible  pointer  values. 
Any  object  without  a  pointer  to  it  is  a  leaked  chunk  of  memory.  Purify 
reports  the  amount  of  memory  leaked  and  the  locations  of  the  leaked 
objects.  We  may  compare  Purify  to  a  "conservative  garbage  collector," 
which  will  be  discussed  in  Section  7.8.3. 

and  machine.  One  antidote  is  to  have  the  compiler  insert  checks  with  every 
access,  to  make  sure  it  is  within  bounds.  The  compiler's  optimizer  can  discover 
and  remove  those  checks  t h at  are  not  really  necessary  because  the  optimizer 
can  deduce  t h at  the  access  must  be  within  bounds. 

P r o g r a m m i ng  C o n v e n t i o ns  a nd  T o o ls 

We  now  present  a  few  of the  most  popular  conventions  and  tools  t h at  have  been 
developed  to  help  programmers  cope  with  t he  complexity  in  managing  memory: 

•  Object  ownership  is  useful  when  an  object's  lifetime  can  be  statically  rea 
soned  about.  The  idea  is  to  associate  an  owner  with  each  object  at  all 
times.  T he  owner  is  a  pointer  to  t h at  object,  presumably  belonging  to 
some  function  invocation.  T he  owner  (i.e.,  its  function)  is  responsible  for 
either  deleting  the  object  or  for  passing  t he  object  to  another  owner.  It 
is  possible  to  have  other,  nonowning  pointers  to  t he  same  object;  these 
pointers  can  be  overwritten  any  time,  and  no  deletes  should  ever  be  ap 
plied  through  them.  This  convention  eliminates  memory  leaks,  as  well  as 
a t t e m p ts  to  delete  t he  same  object  twice.  However,  it  does  not  help  solve 
the  dangling-pointer-reference  problem,  because  it  is  possible  to  follow  a 
nonowning  pointer  to  an  object  t h at  has  been  deleted. 

•  Reference  counting  is  useful  when  an  object's  lifetime  needs  to  be  deter 
mined  dynamically.  T he  idea  is  to  associate  a  count  with  each  dynamically 

7.5. 

INTRODUCTION  TO  GARBAGE  COLLECTION 

463 

allocated  object.  Whenever  a  reference  to  the  object  is  created,  we  incre 
ment  t he  reference  count;  whenever  a  reference  is  removed,  we  decrement 
the  reference  count.  When  the  count  goes  to  zero,  the  object  can  no  longer 
be  referenced  and  can  therefore  be  deleted.  This  technique,  however,  does 
not  catch  useless,  circular  d a ta  structures,  where  a  collection  of  objects 
cannot  be  accessed,  but  their  reference  counts  are  not  zero,  since  they 
refer  to  each  other.  For  an  illustration  of this  problem,  see  Example  7.11. 
Reference  counting  does  eradicate  all  dangling-pointer  references,  since 
there  are  no  outstanding  references  to  any  deleted  objects.  Reference 
counting  is  expensive  because  it  imposes  an  overhead  on  every  operation 
t h at  stores  a  pointer. 

•  Region-based  allocation  is  useful  for  collections  of  objects  whose  lifetimes 
are  tied  to  specific  phases  in  a  computation.When  objects  are  created  to 
be  used  only  within  some  step  of  a  computation,  we  can  allocate  all  such 
objects  in  the  same  region.  We  then  delete  the  entire  region  once  t h at 
computation  step  completes.  This  region-based  allocation  technique  has 
limited  applicability.  However,  it  is  very  efficient  whenever  it  can  be  used; 
instead  of  deallocating  objects  one  at  a  time,  it  deletes  all  objects  in  t he 
region  in  a  wholesale  fashion. 

7.4.6  Exercises  for  Section  7.4 

E x e r c i se  7. 4. 1:  Suppose  the  heap  consists  of seven  chunks,  starting  at  address 
0.  The  sizes  of the  chunks,  in  order,  are  80,  30,  60,  50,  70,  20,  40  bytes.  W h en 
we  place  an  object  in  a  chunk,  we  put  it  at  the  high  end  if  there  is  enough 
space  remaining  to  form  a  smaller  chunk  (so  t h at  t he  smaller  chunk  can  easily 
remain  on  the  linked  list  of  free  space).  However,  we  cannot  tolerate  chunks 
of  fewer  t h at  8  bytes,  so  if  an  object  is  almost  as  large  as  t he  selected  chunk, 
we  give  it  the  entire  chunk  and  place  the  object  at  t he  low  end  of  t he  chunk. 
If  we  request  space  for  objects  of  the  following  sizes:  32,  64,  48,  16,  in  t h at 
order,  what  does  the  free  space  list  look  like  after  satisfying  the  requests,  if  the 
method  of  selecting  chunks  is 

a)  First  fit. 

b)  Best  fit. 

7.5 

Introduction  to  Garbage  Collection 

D a ta  t h at  cannot  be  referenced  is  generally  known  as  garbage.  Many  high-level 
programming  languages  remove  the  burden  of  manual  memory  management 
from  the  programmer  by  offering  automatic  garbage  collection,  which  deallo 
cates  unreachable  data.  Garbage  collection  dates  back  to  the  initial  implemen 
tation  of  Lisp  in  1958.  Other  significant  languages  t h at  offer  garbage  collection 
include  Java,  Perl,  ML,  Modula-3,  Prolog,  and  Smalltalk. 

464 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

In  this  section,  we  introduce  many  of  the  concepts  of  garbage  collection. 
The  notion  of  an  object  being  "reachable"  is  perhaps  intuitive,  but  we  need  to 
be  precise;  the  exact  rules  are  discussed  in  Section  7.5.2.  We  also  discuss,  in 
Section  7.5.3,  a  simple,  but  imperfect,  method  of  automatic  garbage  collection: 
reference  counting,  which  is  based  on  the  idea  t h at  once  a  program  has  lost  all 
references  to  an  object,  it  simply  cannot  and  so  will  not  reference  the  storage. 
Section  7.6  covers  trace-based  collectors,  which  are  algorithms  t h at  discover 

all  the  objects  t h at  are  still  useful,  and  then  t u rn  all  the  other  chunks  of  t he 
heap  into  free  space. 

7.5.1  Design  Goals  for  Garbage  Collectors 

Garbage  collection  is  the  reclamation  of  chunks  of  storage  holding  objects  t h at 
can  no  longer  be  accessed  by  a  program.  We  need  to  assume  t h at  objects  have 
a  type  t h at  can  be  determined  by  the  garbage  collector  at  run  time.  From  the 
type  information,  we  can  tell  how  large  the  object  is  and  which  components  of 
the  object  contain  references  (pointers)  to  other  objects.  We  also  assume  t h at 
references  to  objects  are  always  to  the  address  of  t he  beginning  of  the  object, 
never  pointers  to  places  within  the  object.  Thus,  all  references  to  an  object 
have  the  same  value  and  can  be  identified  easily. 

A  user  program,  which  we  shall  refer  to  as  t he  mutator,  modifies  t he  col 
lection  of  objects  in  t he  heap.  The  m u t a t or  creates  objects  by  acquiring  space 
from  the  memory  manager,  and  the  m u t a t or  may  introduce  and  drop  references 
to  existing  objects.  Objects  become  garbage  when  the  m u t a t or  program  cannot 
"reach"  them,  in  t he  sense  made  precise  in  Section  7.5.2.  T he  garbage  collector 
finds  these  unreachable  objects  and  reclaims  their  space  by  handing  t h em  to 
the  memory  manager,  which  keeps  track  of  the  free  space. 

A  B a s ic  R e q u i r e m e n t:  T y pe  S a f e ty 

Not  all  languages  are  good  candidates  for  automatic  garbage  collection.  For  a 
garbage  collector  to  work,  it  must  be  able  to  tell  whether  any  given  d a ta  element 
or  component  of  a  d a ta  element  is,  or  could  be  used  as,  a  pointer  to  a  chunk  of 
allocated  memory  space.  A  language  in  which  the  type  of  any  d a ta  component 
can  be  determined  is  said  to  be  type  safe.  There  are  type-safe  languages  like 
ML,  for  which  we  can  determine  types  at  compile  time.  There  are  other  type-
safe  languages,  like  Java,  whose  types  cannot  be  determined  at  compile  time, 
but  can  be  determined  at  run  time.  T he  latter  are  called  dynamically  typed 
languages.  If  a  language  is  neither  statically  nor  dynamically  type  safe,  then  it 
is  said  to  be  unsafe. 

Unsafe  languages,  which  unfortunately  include  some  of  the  most  impor 
t a nt  languages  such  as  C  and  C + +,  are  bad  candidates  for  automatic  garbage 
collection. 
In  unsafe  languages,  memory  addresses  can  be  manipulated  arbi 
trarily:  arbitrary  arithmetic  operations  can  be  applied  to  pointers  to  create 
new  pointers,  and  arbitrary  integers  can  be  cast  as  pointers.  Thus  a  program 

7.5. 

INTRODUCTION  TO  GARBAGE  COLLECTION 

465 

theoretically  could  refer  to  any  location  in  memory  at  any  time.  Consequently, 
no  memory  location  can  be  considered  to  be  inaccessible,  and  no  storage  can 
ever  be  reclaimed  safely. 

In  practice,  most  C  and  C ++  programs  do  not  generate  pointers  arbitrarily, 
and  a  theoretically  unsound  garbage  collector  t h at  works  well  empirically  has 
been  developed  and  used.  We  shall  discuss  conservative  garbage  collection  for 
C  and  C ++  in  Section  7.8.3. 

P e r f o r m a n ce  M e t r i cs 

Garbage  collection  is  often  so  expensive  t h a t,  although  it  was  invented  decades 
ago  and  absolutely  prevents  memory  leaks,  it  has  yet  to  be  adopted  by  many 
mainstream  programming  languages.  Many  different  approaches  have  been  pro 
posed  over  the  years,  and  there  is  not  one  clearly  best  garbage-collection  algo 
rithm.  Before  exploring  the  options,  let  us  first  enumerate  the  performance 
metrics  t h at  must  be  considered  when  designing  a  garbage  collector. 

•  Overall  Execution  Time.  Garbage  collection  can  be  very  slow.  It  is  impor 
t a nt  t h at  it  not  significantly  increase  the  total  run  time  of  an  application. 
Since  the  garbage  collector  necessarily  must  touch  a  lot  of  data,  its  perfor 
mance  is  determined  greatly  by  how  it  leverages  the  memory  subsystem. 

•  Space  Usage.  It  is  important  t h at  garbage  collection  avoid  fragmentation 

and  make  the  best  use  of  the  available  memory. 

•  Pause  Time. 

Simple  garbage  collectors  are  notorious  for  causing  pro 
grams  —  t he  m u t a t o rs  —  to  pause  suddenly  for  an  extremely  long  time, 
as  garbage  collection  kicks  in  without  warning.  Thus,  besides  minimiz 
ing  the  overall  execution  time,  it  is  desirable  t h at  the  maximum  pause 
time  be  minimized.  As  an  important  special  case,  real-time  applications 
require  certain  computations  to  be  completed  within  a  time  limit.  We 
must  either  suppress  garbage  collection  while  performing  real-time  tasks, 
or  restrict  maximum  pause  time.  Thus,  garbage  collection  is  seldom  used 
in  real-time  applications. 

•  Program  Locality.  We  cannot  evaluate  the  speed  of  a  garbage  collector 
solely  by  its  running  time.  The  garbage  collector  controls  the  placement 
of  d a ta  and  thus  influences  the  d a ta  locality  of  the  m u t a t or  program.  It 
can  improve  a  m u t a t o r 's  temporal  locality  by  freeing  up  space  and  reusing 
it;  it  can  improve  the  m u t a t o r 's  spatial  locality  by  relocating  d a ta  used 
together  in  the  same  cache  or  pages. 

Some  of  these  design  goals  conflict  with  one  another,  and  tradeoffs  must  be 
made  carefully  by  considering  how  programs  typically  behave.  Also  objects  of 
different  characteristics  may  favor  different  treatments,  requiring  a  collector  to 
use  different  techniques  for  different  kinds  of  objects. 

466 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

For  example,  the  number  of objects  allocated  is  dominated  by  small  objects, 
so  allocation  of  small  objects  must  not  incur  a  large  overhead.  On  t he  other 
hand,  consider  garbage  collectors  t h at  relocate  reachable  objects.  Relocation  is 
expensive  when  dealing  with  large  objects,  but  less  so  with  small  objects. 

As  another  example,  in  general,  the  longer  we  wait  to  collect  garbage  in  a 
trace-based  collector,  t he  larger  the  fraction  of  objects  t h at  can  be  collected. 
The  reason  is  t h at  objects  often  "die  young,"  so  if  we  wait  a  while,  many  of 
the  newly  allocated  objects  will  become  unreachable.  Such  a  collector  thus 
costs  less  on  the  average,  per  unreachable  object  collected.  On  the  other  hand, 
infrequent  collection  increases  a  program's  memory  usage,  decreases  its  d a ta 
locality,  and  increases  the  length  of  the  pauses. 

In  contrast,  a  reference-counting  collector,  by  introducing  a  constant  over 
head  to  many  of the  m u t a t o r 's  operations,  can  slow  down  the  overall  execution 
of  a  program  significantly.  On  the  other  hand,  reference  counting  does  not  cre 
ate  long  pauses,  and  it  is  memory  efficient,  because  it  finds  garbage  as  soon 
as  it  is  produced  (with  the  exception  of  certain  cyclic  structures  discussed  in 
Section  7.5.3). 

Language  design  can  also  affect  the  characteristics  of  memory  usage.  Some 
languages  encourage  a  programming  style  t h at  generates  a  lot  of  garbage.  For 
example,  programs  in  functional  or  almost  functional  programming  languages 
In  Java,  all  objects, 
create  more  objects  to  avoid  mutating  existing  objects. 
other  t h an  base  types  like  integers  and  references,  are  allocated  on  the  heap 
and  not  the  stack,  even  if  their  lifetimes  are  confined  to  t h at  of  one  function 
invocation.  This  design  frees  t he  programmer  from  worrying  about  t he  lifetimes 
of variables,  at  the  expense  of generating  more  garbage.  Compiler  optimizations 
have  been  developed  to  analyze  the  lifetimes  of  variables  and  allocate  t h em  on 
t he  stack  whenever  possible. 

7.5.2  Reachability 

We  refer  to  all  the  d a ta  t h at  can  be  accessed  directly  by  a  program,  without 
having  to  dereference  any  pointer,  as  the  root  set  For  example,  in  Java  the  root 
set  of  a  program  consists  of  all  t he  static  field  members  and  all  the  variables 
on  its  stack.  A  program  obviously  can  reach  any  member  of  its  root  set  at 
any  time.  Recursively,  any  object  with  a  reference  t h at  is  stored  in  the  field 
members  or  array  elements  of  any  reachable  object  is  itself  reachable. 

Reachability  becomes  a  bit  more  complex  when  t he  program  has  been  op 
timized  by  the  compiler.  First,  a  compiler  may  keep  reference  variables  in 
registers.  These  references  must  also  be  considered  part  of  the  root  set.  Sec 
ond,  even  though  in  a  type-safe  language  programmers  do  not  get  to  manipulate 
memory  addresses  directly,  a  compiler  often  does  so  for  the  sake  of speeding  up 
the  code.  Thus,  registers  in  compiled  code  may  point  to  the  middle  of  an  object 
or  an  array,  or  they  may  contain  a  value  to  which  an  offset  will  be  applied  to 
compute  a  legal  address.  Here  are  some  things  an  optimizing  compiler  can  do 
to  enable  the  garbage  collector  to  find  t he  correct  root  set: 

7.5. 

INTRODUCTION  TO  GARBAGE  COLLECTION 

467 

•  T he  compiler  can  restrict  the  invocation  of  garbage  collection  to  only 
certain  code  points  in  the  program,  when  no  "hidden"  references  exist. 

•  T he  compiler  can  write  out  information  t h at  t he  garbage  collector  can 
use  to  recover  all  the  references,  such  as  specifying  which  registers  contain 
references,  or  how  to  compute  the  base  address  of  an  object  t h at  is  given 
an  internal  address. 

•  The  compiler  can  assure  t h at  there  is  a  reference  to  the  base  address  of 
all  reachable  objects  whenever  the  garbage  collector  may  be  invoked. 

T he  set  of reachable  objects  changes  as  a  program  executes.  It  grows  as  new 
objects  get  created  and  shrinks  as  objects  become  unreachable.  It  is  important 
to  remember  t h at  once  an  object  becomes  unreachable,  it  cannot  become  reach 
able  again.  There  are  four  basic  operations  t h at  a  m u t a t or  performs  to  change 
the  set  of  reachable  objects: 

•  Object  Allocations.  These  are  performed  by  t he  memory  manager,  which 
returns  a  reference  to  each  newly  allocated  chunk  of  memory.  This  oper 
ation  adds  members  to  the  set  of  reachable  objects. 

•  Parameter  Passing  and  Return  Values.  References  to  objects  are  passed 
from  t he  actual  input  parameter  to  t he  corresponding  formal  parameter, 
and  from  t he  returned  result  back  to  the  callee.  Objects  pointed  to  by 
these  references  remain  reachable. 

•  Reference  Assignments.  Assignments  of  t he  form  u  =  v,  where  u  and  v 
are  references,  have  two  effects.  First,  u  is  now  a  reference  to  t he  object 
referred  to  by  v.  As  long  as  u  is  reachable,  the  object  it  refers  to  is  surely 
reachable.  Second,  the  original  reference  in  u  is  lost.  If  this  reference  is 
the  last  to  some  reachable  object,  then  t h at  object  becomes  unreachable. 
Any  time  an  object  becomes  unreachable,  all  objects  t h at  are  reachable 
only  through  references  contained  in  t h at  object  also  become  unreachable. 

•  Procedure  Returns.  As  a  procedure  exits, 

the  frame  holding  its  local 
If  the  frame  holds  the  only  reachable 
variables  is  popped  off  the  stack. 
reference  to  any  object,  t h at  object  becomes  unreachable.  Again,  if  the 
now  unreachable  objects  hold  t he  only  references  to  other  objects,  they 
too  become  unreachable,  and  so  on. 

In  summary,  new  objects  are  introduced  through  object  allocations.  P a r a m 
eter  passing  and  assignments  can  propagate  reachability;  assignments  and  ends 
of  procedures  can  terminate  reachability.  As  an  object  becomes  unreachable,  it 
can  cause  more  objects  to  become  unreachable. 

There  are  two  basic  ways  to  find  unreachable  objects.  Either  we  catch  the 
transitions  as  reachable  objects  t u rn  unreachable,  or  we  periodically  locate  all 
t he  reachable  objects  and  then  infer  t h at  all  the  other  objects  are  unreachable. 
Reference  counting,  introduced  in  Section  7.4.5,  is  a  well-known  approximation 

468 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

Survival  of  Stack  Objects 

When  a  procedure  is  called,  a  local  variable  v,  whose  object  is  allocated 
on  the  stack,  may  have  pointers  to  v  placed  in  nonlocal  variables.  These 
pointers  will  continue  to  exist  after  the  procedure  returns,  yet  t he  space  for 
v  disappears,  resulting  in  a  dangling-reference  situation.  Should  we  ever 
allocate  a  local  like  v  on  the  stack,  as  C  does  for  example?  T he  answer 
is  t h at  t he  semantics  of  many  languages  requires  t h at  local  variables  cease 
to  exist  when  their  procedure  returns.  Retaining  a  reference  to  such  a 
variable  is  a  programming  error,  and  t he  compiler  is  not  required  to  fix 
the  bug  in  the  program. 

to  the  first  approach.  We  maintain  a  count  of  the  references  to  an  object,  as 
the  m u t a t or  performs  actions  t h at  may  change  the  reachability  set.  When  the 
count  goes  to  zero,  the  object  becomes  unreachable.  We  discuss  this  approach 
in  more  detail  in  Section  7.5.3. 

The  second  approach  computes  reachability  by  tracing  all  the  references 
transitively.  A  trace-based  garbage  collector  starts  by  labeling  ("marking")  all 
objects  in  the  root  set  as  "reachable,"  examines  iteratively  all  t he  references 
in  reachable  objects  to  find  more  reachable  objects,  and  labels  t h em  as  such. 
This  approach  must  trace  all  the  references  before  it  can  determine  any  object 
to  be  unreachable.  But  once  the  reachable  set  is  computed,  it  can  find  many 
unreachable  objects  all  at  once  and  locate  a good  deal  of free  storage  at  t he  same 
time.  Because  all  t he  references  must  be  analyzed  at  the  same  time,  we  have 
an  option  to  relocate  the  reachable  objects  and  thereby  reduce  fragmentation. 
There  are  many  different  trace-based  algorithms,  and  we  discuss  t he  options  in 
Sections  7.6  and  7.7.1. 

7.5.3  Reference  Counting  Garbage  Collectors 

We  now  consider  a  simple,  although  imperfect,  garbage  collector,  based  on 
reference  counting,  which  identifies  garbage  as  an  object  changes  from  being 
reachable  to  unreachable;  the  object  can  be  deleted  when  its  count  drops  to 
zero.  W i th  a  reference-counting  garbage  collector,  every  object  must  have  a 
field  for  t he  reference  count.  Reference  counts  can  be  maintained  as  follows: 

1.  Object  Allocation.  The  reference  count  of  the  new  object  is  set  to  1. 

2.  Parameter  Passing.  T he  reference  count  of  each  object  passed  into  a 

procedure  is  incremented. 

3.  Reference  Assignments.  For  statement  u  =  v,  where  u  and  v  are  refer 
ences,  t he  reference  count  of  the  object  referred  to  by  v  goes  up  by  one, 
and  t he  count  for  t he  old  object  referred  to  by  u  goes  down  by  one. 

7.5. 

INTRODUCTION  TO  GARBAGE  COLLECTION 

469 

4.  Procedure  Returns.  As  a  procedure  exits,  all  the  references  held  by  the 
local  variables  of  t h at  procedure  activation  record  must  also  be  decre 
mented.  If  several  local  variables  hold  references  to  t he  same  object,  t h at 
object's  count  must  be  decremented  once  for  each  such  reference. 

5.  Transitive  Loss  of  Reachability.  Whenever  t he  reference  count  of  an  object 
becomes  zero,  we  must  also  decrement  the  count  of  each  object  pointed 
to  by  a  reference  within  t he  object. 

Reference  counting  has  two  main  disadvantages:  it  cannot  collect  unreach 
able,  cyclic  d a ta  structures,  and  it  is  expensive.  Cyclic  d a ta  structures  are  quite 
plausible;  d a ta  structures  often  point  back  to  their  parent  nodes,  or  point  to 
each  other  as  cross  references. 

E x a m p le  7 . 1 1:  Figure  7.18  shows  three  objects  with  references  among  them, 
but  no  references  from  anywhere  else. 
If  none  of  these  objects  is  part  of  the 
root  set,  then  they  are  all  garbage,  but  their  reference  counts  are  each  greater 
t h an  0.  Such  a  situation  is  t a n t a m o u nt  to  a  memory  leak  if  we  use  reference 
counting  for  garbage  collection,  since  then  this  garbage  and  any  structures  like 
it  are  never  deallocated. 

• 

No  pointers 
from  outside 

Figure  7.18:  An  unreachable,  cyclic  d a ta  structure 

T he  overhead  of reference  counting  is  high  because  additional  operations  are 
introduced  with  each  reference  assignment,  and  at  procedure  entries  and  exits. 
This  overhead is  proportional  to  the  amount  of computation  in  the  program,  and 
not  just  to  the  number  of  objects  in  the  system.  Of  particular  concern  are  the 
updates  made  to  references  in  the  root  set  of a  program.  T he  concept  of  deferred 
reference  counting  has  been  proposed  as  a  means  to  eliminate  t he  overhead 
associated  with  updating  the  reference  counts  due  to  local  stack  accesses.  T h at 
is,  reference  counts  do  not  include  references  from  t he  root  set  of  t he  program. 
An  object  is  not  considered  to  be  garbage  until  the  entire  root  set  is  scanned 
and  no  references  to  the  object  are  found. 

The  advantage  of reference  counting,  on  the  other  hand,  is  t h at  garbage  col 

lection  is  performed  in  an  incremental  fashion.  Even  though  the  total  overhead 
can  be  large,  t he  operations  are  spread  throughout  t he  m u t a t o r 's  computation. 

470 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

Although  removing  one  reference  may  render  a  large  number  of  objects  un 
reachable,  t he  operation  of  recursively  modifying  reference  counts  can  easily  be 
deferred  and  performed  piecemeal  across  time.  Thus,  reference  counting  is  par 
ticularly  attractive  algorithm  when  timing  deadlines  must  be  met,  as  well  as  for 
interactive  applications  where  long,  sudden  pauses  are  unacceptable.  Another 
advantage  is  t h at  garbage  is  collected  immediately,  keeping  space  usage  low. 

X 

Figure  7.19:  A  network  of  objects 

7.5.4  Exercises  for  Section  7.5 

E x e r c i se  7. 5. 1:  W h at  happens  to  the  reference  counts  of  t he  objects  in  Fig. 
7.19  if: 

a)  T he  pointer  from  A  to  B  is  deleted. 

b)  T he  pointer  from  X  to  A  is  deleted. 

c)  T he  node  C  is  deleted. 

E x e r c i se  7. 5. 2:  W h at  happens  to  reference  counts  when  the  pointer  from  A 
to  D  in  Fig.  7.20  is  deleted? 

7.6 

Introduction  to  Trace-Based  Collection 

Instead  of collecting  garbage  as  it  is  created,  trace-based  collectors  run  periodi 
cally  to  find  unreachable  objects  and  reclaim  their  space.  Typically,  we  run  the 

7.6. 

INTRODUCTION  TO 

TRACE-BASED  COLLECTION 

471 

X 

Y 

Figure  7.20:  Another  network  of  objects 

trace-based  collector  whenever  the  free  space  is  exhausted  or  its  amount  drops 
below  some  threshold. 

We  begin  this  section  by  introducing  the  simplest  "mark-and-sweep"  gar 
bage  collection  algorithm.  We  then  describe  the  variety  of  trace-based  algo 
rithms  in  terms  of  four  states  t h at  chunks  of  memory  can  be  put  in.  This 
section  also  contains  a  number  of  improvements  on  t he  basic  algorithm,  includ 
ing  those  in  which  object  relocation  is  a  part  of  the  garbage-collection  function. 

7.6.1  A  Basic  Mark-and-Sweep  Collector 

Mark-and-sweep  garbage-collection  algorithms  are  straightforward,  stop-the-
world  algorithms  t h at  find  all  the  unreachable  objects,  and  put  t h em  on  the  list 
of free  space.  Algorithm  7.12  visits  and  "marks"  all  the  reachable  objects  in  the 
first  tracing  step  and  then  "sweeps"  the  entire  heap  to  free  up  unreachable  ob 
jects.  Algorithm  7.14,  which  we  consider  after  introducing  a  general  framework 
for  trace-based  algorithms,  is  an  optimization  of  Algorithm  7.12.  By  using  an 
additional  list  to  hold  all  t he  allocated  objects,  it  visits  t he  reachable  objects 
only  once. 

A l g o r i t hm  7 . 1 2:  Mark-and-sweep  garbage  collection. 

I N P U T:  A  root  set  of  objects,  a  heap,  and  a  free  list,  called  Free,  with  all  the 
unallocated  chunks  of  the  heap.  As  in  Section  7.4.4,  all  chunks  of  space  are 
marked  with  boundary  tags  to  indicate  their  free/used  status  and  size. 

O U T P U T:  A  modified  Free  list  after  all  t he  garbage  has  been  removed. 

M E T H O D:  T he  algorithm,  shown  in  Fig.  7.21,  uses  several  simple  d a ta  struc 
tures.  List  Free  holds  objects  known  to  be  free.  A  list  called  Unscanned,  holds 
objects  t h at  we  have  determined  are  reached,  but  whose  successors  we  have  not 
yet  considered.  T h at  is,  we  have  not  scanned  these  objects  to  see  what  other 

472 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

/*  marking  phase  */ 
set  the  reached-bit  to  1  and  add  to  list  Unscanned  each  object 

1) 

referenced  by  t he  root  set; 

2)  w h i le  (Unscanned ^ 0) { 
3) 
4) 
5) 
6) 

remove  some  object  o  from  Unscanned; 
for  (each  object  d  referenced  in  o)  { 

if  (o'  is  unreached;  i.e.,  its  reached-bit  is  0)  { 

set  t he  reached-bit  of  d  to  1; 

7) 

put  d  in  Unscanned; 

} 

} 

} 
/*  sweeping  phase  */ 

8)  Free  = 0; 
9) 
10) 

for  (each  chunk  of  memory  o  in  t he  heap)  { 

if  (o  is  unreached,  i.e.,  its  reached-bit  is  0)  add  o  to  Free; 

11) 

e l se  set  the  reached-bit  of  o  to  0; 

} 

Figure  7.21:  A  Mark-and-Sweep  Garbage  Collector 

objects  can  be  reached  through  them.  The  Unscanned  list  is  empty  initially. 
Additionally,  each  object  includes  a  bit  to  indicate  whether  it  has  been  reached 
(the  reached-bit).  Before  the  algorithm  begins,  all  allocated  objects  have  t he 
reached-bit  set  to  0. 

In  line  (1)  of  Fig.  7.21,  we  initialize  t he  Unscanned  list  by  placing  there  all 
the  objects  referenced  by  the  root  set.  The  reached-bit  for  these  objects  is  also 
set  to  1.  Lines  (2)  through  (7)  are  a  loop,  in  which  we,  in  turn,  examine  each 
object  o  t h at  is  ever  placed  on  the  Unscanned  list. 

The  for-loop  of  lines  (4)  through  (7)  implements  the  scanning  of  object  o. 
We  examine  each  object  d  for  which  we  find  a  reference  within  o. 
If  d  has 
already  been  reached  (its  reached-bit  is  1),  then  there  is  no  need  to  do  anything 
about  d;  it  either  has  been  scanned  previously,  or  it  is  on  the  Unscanned  list 
to  be  scanned  later.  However,  if  d  was  not  reached  already,  then  we  need  to 
set  its  reached-bit  to  1  in  line  (6)  and  add  d  to  the  Unscanned  list  in  line  (7). 
Figure  7.22  illustrates  this  process.  It  shows  an  Unscanned list  with  four  objects. 
The  first  object  on  this  list,  corresponding  to  object  o  in  the  discussion  above, 
is  in  the  process  of  being  scanned.  T he  dashed  lines  correspond  to  t he  three 
kinds  of  objects  t h at  might  be  reached  from  o: 

1.  A  previously  scanned  object  t h at  need  not  be  scanned  again. 

2.  An  object  currently  on  t he  Unscanned  list. 

3.  An  item  t h at  is  reachable,  but  was  previously  thought  to  be  unreached. 

7.6. 

INTRODUCTION  TO 

TRACE-BASED  COLLECTION 

473 

— H 

Unscanned 

U n s c a n n ed  a nd  previously  scanned  objects 
reached  bit  =  1 

Free  a nd  u n r e a c h ed  objects 
reached  bit  =  0 

Figure  7.22:  The  relationships  among  objects  during  the  marking  phase  of  a 
mark-and-sweep  garbage  collector 

Lines  (8)  through  (11),  the  sweeping  phase,  reclaim  the  space  of  all  the 
objects  t h at  remain  unreached  at  the  end  of  the  marking  phase.  Note  t h at 
these  will  include  any  objects  t h at  were  on  the  Free  list  originally.  Because  the 
set  of  unreached  objects  cannot  be  enumerated  directly,  the  algorithm  sweeps 
through  the  entire  heap.  Line  (10)  puts  free  and  unreached  objects  on  the 
Free  list,  one  at  a  time.  Line  (11)  handles  the  reachable  objects.  We  set  their 
reached-bit  to  0,  in  order  to  maintain  the  proper  preconditions  for  the  next 
execution  of  the  garbage-collection  algorithm. 

• 

7.6.2  Basic  Abstraction 

All  trace-based  algorithms  compute  the  set  of  reachable  objects  and  then  take 
the  complement  of  this  set.  Memory  is  therefore  recycled  as  follows: 

a)  T he  program  or  m u t a t or  runs  and  makes  allocation  requests. 

b)  T he  garbage  collector  discovers  reachability  by  tracing. 

c)  The  garbage  collector  reclaims  the  storage  for  unreachable  objects. 

This  cycle  is  illustrated  in  Fig.  7.23  in  terms  of four  states  for  chunks  of memory: 
Free,  Unreached,  Unscanned,  and  Scanned.  The  state  of  a  chunk  might  be  stored 
in  the  chunk  itself,  or  it  might  be  implicit  in  the  d a ta  structures  used  by  t he 
garbage-collection  algorithm. 

While  trace-based  algorithms  may  differ  in  their  implementation,  they  can 

all  be  described  in  terms  of  the  following  states: 

1.  Free.  A  chunk  is  in  the  Free  state  if  it  is  ready  to  be  allocated.  Thus,  a 

Free  chunk  must  not  hold  a  reachable  object. 

2.  Unreached.  Chunks  are  presumed  unreachable,  unless  proven  reachable  by 
tracing.  A  chunk  is  in  the  Unreached  state  at  any  point  during  garbage 

474 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

allocate 

Free 

(a)  Before  tracing:  action  of mutator 

reached  from 
root  set 

(b)  Discovering  reachability  by  tracing 

deallocate 

Free 

(  Unreached 

ready  for 
next  collection 

(c)  Reclaiming  storage 

Figure  7.23:  States  of memory  in  a  garbage  collection  cycle 

collection  if  its  reachability  has  not  yet  been  established.  Whenever  a 
chunk  is  allocated  by  t he  memory  manager,  its  state  is  set  to  Unreached 
as  illustrated  in  Fig.  7.23(a).  Also,  after  a  round  of  garbage  collection, 
the  state  of  a  reachable  object  is  reset  to  Unreached  to  get  ready  for  the 
next  round;  see  the  transition  from  Scanned to  Unreached,  which  is  shown 
dashed  to  emphasize  t h at  it  prepares  for  t he  next  round. 

3.  Unscanned.  Chunks  t h at  are  known  to  be  reachable  are  either  in  state 
Unscanned  or  state  Scanned.  A  chunk  is  in  the  Unscanned  state  if  it  is 
known  to  be  reachable,  but  its  pointers  have  not  yet  been  scanned.  T he 
transition  to  Unscanned  from  Unreached  occurs  when  we  discover  t h at  a 
chunk  is  reachable;  see  Fig.  7.23(b). 

4.  Scanned.  Every  Unscanned  object  will  eventually  be  scanned  and  tran 
sition  to  t he  Scanned  state.  To  scan  an  object,  we  examine  each  of  t he 
pointers  within  it  and  follow  those  pointers  to  the  objects  to  which  they 
refer.  If  a  reference  is  to  an  Unreached  object,  then  t h at  object  is  put  in 
the  Unscanned state.  When  the  scan  of an  object  is  completed,  t h at  object 
is  placed  in  t he  Scanned  state;  see  the  lower  transition  in  Fig.  7.23(b).  A 
Scanned  object  can  only  contain  references  to  other  Scanned or  Unscanned 
objects,  and  never  to  Unreached  objects. 

7.6. 

INTRODUCTION  TO 

TRACE-BASED  COLLECTION 

475 

W h en  no  objects  are  left  in  the  Unscanned  state,  the  computation  of  reach 
ability  is  complete.  Objects  left  in  the  Unreached  state  at  the  end  are  truly 
unreachable.  T he  garbage  collector  reclaims  the  space  they  occupy  and  places 
t he  chunks  in  the  Free  state,  as  illustrated  by  the  solid  transition  in  Fig.  7.23(c). 
To  get  ready  for  the  next  cycle  of garbage  collection,  objects  in  t he  Scanned state 
are  returned  to  t he  Unreached  state;  see  the  dashed  transition  in  Fig.  7.23(c). 
Again,  remember  t h at  these  objects  really  are  reachable  right  now.  The  Un 
reachable  state  is  appropriate  because  we  shall  want  to  start  all  objects  out 
in  this  state  when  garbage  collection  next  begins,  by  which  time  any  of  the 
currently  reachable  objects  may  indeed  have  been  rendered  unreachable. 

E x a m p le  7 . 1 3:  Let  us  see  how  the  d a ta  structures  of  Algorithm  7.12  relate 
to  the  four  states  introduced  above.  Using  the  reached-bit  and  membership  on 
lists  Free  and  Unscanned,  we  can  distinguish  among  all  four  states.  T he  table 
of  Fig.  7.24  summarizes  the  characterization  of  t he  four  states  in  terms  of  t he 
• 
d a ta  structure  for  Algorithm  7.12. 

S T A TE 

ON  Free  ON  Unscanned 

R E A C H E D - B IT 

Free 
Unreached 
Unscanned 
Scanned 

Yes 
No 
No 
No 

No 
No 
Yes 
No 

0 
0 
1 
1 

Figure  7.24:  Representation  of  states  in  Algorithm  7.12 

7.6.3  Optimizing  Mark-and-Sweep 

The  final  step  in  the  basic  mark-and-sweep  algorithm  is  expensive  because  there 
is  no  easy  way  to  find  only  the  unreachable  objects  without  examining  t he  entire 
heap.  An  improved  algorithm,  due  to  Baker,  keeps  a  list  of all  allocated  objects. 
To  find  the  set  of  unreachable  objects,  which  we  must  return  to  free  space,  we 
take  the  set  difference  of  the  allocated  objects  and  the  reached  objects. 

A l g o r i t hm  7 . 1 4:  Baker's  mark-and-sweep  collector. 

INPUT:  A  root  set  of  objects,  a  heap,  a  free  list  Free,  and  a  list  of  allocated 
objects,  which  we  refer  to  as  Unreached. 

OUTPUT:  Modified  lists  Free  and  Unreached,  which  holds  allocated  objects. 

METHOD:  In  this  algorithm,  shown  in  Fig.  7.25,  the  d a ta  structure  for  garbage 
collection  is  four  lists  named  Free,  Unreached,  Unscanned,  and  Scanned,  each 
of  which  holds  all  the  objects  in  the  state  of  the  same  name.  These  lists  may 
be  implemented  by  embedded,  doubly  linked  lists,  as  was  discussed  in  Sec 
tion  7.4.4.  A  reached-bit  in  objects  is  not  used,  but  we  assume  t h at  each  object 

476 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

contains  bits  telling  which  of  the  four  states  it  is  in.  Initially,  Free  is  t he  free 
list  maintained  by  the  memory  manager,  and  all  allocated  objects  are  on  t he 
Unreached  list  (also  maintained  by  the  memory  manager  as  it  allocates  chunks 
to  objects). 

Scanned  =  0; 

1) 
2)  Unscanned  —  set  of objects  referenced  in  the  root  set; 
3)  w h i le  (Unscanned 7^  0)  { 
4) 
5) 
6) 
7) 

move  object  o  from  Unscanned to  Scanned; 
for  (each  object  o'  referenced  in  0)  { 
if (o'  is in  Unreached) 

move  d  from  Unreached  to  Unscanned; 

} 

} 

8)  Free = Free U  Unreached; 
9)  Unreached  =  Scanned; 

Figure  7.25:  Baker's  mark-and-sweep  algorithm 

Lines  (1)  and  (2)  initialize  Scanned to  be  t he  empty  list,  and  Unscanned to 
have  only  the  objects  reached  from  the  root  set.  Note  t h at  these  objects  were 
presumably  on  t he  list  Unreached  and  must  be  removed  from  there.  Lines  (3) 
through  (7)  are  a  straightforward  implementation  of  the  basic  marking  algo 
rithm,  using  these  lists.  T h at  is,  the  for-loop  of  lines  (5)  through  (7)  examines 
the  references  in  one  unscanned  object  o,  and  if  any  of  those  references  o'  have 
not  yet  been  reached,  line  (7)  changes  o'  to  t he  Unscanned  state. 

At  the  end,  line  (8)  takes  those  objects  t h at  are  still  on  the  Unreached  list 
and  deallocates  their  chunks,  by  moving  t h em  to  t he  Free  list.  Then,  line  (9) 
takes  all  the  objects  in  state  Scanned,  which  are  t he  reachable  objects,  and 
reinitializes  the  Unreached  list  to  be  exactly  those  objects.  Presumably,  as  t he 
memory  manager  creates  new  objects,  those  too  will  be  added  to  t he  Unreached 
• 
list  and  removed  from  the  Free  list. 

In  both  algorithms  of  this  section,  we  have  assumed  t h at  chunks  returned 
to  the  free  list  remain  as  they  were  before  deallocation.  However,  as  discussed 
in  Section  7.4.4,  it  is  often  advantageous  to  combine  adjacent  free  chunks  into 
larger  chunks.  If  we  wish  to  do  so,  then  every  time  we  return  a  chunk  to  the 
free  list,  either  at  line  (10)  of  Fig.  7.21  or  line  (8)  of  Fig.  7.25,  we  examine  t he 
chunks  to  its  left  and  right,  and  merge  if  one  is  free. 

7.6.4  Mark-and-Compact  Garbage  Collectors 

Relocating  collectors  move  reachable  objects  around  in  the  heap  to  eliminate 
memory  fragmentation.  It  is  common  t h at  t he  space  occupied  by  reachable  ob 
jects  is  much  smaller  t h an  the  freed  space.  Thus,  after  identifying  all  t he  holes, 

7.6. 

INTRODUCTION  TO 

TRACE-BASED  COLLECTION 

477 

instead  of freeing  t h em  individually,  one  attractive  alternative  is  to  relocate  all 
the  reachable  objects  into  one  end  of  the  heap,  leaving  the  entire  rest  of  the 
heap  as  one  free  chunk.  After  all,  the  garbage  collector  has  already  analyzed 
every  reference  within  the  reachable  objects,  so  updating  t h em  to  point  to  the 
new  locations  does  not  require  much  more  work.  These,  plus  the  references  in 
t he  root  set,  are  all  t he  references  we  need  to  change. 

Having  all  t he  reachable  objects  in  contiguous  locations  reduces  fragmen 
tation  of  the  memory  space,  making  it  easier  to  house  large  objects.  Also,  by 
making  the  d a ta  occupy  fewer  cache  lines  and  pages,  relocation  improves  a  pro 
gram's  temporal  and  spatial  locality,  since  new  objects  created  at  about  t he 
same  time  are  allocated  nearby  chunks.  Objects  in  nearby  chunks  can  bene 
fit  from  prefetching  if  they  are  used  together.  Further,  the  d a ta  structure  for 
maintaining  free  space  is  simplified;  instead  of a  free  list,  all  we  need  is  a  pointer 
free  to  the  beginning  of  the  one  free  block. 

Relocating  collectors  vary  in  whether  they  relocate  in  place  or  reserve  space 

ahead  of  time  for  the  relocation: 

•  A  mark-and-compact  collector,  described  in  this  section,  compacts  objects 

in  place.  Relocating  in  place  reduces  memory  usage. 

•  T he  more  efficient  and  popular  copying  collector  in  Section  7.6.5  moves 
objects  from  one  region  of  memory  to  another.  Reserving  extra  space  for 
relocation  allows  reachable  objects  to  be  moved  as  they  are  discovered. 

T he  mark-and-compact  collector  in  Algorithm  7.15  has  three  phases: 

1.  First  is  a  marking  phase,  similar  to  t h at  of t he  mark-and-sweep  algorithms 

described  previously. 

2.  Second,  t he  algorithm  scans  the  allocated  section  of  the  heap  and  com 

putes  a  new  address  for  each  of  the  reachable  objects.  New  addresses  are 
assigned from t he  low  end  of t he  heap,  so  there  are  no  holes  between  reach 
able  objects.  T he  new  address  for  each  object  is  recorded  in  a  structure 
called  NewLocation. 

3.  Finally,  the  algorithm  copies  objects  to  their  new  locations,  updating  all 
references  in  the  objects  to  point  to  the  corresponding  new  locations.  The 
needed  addresses  are  found  in  NewLocation. 

A l g o r i t hm  7. 1 5:  A  mark-and-compact  garbage  collector. 

INPUT:  A  root  set  of  objects,  a  heap,  and  free,  a  pointer  marking  the  start  of 
free  space. 

OUTPUT:  The  new  value  of  pointer  free. 

METHOD:  T he  algorithm  is  in  Fig.  7.26;  it  uses  the  following  d a ta  structures: 

1.  An  Unscanned  list,  as  in  Algorithm  7.12. 

478 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

2.  Reached  bits  in  all  objects,  also  as  in  Algorithm  7.12.  To  keep  our  de 

scription  simple,  we  refer  to  objects  as  "reached"  or  "unreached,"  when 
we  mean  t h at  their  reached-bit  is  1  or  0,  respectively.  Initially,  all  objects 
are  unreached. 

3.  The  pointer  free,  which  marks  the  beginning  of  unallocated  space  in  the 

heap. 

4.  The  table  NewLocation.  This  structure  could  be  a  hash  table,  search  tree, 

or  another  structure  t h at  implements  the  two  operations: 

(a)  Set  NewLocation{o)  to  a  new  address  for  object  o. 

(b)  Given  object  o,  get  t he  value  of  NewLocation(o). 

We  shall  not  concern  ourselves  with  the  exact  structure  used,  although 
you  may  assume  t h at  NewLocation  is  a  hash  table,  and  therefore,  t he 
"set"  and  "get"  operations  are  each  performed  in  average  constant  time, 
independent  of  how  many  objects  are  in  t he  heap. 

The  first,  or  marking,  phase  of  lines  (1)  through  (7)  is  essentially  t he  same 
as  the  first  phase  of  Algorithm  7.12.  T he  second  phase,  lines  (8)  through  (12), 
visits  each  chunk  in  t he  allocated  part  of the  heap,  from  the  left,  or  low  end.  As 
a  result,  chunks  are  assigned  new  addresses  t h at  increase  in  the  same  order  as 
their  old  addresses.  This  ordering  is  important,  since  when  we  relocate  objects, 
we  can  do  so  in  a  way  t h at  assures  we  only  move  objects  left,  into  space  t h at 
was  formerly  occupied  by  objects  we  have  moved  already. 

Line  (8)  starts  the  free  pointer  at  t he  low  end  of  t he  heap.  In  this  phase, 
we  use  free  to  indicate  t he  first  available  new  address.  We  create  a  new  address 
only  for  those  objects  o  t h at  are  marked  as  reached.  Object  o  is  given  the  next 
available  address  at  line  (10),  and  at  line  (11)  we  increment  free  by  t he  amount 
of  storage  t h at  object  o  requires,  so  free  again  points  to  the  beginning  of  free 
space. 

In t he  final  phase,  lines  (13)  through  (17),  we  again  visit  the  reached  objects, 
in  the  same  from-the-left  order  as  in  the  second  phase.  Lines  (15)  and  (16) 
replace  all  internal  pointers  of  a  reached  object  o  by  their  proper  new  values, 
using  the  NewLocation  table  to  determine  the  replacement.  Then,  line  (17) 
moves  the  object  o,  with  t he  revised  internal  references,  to  its  new  location. 
Finally,  lines  (18)  and  (19)  retarget  pointers  in  the  elements  of t he  root  set  t h at 
are  not  themselves  heap  objects,  e.g.,  statically  allocated  or  stack-allocated 
objects.  Figure  7.27  suggests  how  the  reachable  objects  (those  t h at  are  not 
shaded)  are  moved  down  the  heap,  while  t he  internal  pointers  are  changed  to 
point  to  the  new  locations  of  t he  reached  objects. 

• 

7.6.5  Copying  collectors 

A  copying  collector  reserves,  ahead  of  time,  space  to  which  the  objects  can 
move,  thus  breaking  the  dependency  between  tracing  and  finding  free  space. 

7.6. 

INTRODUCTION  TO 

TRACE-BASED  COLLECTION 

479 

/*  mark  */ 

1)  Unscanned  —  set  of  objects  referenced  by  t he  root  set; 
2)  w h i le  (Unscanned  ^ 0) { 
3) 
4) 
5) 
6) 
7) 

remove  object  o  from  Unscanned; 
for  (each  object  d  referenced  in  6)  { 
if  (d  is  unreached)  { 

mark  d  as  reached; 
put  d  on  list  Unscanned; 

} 

} 

} 
/*  compute  new  locations  */ 
free  =  starting  location  of  heap  storage; 
for  (each  chunk  of  memory  o  in  t he  heap,  from  the  low  end)  { 

if  (o  is  reached  { 

NewLocation(o)  = 
free; 
free  =  free  +  sizeof(d); 

} 

} 
/*  retarget  references  and  move  reached  objects  */ 
for  (each  chunk  of  memory  o  in  the  heap,  from  the  low  end)  { 

if  (o  is  reached)  { 

for  (each  reference  o.r  in  6) 

o.r  =  NewLocation(o.r); 

copy  o  to  NewLocation(o); 

} 

} 
for  (each  reference  r  in  t he  root  set) 
r  =  NewLocation(r); 

Figure  7.26:  A  Mark-and-Compact  Collector 

8) 
9) 
10) 
11) 
12) 

13) 
14) 
15) 
16) 

17) 

18) 
19) 

T he  memory  space  is  partitioned  into  two  semispaces,  A  and  B.  T he  m u t a t or 
allocates  memory  in  one  semispace,  say  A,  until  it  fills  u p,  at  which  point  t he 
m u t a t or  is  stopped  and  t he  garbage  collector  copies  the  reachable  objects  to 
t he  other  space,  say  B.  When  garbage  collection  completes,  the  roles  of  t he 
semispaces  are  reversed.  The  m u t a t or  is  allowed  to  resume  and  allocate  objects 
in  space  B,  and  t he  next  round  of  garbage  collection  moves  reachable  objects 
to  space  A.  T he  following  algorithm  is  due  to  C.  J.  Cheney. 

A l g o r i t hm  7 . 1 6:  Cheney's  copying  collector. 

INPUT:  A  root  set  of  objects,  and  a  heap  consisting  of  t he  From  semispace, 
containing  allocated  objects,  and  t he  To  semispace,  all  of  which  is  free. 

480 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

Figure  7.27:  Moving  reached  objects  to  t he  front  of  the  heap,  while  preserving 
internal  pointers 

OUTPUT:  At  t he  end,  the  To  semispace  holds  t he  allocated  objects.  A  free 
pointer  indicates  the  start  of  free  space  remaining  in  t he  To  semispace.  The 
From  semispace  is  completely  free. 

METHOD:  The  algorithm  is  shown  in  Fig.  7.28.  Cheney's  algorithm  finds 
reachable  objects  in  the  From  semispace  and  copies  them,  as  soon  as  they  are 
reached,  to  t he  To  semispace.  This  placement  groups  related  objects  together 
and  may  improve  spatial  locality. 

Before  examining  the  algorithm  itself,  which  is  the  function  CopyingCollec 
tor  m.  Fig.  7.28,  consider  the  auxiliary  function  LookupNewLocation  in  lines  (11) 
through  (16).  This  function  takes  an  object  o  and  finds  a  new  location  for  it 
in  the  To  space  if  o  has  no  location  there  yet.  All  new  locations  are  recorded 
in  a  structure  NewLocation,  and  a  value  of  N U LL  indicates  o  has  no  assigned 
location.5  As  in  Algorithm  7.15,  t he  exact  form  of  structure  NewLocation  may 
vary,  but  it  is  fine  to  assume  t h at  it  is  a  hash  table. 

If we  find  at  line  (12)  t h at  o  has  no  location,  then  it  is  assigned t he  beginning 
of  the  free  space  within  t he  To  semispace,  at  line  (13).  Line  (14)  increments 
t he  free  pointer  by  the  amount  of  space  taken  by  o,  and  at  line  (15)  we  copy  o 
from  the  From  space  to  the  To  space.  Thus,  the  movement  of objects  from  one 
semispace  to  t he  other  occurs  as  a  side  effect,  the  first  time  we  look  up  t he  new 
location  for  the  object.  Regardless  of  whether  the  location  of  o  was  or  was  not 
previously  established,  line  (16)  returns  t he  location  of  o  in  t he  To  space. 

Now,  we  can  consider  the  algorithm  itself.  Line  (2)  establishes  t h at  none  of 
the  objects  in  the  From  space  have  new  addresses  yet.  At  line  (3),  we  initialize 
two  pointers,  unscanned  and  free,  to  the  beginning  of t he  To  semispace.  Pointer 
free  will  always  indicate  the  beginning  of  free  space  within  t he  To  space.  As  we 
add  objects  to  t he  To  space,  those  with  addresses  below  unscanned  will  be  in 
the  Scanned  state,  while  those  between  unscanned  and  free  are  in  t he  Unscanned 

5 In  a typical  data  structure,  such  as  a  hash  table,  if o  is  not  assigned  a  location,  then  there 

simply  would  be  no  mention  of  it  in  the  structure. 

7.6. 

INTRODUCTION  TO 

TRACE-BASED  COLLECTION 

481 

1) 
2) 
3) 
4) 
5) 
6) 
7) 
8) 
9) 
10) 

11) 
12) 
13) 
14) 
15) 

16) 

CopyingCollector  ()  { 

for  (all  objects  o  in  From  space)  NewLocation(o)  = N U L L; 
unscanned  —  free  =  starting  address  of  To  space; 
for  (each  reference  r  in  t he  root  set) 

replace 

r  with  LookupNewLocation(r); 

w h i le  (unscanned  ^  free)  { 

o  —  object  at  location  unscanned] 
for  (each  reference  o.r  within  o) 

o.r  = 

LookupNewLocation(o.r); 

unscanned  —  unscanned  +  sizeof(o); 

} 

} 

/*  Look  up  the  new  location  for  object  if  it  has  been  moved.  */ 
/*  Place  object  in  Unscanned  state  otherwise.  */ 

LookupNewLocation(o)  { 

if  (NewLocation(o)  =  N U L L)  { 

NewLocation(o)  —  free; 
free  =  free  +  sizeof(o); 
copy  o  to  NewLocation(o); 

} 
r e t u rn  NewLocation(o); 

} 

Figure  7.28:  A  Copying  Garbage  Collector 

state.  Thus,  free  always  leads  unscanned,  and  when  the  latter  catches  up  to 
the  former,  there  are  no  more  Unscanned  objects,  and  we  are  done  with  the 
garbage  collection.  Notice  t h at  we  do  our  work  within  the  To  space,  although 
all  references  within  objects  examined  at  line  (8)  lead  us  back  to  the  From 
space. 

Lines  (4)  and  (5)  handle  t he  objects  reachable  from  t he  root  set.  Note  t h at 
as  a  side  effect,  some  of  t he  calls  to  LookupNewLocation  at  line  (5)  will  increase 
free,  as  chunks  for  these  objects  are  allocated  within  To.  Thus,  the  loop  of lines 
(6)  through  (10)  will  be  entered  the  first  time  it  is  reached,  unless  there  are  no 
objects  referenced  by  t he  root  set  (in  which  case  t he  entire  heap  is  garbage). 
This  loop  then  scans  each  of t he  objects  t h at  has  been  added  to  To  and  is  in  t he 
Unscanned  state.  Line  (7)  takes  t he  next  unscanned  object,  o.  Then,  at  lines 
(8)  and  (9),  each  reference  within  o  is  translated  from  its  value  in  t he  From 
semispace  to  its  value  in  the  To  semispace.  Notice  t h a t,  as  a  side  effect,  if  a 
reference  within  o  is  to  an  object  we  have  not  reached  previously,  then  t he  call 
to  LookupNewLocation  at  line  (9)  creates  space  for  t h at  object  in  t he  To  space 
and  moves  t he  object  there.  Finally,  line  (10)  increments  unscanned  to  point 
to  t he  next  object,  just  beyond  o  in  the  To  space. 

• 

482 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

7.6.6  Comparing  Costs 

Cheney's  algorithm  has  t he  advantage  t h at  it  does  not  touch  any  of  t he  un 
reachable  objects.  On  the  other  hand,  a  copying  garbage  collector  must  move 
the  contents  of all  t he  reachable  objects.  This  process  is  especially  expensive  for 
large  objects  and  for  long-lived  objects  t h at  survive  multiple  rounds  of  garbage 
collection.  We  can  summarize  the  running  time  of  each  of  the  four  algorithms 
described  in  this  section,  as  follows.  Each  estimate  ignores t he  cost  of processing 
the  root  set. 

•  Basic  Mark-and-Sweep  (Algorithm  7.12):  Proportional  to  the  number  of 

chunks  in  the  heap. 

•  Baker's  Mark-and-Sweep  (Algorithm  7.14):  Proportional  to  t he  number 

of  reached  objects. 

»  Basic  Mark-and-Compact  (Algorithm  7.15):  Proportional  to  t he  number 

of  chunks  in  t he  heap  plus  the  total  size  of  the  reached  objects. 

•  Cheney's  Copying  Collector  (Algorithm  7.16):  Proportional  to  t he  total 

size  of  t he  reached  objects. 

7.6.7  Exercises  for  Section  7.6 

E x e r c i se  7 . 6 . 1:  Show  the  steps  of  a  mark-and-sweep  garbage  collector  on 

a)  Fig.  7.19  with  t he  pointer  A  ->•  B  deleted. 

b)  Fig.  7.19  with  the  pointer  A  ->  C  deleted. 

c)  Fig.  7.20  with  the  pointer  A-t  D  deleted. 

d)  Fig.  7.20  with  t he  object  B  deleted. 

E x e r c i se  7 . 6 . 2:  The  Baker  mark-and-sweep  algorithm  moves  objects  among 
four  lists:  Free,  Unreached,  Unscanned,  and  Scanned.  For  each  of  t he  object 
networks  of  Exercise  7.6.1,  indicate  for  each  object  t he  sequence  of  lists  on 
which  it  finds  itself from  just  before  garbage  collection  begins  until  just  after  it 
finishes. 

E x e r c i se  7 . 6 . 3:  Suppose  we  perform  a  mark-and-compact  garbage  collection 
on  each  of  the  networks  of  Exercise  7.6.1.  Also,  suppose  t h at 

i.  Each  object  has  size  100  bytes,  and 

ii.  Initially,  t he  nine  objects  in  the  heap  are  arranged  in  alphabetical  order, 

starting  at  byte  0  of  t he  heap. 

W h at  is  the  address  of  each  object  after  garbage  collection? 

7.7. 

SHORT-PAUSE  GARBAGE  COLLECTION 

483 

E x e r c i se  7.6.4:  Suppose  we  execute  Cheney's  copying  garbage  collection  al 
gorithm  on  each  of  t he  networks  of  Exercise  7.6.1.  Also,  suppose  t h at 

i.  Each  object  has  size  100  bytes, 

ii.  T he  unscanned  list  is  managed  as  a  queue,  and  when  an  object  has  more 
t h an  one  pointer,  the  reached  objects  are  added  to  the  queue  in  alpha 
betical  order,  and 

Hi.  T he  From  semispace  starts  at  location  0,  and  the  To  semispace  starts  at 

location  10,000. 

W h at  is  the  value  of  NewLocation(o)  for  each  object  o  t h at  remains  after  garbage 
collection? 

7.7  Short-Pause  Garbage  Collection 

Simple  trace-based  collectors  do  stop-the-world-style  garbage  collection,  which 
may  introduce  long  pauses  into  the  execution  of  user  programs.  We  can  reduce 
the  length  of  the  pauses  by  performing  garbage  collection  one  part  at  a  time. 
We  can  divide  the  work  in  time,  by  interleaving  garbage  collection  with  the 
mutation,  or  we  can  divide  the  work  in  space  by  collecting  a  subset  of  the 
garbage  at  a  time.  The  former  is  known  as 
incremental  collection  and  t he 
latter  is  known  as  partial  collection. 

An  incremental  collector  breaks  up  the  reachability  analysis  into  smaller 
units,  allowing  the  m u t a t or  to  run  between  these  execution  units.  T he  reachable 
set  changes  as  the  m u t a t or  executes,  so  incremental  collection  is  complex.  As 
we  shall  see  in  Section  7.7.1,  finding  a  slightly  conservative  answer  can  make 
tracing  more  efficient. 

T he  best  known  of  partial-collection  algorithms  is  generational  garbage  col 
lection]  it  partitions  objects  according  to  how  long  they  have  been  allocated 
and  collects  the  newly  created  objects  more  often  because  they  tend  to  have  a 
shorter  lifetime.  An  alternative  algorithm,  the  train  algorithm,  also  collects  a 
subset  of  garbage  at  a  time,  and  is  best  applied  to  more  m a t u re  objects.  These 
two  algorithms  can  be  used  together  to  create  a  partial  collector  t h at  handles 
younger  and  older  objects  differently.  We  discuss  the  basic  algorithm  behind 
partial  collection  in  Section  7.7.3,  and  then  describe  in  more  detail  how  the 
generational  and  train  algorithms  work. 

Ideas  from  both  incremental  and  partial  collection  can  be  adapted  to  cre 
ate  an  algorithm  t h at  collects  objects  in  parallel  on  a  multiprocessor;  see  Sec 
tion  7.8.1. 

7.7.1 

Incremental  Garbage  Collection 

Incremental  collectors  are  conservative.  While  a  garbage  collector  must  not 
collect  objects  t h at  are  not  garbage,  it  does  not  have  to  collect  all  the  garbage 

484 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

in  each  round.  We  refer  to  the  garbage  left  behind  after  collection  as  floating 
garbage.  Of  course  it  is  desirable  to  minimize  floating  garbage.  In  particular, 
an  incremental  collector  should  not  leave  behind  any  garbage  t h at  was  not 
If  we  can  be  sure  of  such 
reachable  at  t he  beginning  of  a  collection  cycle. 
a  collection  guarantee,  then  any  garbage  not  collected  in  one  round  will  be 
collected  in  the  next,  and  no  memory  is  leaked  because  of  this  approach  to 
garbage  collection. 

In  other  words,  incremental  collectors  play  it  safe  by  overestimating  the  set 
of reachable  objects.  They  first  process  the  program's  root  set  atomically,  with 
out  interference  from  the  mutator.  After  finding  the  initial  set  of  unscanned 
objects,  the  m u t a t o r 's  actions  are  interleaved  with  the  tracing  step.  During  this 
period,  any  of  the  m u t a t o r 's  actions  t h at  may  change  reachability  are  recorded 
succinctly,  in  a  side  table,  so  t h at  the  collector  can  make  the  necessary  ad 
justments  when  it  resumes  execution.  If space  is  exhausted  before  tracing  com 
pletes,  the  collector  completes  the  tracing  process,  without  allowing  the  m u t a t or 
to  execute.  In  any  event,  when  tracing  is  done,  space  is  reclaimed  atomically. 

P r e c i s i on  of  I n c r e m e n t al  C o l l e c t i on 

Once  an  object  becomes  unreachable,  it  is  not  possible  for  the  object  to  become 
reachable  again.  Thus,  as  garbage  collection  and  mutation  proceed,  t he  set  of 
reachable  objects  can  only 

1.  Grow  due  to  new  objects  allocated  after  garbage  collection  starts,  and 

2.  Shrink  by  losing  references  to  allocated  objects. 

Let  the  set  of  reachable  objects  at  t he  beginning  of  garbage  collection  be  R; 
let  New  be  the  set  of  allocated  objects  during  garbage  collection,  and  let  Lost 
be  t he  set  of  objects  t h at  have  become  unreachable  due  to  lost  references  since 
tracing  began.  The  set  of  objects  reachable  when  tracing  completes  is 

(R  U  New)  -  Lost. 

It  is  expensive  to  reestablish  an  object's  reachability  every  time  a  m u t a t or 
loses  a  reference  to  the  object,  so  incremental  collectors  do  not  a t t e m pt  to 
collect  all  the  garbage  at  t he  end  of tracing.  Any  garbage  left  behind  —  floating 
garbage  —  should  be  a  subset  of  the  Lost  objects.  Expressed  formally,  t he  set 
S  of  objects  found  by  tracing  must  satisfy 

(R  U  New)  -  Lost  C 5  C  (R  U  New) 

S i m p le  I n c r e m e n t al  T r a c i ng 

We  first  describe  a  straightforward  tracing  algorithm  t h at  finds  the  upper  bound 
R  U  New.  T he  behavior  of the  m u t a t or  is  modified  during  the  tracing  as  follows: 

7.7. 

SHORT-PAUSE  GARBAGE  COLLECTION 

485 

•  All  references  t h at  existed  before  garbage  collection  are  preserved;  t h at  is, 
before  t he  m u t a t or  overwrites  a  reference,  its  old  value  is  remembered  and 
treated  like  an  additional  unscanned  object  containing  just  t h at  reference. 

•  All  objects  created  are  considered  reachable  immediately  and  are  placed 

in  the  Unscanned  state. 

This  scheme  is  conservative  but  correct,  because  it  finds  R,  the  set  of all  the 
objects  reachable  before  garbage  collection,  plus  New,  the  set  of  all  the  newly 
allocated  objects.  However,  the  cost  is  high,  because  the  algorithm  intercepts 
all  write  operations  and  remembers  all  the  overwritten  references.  Some  of this 
work  is  unnecessary  because  it  may  involve  objects  t h at  are  unreachable  at  the 
end  of  garbage  collection.  We  could  avoid  some  of  this  work  and  also  improve 
the  algorithm's  precision  if  we  could  detect  when  t he  overwritten  references 
point  to  objects  t h at  are  unreachable  when  this  round  of  garbage  collection 
ends.  The  next  algorithm  goes  fairly  far  in  these  two  directions. 

7.7.2 

Incremental  Reachability  Analysis 

If  we  interleave  the  mutator  with  a  basic  tracing  algorithm,  such  as  Algo 
rithm  7.12,  then  some  reachable  objects  may  be  misclassified  as  unreachable. 
The  problem  is  t h at  the  actions  of  the  mutator  can  violate  a  key  invariant  of 
the  algorithm;  namely,  a  Scanned  object  can  only  contain  references  to  other 
Scanned  or  Unscanned  objects,  never  to  Unreached  objects.  Consider  the  fol 
lowing  scenario: 

1.  The  garbage  collector  finds  object  o\  reachable  and  scans  the  pointers 

within  o\,  thereby  putting  0\  in  t he  Scanned  state. 

2.  The  m u t a t or  stores  a  reference  to  an  Unreached  (but  reachable)  object  o 
It  does  so  by  copying  a  reference  to  o  from 

into  t he  Scanned  object  o\. 
an  object  o2  t h at  is  currently  in  the  Unreached  or  Unscanned  state. 

3.  T he  m u t a t or  loses  t he  reference  to  o  in  object  o2.  It  may  have  overwrit 
ten  o2's  reference  to  o  before  the  reference  is  scanned,  or  o2  may  have 
become  unreachable  and  never  have  reached  the  Unscanned  state  to  have 
its  references  scanned. 

Now,  o  is  reachable  through  object  0\,  but  the  garbage  collector  may  have  seen 
neither  t he  reference  to  o  in  oi  nor  the  reference  to  o  in  o2 • 

T he  key  to  a  more  precise,  yet  correct,  incremental  trace  is  t h at  we  must 
note  all  copies  of  references  to  currently  unreached  objects  from  an  object  t h at 
has  not  been  scanned  to  one  t h at  has.  To  intercept  problematic  transfers  of 
references,  the  algorithm  can  modify  t he  m u t a t o r 's  action  during  tracing  in  any 
of  the  following  ways: 

486 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

•  Write  Barriers. 

Intercept  writes  of  references  into  a  Scanned  object  ox, 
when  the  reference  is  to  an  Unreached  object  o. 
In  this  case,  classify  o 
as  reachable  and  place  it  in  the  Unscanned  set.  Alternatively,  place  the 
written  object  o\  back  in  the  Unscanned  set  so  we  can  rescan  it. 

•  Read  Barriers. 

Intercept  the  reads  of  references  in  Unreached  or  Un 
scanned  objects.  Whenever  the  m u t a t or  reads  a  reference  to  an  object  o 
from  an  object  in  either  the  Unreached  or  Unscanned  state,  classify  o  as 
reachable  and  place  it  in  the  Unscanned  set. 

•  Transfer  Barriers. 

Intercept  the  loss  of  the  original  reference  in  an  Un 
reached  or  Unscanned  object.  Whenever  the  m u t a t or  overwrites  a  ref 
erence  in  an  Unreached  or  Unscanned  object,  save  the  reference  being 
overwritten,  classify  it  as  reachable,  and  place  t he  reference  itself  in  the 
Unscanned  set. 

None  of the  options  above  finds  the  smallest  set  of reachable  objects.  If  the 
tracing  process  determines  an  object  to  be  reachable,  it  stays  reachable  even 
though  all  references  to  it  are  overwritten  before  tracing  completes.  T h at  is, 
the  set  of reachable  objects  found  is  between  (R  U  New)  —  Lost  and  (R  U  New). 
Write  barriers  are  t he  most  efficient  of  the  options  outlined  above.  Read 
barriers  are  more  expensive  because  typically  there  are  many  more  reads  t h an 
there  are  writes.  Transfer  barriers  are  not  competitive;  because  many  objects 
"die  young,"  this  approach  would  retain  many  unreachable  objects. 

I m p l e m e n t i ng  W r i te  B a r r i e rs 

We  can  implement  write  barriers  in  two  ways.  T he  first  approach  is  to  re 
member,  during  a  mutation  phase,  all  new  references  written  into  the  Scanned 
objects.  We  can  place  all  these  references  in  a  list;  t he  size  of the  list  is  propor 
tional  to  t he  number  of  write  operations  to  Scanned  objects,  unless  duplicates 
are  removed  from  the  list.  Note  t h at  references  on  the  list  may  later  be  over 
written  themselves  and  potentially  could  be  ignored. 

T he  second,  more  efficient  approach  is  to  remember  the  locations  where  the 
writes  occur.  We  may  remember  t h em  as  a  list  of  locations  written,  possibly 
with  duplicates  eliminated.  Note  it  is  not  important  t h at  we  pinpoint  the 
exact  locations  written,  as  long  as  all  t he  locations  t h at  have  been  written  are 
rescanned.  Thus,  there  are  several  techniques  t h at  allow  us  to  remember  less 
detail  about  exactly  where  the  rewritten  locations  are. 

•  Instead  of  remembering  the  exact  address  or  the  object  and  field  t h at  is 
written,  we  can  remember  just  the  objects  t h at  hold  the  written  fields. 

•  We  can  divide  the  address  space  into  fixed-size  blocks,  known  as  cards, 
and  use  a  bit  array  to  remember  the  cards  t h at  have  been  written  into. 

7.7. 

SHORT-PAUSE  GARBAGE  COLLECTION 

487 

•  We  can  choose  to  remember  t he  pages  t h at  contain  t he  written  locations. 
We  can  simply  protect  the  pages  containing  Scanned  objects.  Then,  any 
writes  into  Scanned  objects  will  be  detected  without  executing  any  ex 
plicit  instructions,  because  they  will  cause  a  protection  violation,  and  the 
operating  system  will  raise  a  program  exception. 

In  general,  by  coarsening  the  granularity  at  which  we  remember  the  written 
locations,  less  storage  is  needed,  at  t he  expense  of  increasing  the  amount  of 
rescanning  performed.  In  t he  first  scheme,  all  references  in  t he  modified  objects 
will  have  to  be  rescanned,  regardless  of  which  reference  was  actually  modified. 
In  the  last  two  schemes,  all  reachable  objects  in  the  modified  cards  or  modified 
pages  need  to  be  rescanned  at  the  end  of  the  tracing  process. 

C o m b i n i ng  I n c r e m e n t al  a nd  C o p y i ng  T e c h n i q u es 

T he  above  methods  are  sufficient  for  mark-and-sweep  garbage  collection.  Copy 
ing  collection  is  slightly  more  complicated,  because  of  its  interaction  with  the 
mutator.  Objects  in  the  Scanned  or  Unscanned  states  have  two  addresses,  one 
in  the  From  semispace  and  one  in  the  To  semispace.  As  in  Algorithm  7.16,  we 
must  keep  a  mapping  from  the  old  address  of  an  object  to  its  relocated  address. 
There  are  two  choices  for  how  we  u p d a te  the  references.  First,  we  can  have 
the  m u t a t or  make  all  the  changes  in  the  From  space,  and  only  at  the  end  of 
garbage  collection  do  we  u p d a te  all  the  pointers  and  copy  all  the  contents  over 
to  t he  To  space.  Second,  we  can  instead  make  changes  to  the  representation  in 
t he  To  space.  Whenever  t he  m u t a t or  dereferences  a  pointer  to  the  From  space, 
the  pointer  is  translated  to  a  new  location  in  t he  To  space  if  one  exists.  All  the 
pointers  need  to  be  translated  to  point  to  t he  To  space  in  t he  end. 

7.7.3  Partial-Collection  Basics 

T he  fundamental  fact  is  t h at  objects  typically  "die  young."  It  has  been  found 
t h at  usually  between  80%  and  98%  of  all  newly  allocated  objects  die  within  a 
few  million  instructions,  or  before  another  megabyte  has  been  allocated.  T h at 
is,  objects  often  become  unreachable  before  any  garbage  collection  is  invoked. 
Thus,  is  it  quite  cost  effective  to  garbage  collect  new  objects  frequently. 

Yet,  objects  t h at  survive  a  collection  once  are  likely  to  survive  many  more 
collections.  W i th  the  garbage  collectors  described  so  far,  t he  same  m a t u re 
objects  will  be  found  to  be  reachable  over  and  over  again  and,  in  t he  case 
of  copying  collectors,  copied  over  and  over  again,  in  every  round  of  garbage 
collection.  Generational  garbage  collection  works  most  frequently  on  the  area 
of  the  heap  t h at  contains  the  youngest  objects,  so  it  tends  to  collect  a  lot  of 
garbage  for  relatively  little  work.  The  train  algorithm,  on  the  other  hand,  does 
not  spend  a  large  proportion  of  time  on  young  objects,  but  it  does  limit  the 
pauses  due  to  garbage  collection.  Thus,  a  good  combination  of  strategies  is 
to  use  generational  collection  for  young  objects,  and  once  an  object  becomes 

488 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

sufficiently  mature,  to  "promote"  it  to  a  separate  heap  t h at  is  managed  by  t he 
train  algorithm. 

We  refer  to  the  set  of objects  to  be  collected  on  one  round  of partial  collection 
as  the  target  set  and  the  rest  of  t he  objects  as  the  stable  set.  Ideally,  a  partial 
collector  should  reclaim  all  objects  in  t he  target  set  t h at  are  unreachable  from 
the  program's  root  set.  However,  doing  so  would  require  tracing  all  objects, 
which  is  what  we  t ry  to  avoid  in  the  first  place. 
Instead,  partial  collectors 
conservatively  reclaim  only  those  objects  t h at  cannot  be  reached  through  either 
the  root  set  of  the  program  or  t he  stable  set.  Since  some  objects  in  t he  stable 
set  may  themselves  be  unreachable,  it  is  possible  t h at  we  shall  treat  as  reachable 
some  objects  in  the  target  set  t h at  really  have  no  p a th  from  the  root  set. 

We  can  a d a pt  t he  garbage  collectors  described  in  Sections  7.6.1  and  7.6.4  to 
work  in  a  partial  manner  by  changing  the  definition  of the  "root  set."  Instead  of 
referring  to  just  the  objects  held  in  t he  registers,  stack  and  global  variables,  t he 
root  set  now  also  includes  all  the  objects  in  the  stable  set  t h at  point  to  objects 
in  the  target  set.  References  from  target  objects  to  other  target  objects  are 
traced  as  before  to  find  all  the  reachable  objects.  We  can  ignore  all  pointers  to 
stable  objects,  because  these  objects  are  all  considered  reachable  in  this  round 
of  partial  collection. 

To  identify  those  stable  objects  t h at  reference  target  objects,  we  can  adopt 
techniques  similar  to  those  used  in  incremental  garbage  collection.  In  incremen 
tal  collection,  we  need  to  remember  all  t he  writes  of  references  from  scanned 
objects  to  unreached  objects  during  t he  tracing  process.  Here  we  need  to  re 
member  all  t he  writes  of  references  from  t he  stable  objects  to  t he  target  objects 
throughout  t he  m u t a t o r 's  execution.  Whenever  t he  m u t a t or  stores  into  a  sta 
ble  object  a  reference  to  an  object  in  t he  target  set,  we  remember  either  the 
reference  or  the  location  of  t he  write.  We  refer  to  t he  set  of  objects  holding 
references  from  t he  stable  to  t he  target  objects  as  t he  remembered  set  for  this 
set  of  target  objects.  As  discussed  in  Section  7.7.2,  we  can  compress  t he  repre 
sentation  of  a  remembered  set  by  recording  only  the  card  or  page  in  which  the 
written  object  is  found. 

Partial  garbage  collectors  are  often  implemented  as  copying  garbage  collec 
tors.  Noncopying  collectors  can  also  be  implemented  by  using  linked  lists  to 
keep  track  of the  reachable  objects.  T he  "generational"  scheme  described  below 
is  an  example  of  how  copying  may  be  combined  with  partial  collection. 

7.7.4  Generational  Garbage  Collection 

Generational  garbage  collection  is  an  effective  way  to  exploit  the  property  t h at 
most  objects  die  young.  T he  heap  storage  in  generational  garbage  collection  is 
separated  into  a  series  of  partitions.  We  shall  use  the  convention  of  numbering 
t h em  0 , 1 , 2 , . ..  , n,  with  t he  lower-numbered  partitions  holding  t he  younger 
objects.  Objects  are  first  created  in  partition  0.  When  this  partition  fills  up, 
it  is  garbage  collected,  and  its  reachable  objects  are  moved  into  partition  1. 
Now,  with  partition  0  empty  again,  we  resume  allocating  new  objects  in  t h at 

7.7. 

SHORT-PAUSE  GARBAGE  COLLECTION 

489 

partition.  W h en  partition  0  again  fills,6  it  is  garbage  collected  and  its  reachable 
objects  copied  into  partition  1,  where  they  join  the  previously  copied  objects. 
This  p a t t e rn  repeats  until  partition  1  also  fills  up,  at  which  point  garbage 
collection  is  applied  to  partitions  0  and  1. 

In  general,  each  round  of  garbage  collection  is  applied  to  all  partitions  num 
bered  i  or  below,  for  some  i;  the  proper  i  to  choose  is  the  highest-numbered 
partition  t h at  is  currently  full.  Each  time  an  object  survives  a  collection  (i.e., 
it  is  found  to  be  reachable),  it  is  promoted  to  t he  next  higher  partition  from 
the  one  it  occupies,  until  it  reaches  the  oldest  partition,  the  one  numbered  n. 

Using  the  terminology  introduced  in  Section  7.7.3,  when  partitions  i  and 
below  are  garbage  collected,  t he  partitions  from  0  through  i  make  up  the  target 
set,  and  all  partitions  above  i  comprise  the  stable  set.  To  support  finding  root 
sets  for  all  possible  partial  collections,  we  keep  for  each  partition  i  a  remembered 
set,  consisting  of  all  the  objects  in  partitions  above  i  t h at  point  to  objects  in  set 
i.  T he  root  set  for  a  partial  collection  invoked  on  set  i  includes  t he  remembered 
sets  for  partition  i  and  below. 

In  this  scheme,  all  partitions  below  i  are  collected  whenever  we  collect  i. 

There  are  two  reasons  for  this  policy: 

1.  Since  younger  generations  contain  more  garbage  and  are  collected  more 
often  anyway,  we  may  as  well  collect  them  along  with  an  older  generation. 

2.  Following  this  strategy,  we  need  to  remember  only  the  references  pointing 
from  an  older  generation  to  a  newer  generation.  T h at  is,  neither  writes 
to  objects  in  the  youngest  generation  nor  promoting  objects  to  the  next 
generation  causes  updates  to  any  remembered  set.  If  we  were  to  collect 
a  partition  without  a  younger  one,  t he  younger  generation  would  become 
part  of  the  stable  set,  and  we  would  have  to  remember  references  t h at 
point  from  younger  to  older  generations  as  well. 

In  summary,  this  scheme  collects  younger  generations  more  often,  and  col 
lections  of  these  generations  are  particularly  cost  effective,  since  "objects  die 
young."  Garbage  collection  of  older  generations  takes  more  time,  since  it  in 
cludes  t he  collection  of  all  t he  younger  generations  and  contains  proportionally 
less  garbage.  Nonetheless,  older  generations  do  need  to  be  collected  once  in 
a  while  to  remove  unreachable  objects.  The  oldest  generation  holds  the  most 
m a t u re  objects;  its  collection  is  expensive  because  it  is  equivalent  to  a full  collec 
tion.  T h at  is,  generational  collectors  occasionally  require  t h at  t he  full  tracing 
step  be  performed  and  therefore  can  introduce  long  pauses  into  a  program's 
execution.  An  alternative  for  handling  m a t u re  objects  only  is  discussed  next. 

technically,  partitions  do  not  "fill,"  since  they  can  be  expanded  with  additional  disk 
blocks  by  the  memory  manager,  if desired.  However,  there  is  normally  a  limit  on  the  size  of a 
partition,  other  than  the  last.  We  shall  refer  to  reaching  this  limit  as  "filling"  the  partition. 

490 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

7.7.5  The  Train  Algorithm 

While  the  generational  approach  is  very  efficient  for  the  handling  of  immature 
objects,  it  is  less  efficient  for  the  m a t u re  objects,  since  m a t u re  objects  are  moved 
every  time  there  is  a  collection  involving  them,  and  they  are  quite  unlikely  to 
be  garbage.  A  different  approach  to  incremental  collection,  called  the  train 
algorithm,  was  developed  to  improve  the  handling  of  m a t u re  objects.  It  can  be 
used  for  collecting  all  garbage,  but  it  is  probably  better  to  use  the  generational 
approach  for  immature  objects  and,  only  after  they  have  survived  a  few  rounds 
of collection,  "promote"  t h em  to  another  heap,  managed  by  the  train  algorithm. 
Another  advantage  to  the  train  algorithm  is  t h at  we  never  have  to  do  a  complete 
garbage  collection,  as  we  do  occasionally  for  generational  garbage  collection. 

To  motivate  the  train  algorithm,  let  us  look  at  a  simple  example  of why  it  is 
necessary,  in  t he  generational  approach,  to  have  occasional  all-inclusive  rounds 
of  garbage  collection.  Figure  7.29  shows  two  mutually  linked  objects  in  two 
partitions  i  and  j,  where  j  >  i.  Since  both  objects  have  pointers  from  outside 
their  partition,  a  collection  of  only  partition  i  or  only  partition  j  could  never 
collect  either  of  these  objects.  Yet  they  may  in  fact  be  part  of  a  cyclic  garbage 
structure  with  no  links  from  the  outside.  In  general,  the  "links"  between  the 
objects  shown  may  involve  many  objects  and  long  chains  of  references. 

Figure  7.29:  A  cyclic  structure  across  partitions  t h at  may  be  cyclic  garbage 

In  generational  garbage  collection,  we  eventually  collect  partition  j,  and 
since  i  <  j,  we  also  collect  i  at  t h at  time.  Then,  t he  cyclic  structure  will  be 
completely  contained  in  t he  portion  of  the  heap  being  collected,  and  we  can 
tell  if  it  truly  is  garbage.  However,  if  we  never  have  a  round  of  collection  t h at 
includes  both  i  and  j,  we  would  have  a  problem  with  cyclic  garbage,  just  as  we 
did  with  reference  counting  for  garbage  collection. 

The  train  algorithm  uses  fixed-length  partitions,  called  cars;  a  car  might  be 
a  single  disk  block,  provided  there  are  no  objects  larger  t h an  disk  blocks,  or  t he 
car  size  could  be  larger,  but  it  is  fixed  once  and  for  all.  Cars  are  organized  into 
trains.  There  is  no  limit  to  the  number  of  cars  in  a  train,  and  no  limit  to  t he 
number  of  trains.  There  is  a  lexicographic  order  to  cars:  first  order  by  train 
number,  and  within  a  train,  order  by  car  number,  as  in  Fig.  7.30. 

There  are  two  ways  t h at  garbage  is  collected  by  t he  train  algorithm: 

•  The  first  car  in  lexicographic  order  (that  is,  the  first  remaining  car  of  the 
first  remaining  train)  is  collected  in  one  incremental  garbage-collection 
step.  This  step  is  similar  to  collection  of  t he  first  partition  in  t he  gener 
ational  algorithm,  since  we  maintain  a  "remembered"  list  of  all  pointers 

7.7. 

SHORT-PAUSE  GARBAGE  COLLECTION 

491 

Train  1 

car  11 

car  12 

Train  2 

car  21 

car  22 

car  23 

car  24 

Train  3 

car  31 

car  32 

car  33 

Figure  7.30:  Organization  of  t he  heap  for  t he  train  algorithm 

from  outside  t he  car.  Here,  we  identify  objects  with  no  references  at  all, 
as  well  as  garbage  cycles  t h at  are  contained  completely  within  this  car. 
Reachable  objects  in  the  car  are  always  moved  to  some  other  car,  so  each 
garbage-collected  car  becomes  empty  and  can  be  removed  from  the  train. 

•  Sometimes,  the  first  train  has  no  external  references.  T h at  is,  there  are 
no  pointers  from  the  root  set  to  any  car  of the  train,  and  the  remembered 
sets  for  the  cars  contain  only  references  from  other  cars  in  t he  train,  not 
from  other  trains.  In  this  situation,  the  train  is  a  huge  collection  of  cyclic 
garbage,  and  we  delete  the  entire  train. 

R e m e m b e r ed  S e ts 

We  now  give  the  details  of  the  train  algorithm.  Each  car  has  a  remembered  set 
consisting  of  all  references  to  objects  in  the  car  from 

a)  Objects  in  higher-numbered  cars  of  the  same  train,  and 

b)  Objects  in  higher-numbered  trains. 

In  addition,  each  train  has  a  remembered  set  consisting  of  all  references  from 
higher-numbered  trains.  T h at  is,  the  remembered  set  for  a  train  is  t he  union  of 
the  remembered  sets  for  its  cars,  except  for  those  references  t h at  are  internal 
to  the  train. 
It  is  thus  possible  to  represent  both  kinds  of  remembered  sets 
by  dividing  t he  remembered  sets  for  t he  cars  into  "internal"  (same  train)  and 
"external"  (other  trains)  portions. 

Note  t h at  references  to  objects  can  come  from  anywhere,  not  just  from 
lexicographically  higher  cars.  However,  the  two  garbage-collection  processes 
deal  with  the  first  car  of  the  first  train,  and  t he  entire  first  train,  respectively. 
Thus,  when  it  is  time  to  use  the  remembered  sets  in  a  garbage  collection,  there 
is  nothing  earlier  from  which  references  could  come,  and  therefore  there  is  no 
point  in  remembering  references  to  higher  cars  at  any  time.  We  must  be  careful, 
of  course,  to  manage  the  remembered  sets  properly,  changing  t h em  whenever 
the  m u t a t or  modifies  references  in  any  object. 

492 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

M a n a g i ng  Trains 

Our  objective  is  to  draw  out  of  the  first  train  all  objects  t h at  are  not  cyclic 
garbage.  Then,  the  first  train  either  becomes  nothing  but  cyclic  garbage  and  is 
therefore  collected  at  the  next  round  of  garbage  collection,  or  if  the  garbage  is 
not  cyclic,  then  its  cars  may  be  collected  one  at  a  time. 

We  therefore  need  to  start  new  trains  occasionally,  even  though  there  is  no 
limit  on  the  number  of  cars  in  one  train,  and  we  could  in  principle  simply  add 
new  cars  to  a  single  train,  every  time  we  needed  more  space.  For  example,  we 
could  start  a  new  train  after  every  k  object  creations,  for  some  k.  T h at  is,  in 
general,  a  new  object  is  placed  in  the  last  car  of t he  last  train,  if  there  is  room, 
or  in  a  new  car  t h at  is  added  to  t he  end  of  the  last  train,  if  there  is  no  room. 
However,  periodically,  we  instead  start  a  new  train  with  one  car,  and  place  the 
new  object  there. 

G a r b a ge  C o l l e c t i ng  a  Car 

The  heart  of  the  train  algorithm  is  how  we  process  t he  first  car  of  the  first 
train  during  a  round  of  garbage  collection.  Initially,  the  reachable  set  is  taken 
to  be  the  objects  of  t h at  car  with  references  from  t he  root  set  and  those  with 
references  in  t he  remembered  set  for  t h at  car.  We  then  scan  these  objects  as 
in  a  mark-and-sweep  collector,  but  we  do  not  scan  any  reached  objects  outside 
the  one  car  being  collected.  After  this  tracing,  some  objects  in  the  car  may 
be  identified  as  garbage.  There  is  no  need  to  reclaim  their  space,  because  t he 
entire  car  is  going  to  disappear  anyway. 

However,  there  are  likely  to  be  some  reachable  objects  in  t he  car,  and  these 

must  be  moved  somewhere  else.  The  rules  for  moving  an  object  are: 

•  If  there  is  a  reference  in  t he  remembered  set  from  any  other  train  (which 
will  be  higher-numbered  t h an  the  train  of  the  car  being  collected),  then 
move  the  object  to  one  of  those  trains.  If  there  is  room,  the  object  can 
go  in  some  existing  car  of  t he  train  from  which  a  reference  emanates,  or 
it  can  go  in  a  new,  last  car  if  there  is  no  room. 

•  If  there  is  no  reference  from  other  trains,  but  there  are  references  from 
the  root  set  or  from  the  first  train,  then  move  the  object  to  any  other  car 
of the  same  train,  creating  a  new,  last  car  if  there  is  no  room.  If possible, 
pick  a  car  from  which  there  is  a  reference,  to  help  bring  cyclic  structures 
to  a  single  car. 

After  moving  all  the  reachable  objects  from  the  first  car,  we  delete  t h at  car. 

P a n ic  M o de 

There  is  one  problem  with  the  rules  above.  In  order  to  be  sure  t h at  all  garbage 
will  eventually  be  collected,  we  need  to  be  sure  t h at  every  train  eventually 
becomes  t he  first  train,  and  if  this  train  is  not  cyclic  garbage,  then  eventually 

7.7. 

SHORT-PAUSE  GARBAGE  COLLECTION 

493 

all  cars  of  t h at  train  are  removed  and  the  train  disappears  one  car  at  a  time. 
However,  by  rule  (2)  above,  collecting  the  first  car  of the  first  train  can  produce 
a  new  last  car. 
It  cannot  produce  two  or  more  new  cars,  since  surely  all  the 
objects  of  t he  first  car  can  fit  in  the  new,  last  car.  However,  could  we  be  in  a 
situation  where  each  collection  step  for  a  train  results  in  a  new  car  being  added, 
and  we  never  get  finished  with  this  train  and  move  on  to  the  other  trains? 

The  answer  is,  unfortunately,  t h at  such  a  situation  is  possible.  T he  problem 
arises  if we  have  a  large,  cyclic,  nongarbage  structure,  and  t he  m u t a t or  manages 
to  change  references  in  such  a  way  t h at  we  never  see,  at  t he  time  we  collect 
a  car,  any  references  from  higher  trains  in  the  remembered  set. 
If  even  one 
object  is  removed  from  the  train  during  the  collection  of a  car,  then  we  are  OK, 
since  no  new  objects  are  added  to  the  first  train,  and  therefore  the  first  train 
will  surely  run  out  of  objects  eventually.  However,  there  may  be  no  garbage 
at  all  t h at  we  can  collect  at  a  stage,  and  we  run  the  risk  of  a  loop  where  we 
perpetually  garbage  collect  only  the  current  first  train. 

To  avoid  this  problem,  we  need  to  behave  differently  whenever  we  encounter 
a  futile  garbage  collection,  t h at  is,  a  car  from  which  not  even  one  object  can  be 
deleted  as  garbage  or  moved  to  another  train.  In  this  "panic  mode,"  we  make 
two  changes: 

1.  When  a  reference  to  an  object  in  the  first  train  is  rewritten,  we  maintain 

the  reference  as  a  new  member  of  the  root  set. 

2.  When  garbage  collecting,  if  an  object  in  the  first  car  has  a  reference  from 
t he  root  set,  including  dummy  references  set  up  by  point  (1),  then  we 
move  t h at  object  to  another  train,  even  if  it  has  no  references  from  other 
trains.  It  is  not  important  which  train  we  move  it  to,  as  long  as  it  is  not 
the  first  train. 

In  this  way,  if  there  are  any  references  from  outside  the  first  train  to  objects 
in  t he  first  train,  these  references  are  considered  as  we  collect  every  car,  and 
eventually  some  object  will  be  removed  from  t h at  train.  We  can  then  leave  panic 
mode  and  proceed  normally,  sure  t h at  the  current  first  train  is  now  smaller  t h an 
it  was. 

7.7.6  Exercises  for  Section  7.7 

E x e r c i se  7 . 7 . 1:  Suppose  t h at  the  network of objects  from  Fig.  7.20  is  managed 
by  an  incremental  algorithm  t h at  uses  the  four  lists  Unreached,  Unscanned, 
Scanned,  and  Free,  as  in  Baker's  algorithm.  To  be  specific,  the  Unscanned  list 
is  managed  as  a queue,  and  when  more t h an  one  object  is  to  be  placed  on this  list 
due  to  t he  scanning  of  one  object,  we  do  so  in  alphabetical  order.  Suppose  also 
t h at  we  use  write  barriers  to  assure  t h at  no  reachable  object  is  made  garbage. 
Starting  with  A  and  B  on  the  Unscanned  list,  suppose  the  following  events 
occur: 

i.  A  is  scanned. 

494 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

ii.  The  pointer  A  -»  D  is  rewritten  to  be  A  ->•  i J. 

m. 

i?  is  scanned. 

iv.  D  is  scanned. 

v.  The  pointer  5  ->  C  is  rewritten  to  be  I? 

/. 

Simulate  the  entire  incremental  garbage  collection,  assuming  no  more  pointers 
are  rewritten.  Which  objects  are  garbage?  Which  objects  are  placed  on  the 
Free  list? 

E x e r c i se  7 . 7 . 2:  Repeat  Exercise  7.7.1  on  the  assumption  t h at 

a)  Events  (ii)  and  (v)  are  interchanged  in  order. 

b)  Events  (ii)  and  (v)  occur  before  (i),  (Hi),  and  (iv). 

E x e r c i se  7 . 7 . 3:  Suppose  the  heap  consists  of  exactly  the  nine  cars  on  three 
trains  shown  in  Fig.  7.30  (i.e.,  ignore  the  ellipses).  Object  o  in  car  11  has 
references  from  cars  12,  23,  and  32.  When  we  garbage  collect  car  11,  where 
might  o  wind  up? 

E x e r c i se  7 . 7 . 4:  Repeat  Exercise  7.7.3  for  the  cases  t h at  o  has 

a)  Only  references  from  cars  22  and  31. 

b)  No  references  other  t h an  from  car  11. 

E x e r c i se  7 . 7 . 5:  Suppose  the  heap  consists  of  exactly  the  nine  cars  on  three 
trains  shown  in  Fig.  7.30  (i.e.,  ignore  t he  ellipses).  We  are  currently  in  panic 
mode.  Object  oi  in  car  11  has  only  one  reference,  from  object  o2  in  car  12.  T h at 
reference  is  rewritten.  When  we  garbage  collect  car  11,  what  could  happen  to 
oi? 

7.8  Advanced  Topics  in  Garbage  Collection 

We  close  our  investigation  of  garbage  collection  with  brief  treatments  of  four 
additional  topics: 

1.  Garbage  collection  in  parallel  environments. 

2.  Partial  relocations  of  objects. 

3.  Garbage  collection  for  languages  t h at  are  not  type-safe. 

4.  T he  interaction  between  programmer-controlled  and  automatic  garbage 

collection. 

7.8. 

ADVANCED 

TOPICS 

IN  GARBAGE  COLLECTION 

495 

7.8.1  Parallel  and  Concurrent  Garbage  Collection 

Garbage  collection  becomes  even  more  challenging  when  applied  to  applications 
running  in  parallel  on  a  multiprocessor  machine.  It  is  not  uncommon  for  server 
applications  to  have  thousands  of  threads  running  at  t he  same  time;  each  of 
these  threads  is  a  mutator.  Typically,  the  heap  will  consist  of  gigabytes  of 
memory. 

Scalable  garbage-collection  algorithms  must  take  advantage  of  t he  presence 
of  multiple  processors.  We  say  a  garbage  collector  is  parallel  if  it  uses  multiple 
threads;  it  is  concurrent  if  it  runs  simultaneously  with  the  mutator. 

We  shall  describe  a  parallel,  and  mostly  concurrent,  collector  t h at  uses  a 
concurrent  and  parallel  phase  t h at  does  most  of  the  tracing  work,  and  then  a 
stop-the-world  phase  t h at  guarantees  all  the  reachable  objects  are  found  and  re 
claims  t he  storage.  This  algorithm  introduces  no  new  basic  concepts  in  garbage 
collection  per  se;  it  shows  how  we  can  combine  the  ideas  described  so  far  to 
create  a  full  solution  to  the  parallel-and-concurrent  collection  problem.  How 
ever,  there  are  some  new  implementation  issues  t h at  arise  due  to  t he  n a t u re 
of  parallel  execution.  We  shall  discuss  how  this  algorithm  coordinates  multiple 
threads  in  a  parallel  computation  using  a  rather  common  work-queue  model. 
To  understand  the  design  of  t he  algorithm  we  must  keep  in  mind  t he  scale 
of  the  problem.  Even  the  root  set  of  a  parallel  application  is  much  larger, 
consisting  of  every  thread's  stack,  register  set  and  globally  accessible  variables. 
The  amount  of heap  storage  can  be  very  large,  and  so  is  t he  amount  of reachable 
data.  T he  rate  at  which  mutations  take  place  is  also  much  greater. 

To  reduce  the  pause  time,  we  can  adapt  the  basic  ideas  developed  for  in 
cremental  analysis  to  overlap  garbage  collection  with  mutation.  Recall  t h at  an 
incremental  analysis,  as  discussed  in  Section  7.7,  performs  the  following  three 
steps: 

1.  Find  the  root  set.  This  step  is  normally  performed  atomically,  t h at  is, 

with  t he  mutator(s)  stopped. 

2.  Interleave  t he  tracing  of  the  reachable  objects  with  the  execution  of  the 
mutator(s).  In  this  period,  every  time  a  m u t a t or  writes  a  reference  t h at 
points  from  a  Scanned  object  to  an  Unreached  object,  we  remember  t h at 
reference.  As  discussed  in  Section  7.7.2,  we  have  options  regarding  the 
granularity  with  which  these  references  are  remembered.  In  this  section, 
we  shall  assume  the  card-based  scheme,  where  we  divide  the  heap  into 
sections  called  "cards"  and  maintain  a  bit  m ap  indicating  which  cards  are 
dirty  (have  had  one  or  more  references  within  them  rewritten). 

3.  Stop  the  mutator(s)  again  to  rescan  all  the  cards  t h at  may  hold  references 

to  unreached  objects. 

For  a  large  multithreaded  application,  the  set  of objects  reached  by  the  root 
set  can  be  very  large.  It  is  infeasible  to  take  the  time  and  space  to  visit  all  such 
objects  while  all  mutations  cease.  Also,  due  to  t he  large  heap  and  t he  large 

496 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

number  of  mutation  threads,  many  cards  may  need  to  be  rescanned  after  all 
objects  have  been  scanned  once.  It  is  thus  advisable  to  scan  some  of these  cards 
in  parallel,  while  the  m u t a t o rs  are  allowed  to  continue  to  execute  concurrently. 
To  implement  the  tracing  of step  (2)  above,  in  parallel,  we  shall  use  multiple 
garbage-collecting  threads  concurrently  with  t he  m u t a t or  threads  to  trace  most 
of  the  reachable  objects.  Then,  to  implement  step  (3),  we  stop  the  m u t a t o rs 
and  use  parallel  threads  to  ensure  t h at  all  reachable  objects  are  found. 

The  tracing  of  step  (2)  is  carried  out  by  having  each  m u t a t or  thread  per 
form  part  of  t he  garbage  collection,  along  with  its  own  work.  In  addition,  we 
use  threads  t h at  are  dedicated  purely  to  collecting  garbage.  Once  garbage  col 
lection  has  been  initiated,  whenever  a  m u t a t or  thread  performs  some  memory-
allocation  operation,  it  also  performs  some  tracing  computation.  T he  pure 
garbage-collecting  threads  are  put  to  use  only  when  a  machine  has  idle  cycles. 
As  in  incremental  analysis,  whenever  a  m u t a t or  writes  a  reference  t h at  points 
from  a  Scanned object  to  an  Unreached object,  the  card  t h at  holds  this  reference 
is  marked  dirty  and  needs  to  be  rescanned. 

Here  is  an  outline  of  t he  parallel,  concurrent  garbage-collection  algorithm. 

1.  Scan  the  root  set  for  each  m u t a t or  thread,  and  put  all  objects  directly 
reachable  from  t h at  thread  into  the  Unscanned  state.  The  simplest  incre 
mental  approach  to  this  step  is  to  wait  until  a  m u t a t or  thread  calls  the 
memory  manager,  and  have  it  scan  its  own  root  set  if t h at  has  not  already 
been  done. 
If  some  m u t a t or  thread  has  not  called  a  memory  allocation 
function,  but  all  t he  rest  of  tracing  is  done,  then  this  thread  must  be 
interrupted  to  have  its  root  set  scanned. 

2.  Scan  objects  t h at  are  in  t he  Unscanned  state.  To  support  parallel  com 

putation,  we  use  a  work  queue  of  fixed-size  work  packets,  each  of  which 
holds  a  number  of  Unscanned  objects.  Unscanned  objects  are  placed  in 
work  packets  as  they  are  discovered.  Threads  looking  for  work  will  de 
queue  these  work  packets  and  trace  the  Unscanned  objects  therein.  This 
strategy  allows  t he  work  to  be  spread  evenly  among  workers  in  t he  tracing 
process.  If  the  system  runs  out  of  space,  and  we  cannot  find  t he  space  to 
create  these  work  packets,  we  simply  mark  the  cards  holding  t he  objects 
to  force  t h em  to  be  scanned.  The  latter  is  always  possible  because  t he  bit 
array  holding  the  marks  for  t he  cards  has  already  been  allocated. 

3.  Scan  the  objects  in  dirty  cards.  When  there  are  no  more  Unscanned  ob 
jects  left  in  the  work  queue,  and  all  t h r e a d s'  root  sets  have  been  scanned, 
the  cards  are  rescanned  for  reachable  objects.  As  long  as  t he  m u t a t o rs 
continue  to  execute,  dirty  cards  continue  to  be  produced.  Thus,  we  need 
to  stop  t he  tracing  process  using  some  criterion,  such  as  allowing  cards  to 
be  rescanned  only  once  or  a  fixed  number  of  times,  or  when  t he  number 
of outstanding  cards  is  reduced  to  some  threshold.  As  a  result,  this  paral 
lel  and  concurrent  step  normally  terminates  before  completing  t he  trace, 
which  is  finished  by  the  final  step,  below. 

7.8.  ADVANCED  TOPICS  IN  GARBAGE  COLLECTION 

497 

4.  T he  final  step  guarantees  t h at  all  reachable  objects  are  marked  as  reached. 
W i th  all  t he  m u t a t o rs  stopped,  the  root  sets  for  all  the  threads  can  now 
be  found  quickly  using  all  the  processors  in  t he  system.  Because  the 
reachability  of  most  objects  has  been  traced,  only  a  small  number  of 
objects  are  expected  to  be  placed  in  the  Unscanned  state.  All  t he  threads 
then  participate  in  tracing  the  rest  of the  reachable  objects  and  rescanning 
all  t he  cards. 

It  is  important  t h at  we  control  the  rate  at  which  tracing  takes  place.  The 
tracing  phase  is  like  a race.  The  mutators  create  new  objects  and  new  references 
t h at  must  be  scanned,  and  the  tracing  tries  to  scan  all  the  reachable  objects  and 
rescan  the  dirty  cards  generated  in  the  meanwhile.  It  is  not  desirable  to  start 
the  tracing  too  much  before  a  garbage  collection  is  needed,  because  t h at  will 
increase  t he  amount  of  floating  garbage.  On  t he  other  hand,  we  cannot  wait 
until  the  memory  is  exhausted  before  the  tracing  starts,  because  then  m u t a t o rs 
will  not  be  able  to  make  forward  progress  and  t he  situation  degenerates  to  t h at 
of  a  stop-the-world  collector.  Thus,  the  algorithm  must  choose  t he  time  to 
commence  the  collection  and  the  rate  of  tracing  appropriately.  An  estimate 
of  the  mutation  rate  from  previous  cycles  of  collection  can  be  used  to  help  in 
t he  decision.  T he  tracing  rate  is  dynamically  adjusted  to  account  for  the  work 
performed  by  the  pure  garbage-collecting  threads. 

7.8.2  Partial  Object  Relocation 

As  discussed  starting  in  Section  7.6.4,  copying  or  compacting  collectors  are  ad 
vantageous  because  they  eliminate  fragmentation.  However,  these  collectors 
have  nontrivial  overheads.  A  compacting  collector  requires  moving  all  objects 
and  updating  all  the  references  at  the  end  of  garbage  collection.  A  copying 
collector  figures  out  where  the  reachable  objects  go  as  tracing  proceeds;  if trac 
ing  is  performed  incrementally,  we  need  either  to  translate  a  m u t a t o r 's  every 
reference,  or  to  move  all  the  objects  and  u p d a te  their  references  at  the  end. 
Both  options  are  very  expensive,  especially  for  a  large  heap. 

We  can  instead  use  a  copying  generational  garbage  collector.  It  is  effective  in 
collecting  i m m a t u re  objects  and  reducing  fragmentation,  but  can  be  expensive 
when  collecting  m a t u re  objects.  We  can  use  the  train  algorithm  to  limit  t he 
amount  of m a t u re  d a ta  analyzed  each  time.  However,  the  overhead  of the  train 
algorithm  is  sensitive  to  the  size  of  the  remembered  set  for  each  partition. 

There  is  a  hybrid  collection  scheme  t h at  uses  concurrent  tracing  to  reclaim 
all  t he  unreachable  objects  and  at  the  same  time  moves  only  a  part  of  the 
objects.  This  method  reduces  fragmentation  without  incurring  t he  full  cost  of 
relocation  in  each  collection  cycle. 

1.  Before  tracing  begins,  choose  a  part  of  the  heap  t h at  will  be  evacuated. 

2.  As  t he  reachable  objects  are  marked,  also  remember  all  the  references 

pointing  to  objects  in  the  designated  area. 

498 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

3.  When  tracing  is  complete,  sweep  the  storage  in  parallel  to  reclaim  the 

space  occupied  by  unreachable  objects. 

4.  Finally,  evacuate  the  reachable  objects  occupying  t he  designated  area  and 

fix  up  the  references  to  the  evacuated  objects. 

7.8.3  Conservative  Collection  for  Unsafe  Languages 

As  discussed  in  Section  7.5.1,  it  is  impossible  to  build  a  garbage  collector  t h at  is 
guaranteed  to  work  for  all  C  and  C ++  programs.  Since  we  can  always  compute 
an  address  with  arithmetic  operations,  no  memory  locations  in  C  and  C ++  can 
ever  be  shown  to  be  unreachable.  However,  many  C  or  C ++  programs  never 
fabricate  addresses  in  this  way.  It  has  been  demonstrated  t h at  a  conservative 
garbage  collector  —  one  t h at  does  not  necessarily  discard  all  garbage  —  can  be 
built  to  work  well  in  practice  for  this  class  of  programs. 

A  conservative  garbage  collector  assumes  t h at  we  cannot  fabricate  an  ad 
dress,  or  derive  the  address  of  an  allocated  chunk  of  memory  without  an  ad 
dress  pointing  somewhere  in  the  same  chunk.  We  can  find  all  the  garbage  in 
programs  satisfying  such  an  assumption  by  treating  as  a  valid  address  any  bit 
p a t t e rn  found  anywhere  in  reachable  memory,  as  long  as  t h at  bit  p a t t e rn  may 
be  construed  as  a  memory  location.  This  scheme  may  classify  some  d a ta  erro 
neously  as  addresses.  It  is  correct,  however,  since  it  only  causes  the  collector  to 
be  conservative  and  keep  more  d a ta  t h an  necessary. 

Object  relocation,  requiring  all  references  to  t he  old  locations  be  u p d a t ed  to 
point  to  the  new  locations,  is  incompatible  with  conservative  garbage  collection. 
Since  a  conservative  garbage  collector  does  not  know  if  a  particular  bit  p a t t e rn 
refers  to  an  actual  address,  it  cannot  change  these  patterns  to  point  to  new 
addresses. 

Here  is  how  a  conservative  garbage  collector  works.  First,  the  memory 
manager  is  modified  to  keep  a  data  map  of  all  the  allocated  chunks  of  memory. 
This  m ap  allows  us  to  find  easily  t he  starting  and  ending  boundary  of the  chunk 
of  memory  t h at  spans  a  certain  address.  T he  tracing  starts  by  scanning  the 
program's  root  set  to  find  any  bit  p a t t e rn  t h at  looks  like  a  memory  location, 
without  worrying  about  its  type.  By  looking  up  these  potential  addresses  in  t he 
d a ta  m a p,  we  can  find  t he  starting  addresses  of  those  chunks  of  memory  t h at 
might  be  reached,  and  place  t h em  in  t he  Unscanned  state.  We  then  scan  all  the 
unscanned  chunks,  find  more  (presumably)  reachable  chunks  of  memory,  and 
place  t h em  on  the  work  list  until  the  work  list  becomes  empty.  After  tracing 
is  done,  we  sweep  through  the  heap  storage  using  the  d a ta  m ap  to  locate  and 
free  all  the  unreachable  chunks  of  memory. 

7.8.4  Weak  References 

Sometimes,  programmers  use  a  language  with  garbage  collection,  but  also  wish 
to  manage  memory,  or  parts  of  memory,  themselves.  T h at  is,  a  programmer 
may  know  t h at  certain  objects  are  never  going to  be  accessed  again,  even  though 

7.8. 

ADVANCED 

TOPICS 

IN  GARBAGE  COLLECTION 

499 

references  to  t he  objects  remain.  An  example  from  compiling  will  suggest  t he 
problem. 

E x a m p le  7 . 1 7:  We  have  seen  t h at  the  lexical  analyzer  often  manages  a  sym 
bol  table  by  creating  an  object  for  each  identifier  it  sees.  These  objects  may 
appear  as  lexical  values  attached  to  leaves  of  the  parse  tree  representing  those 
identifiers,  for  instance.  However,  it  is  also  useful  to  create  a  hash  table,  keyed 
by  t he  identifier's  string,  to  locate  these  objects.  T h at  table  makes  it  easier  for 
t he  lexical  analyzer  to  find  t he  object  when  it  encounters  a  lexeme  t h at  is  an 
identifier. 

When  the  compiler  passes  the  scope  of  an  identifier  J,  its  symbol-table 
object  no  longer  has  any  references  from  the  parse  tree,  or  probably  any  other 
intermediate  structure  used  by  the  compiler.  However,  a  reference  to  the  object 
is  still  sitting  in  t he  hash  table.  Since  the  hash  table  is  part  of the  root  set  of t he 
compiler,  t he  object  cannot  be  garbage  collected.  If  another  identifier  with  t he 
same  lexeme  as  I  is  encountered,  then  it  will  be  discovered t h at  i"  is  out  of scope, 
and  t he  reference  to  its  object  will  be  deleted.  However,  if  no  other  identifier 
with  this  lexeme  is  encountered,  then  J's  object  may  remain  as  uncollectable, 
yet  useless,  throughout  compilation. 

• 

If  the  problem  suggested  by  Example  7.17  is  important,  then  the  compiler 
writer  could  arrange  to  delete  from  the  hash  table  all  references  to  objects  as 
soon  as  their  scope  ends.  However,  a  technique  known  as  weak  references  allows 
the  programmer  to  rely  on  automatic  garbage  collection,  and  yet  not  have  the 
heap  burdened  with  reachable,  yet  truly  unused,  objects.  Such  a  system  allows 
certain  references  to  be  declared  "weak."  An  example  would  be  all the  references 
in  the  hash  table  we  have  been  discussing.  When  the  garbage  collector  scans 
an  object,  it  does  not  follow  weak  references  within  t h at  object,  and  does  not 
make  the  objects  they  point  to  reachable.  Of  course,  such  an  object  may  still 
be  reachable  if  there  is  another  reference  to  it  t h at  is  not  weak. 

7.8.5  Exercises  for  Section  7.8 

!  E x e r c i se  7 . 8 . 1:  In  Section  7.8.3  we  suggested  t h at  it  was  possible  to  garbage 
collect  for  C  programs  t h at  do  not  fabricate  expressions  t h at  point  to  a  place 
within  a  chunk  unless  there  is  an  address  t h at  points  somewhere  within  t h at 
same  chunk.  Thus,  we  rule  out  code  like 

p  =  12345; 
x  =  *p; 

because,  while p  might  point  to  some  chunk  accidentally,  there  could  be  no  other 
pointer  to  t h at  chunk.  On  the  other  hand,  with  the  code  above,  it  is  more  likely 
t h at  p  points  nowhere,  and  executing  t h at  code  will  result  in  a  segmentation 
fault.  However,  in  C  it  is  possible  to  write  code  such  t h at  a  variable  like  p  is 
guaranteed  to  point  to  some  chunk,  and  yet  there  is  no  pointer  to  t h at  chunk. 
Write  such  a  program. 

500 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

7.9  Summary  of  Chapter  7 

•  Run-Time  Organization.  To  implement  the  abstractions  embodied  in  t he 
source  language,  a  compiler  creates  and  manages  a  run-time  environment 
in  concert  with  the  operating  system  and  the  target  machine.  T he  run 
time  environment  has  static  d a ta  areas  for  the  object  code  and  the  static 
d a ta  objects  created  at  compile  time.  It  also  has  dynamic  stack  and  heap 
areas  for  managing  objects  created  and  destroyed  as  the  target  program 
executes. 

•  Control  Stack.  Procedure  calls  and  returns  are  usually  managed  by  a  run 
time  stack  called  t he  control  stack.  We  can  use  a  stack  because  procedure 
calls  or  activations  nest  in  time;  t h at  is,  if  p  calls  q,  then  this  activation 
of  q  is  nested  within  this  activation  of p. 

•  Stack  Allocation.  Storage  for  local  variables  can  allocated  on  a  run-time 
stack  for  languages  t h at  allow  or  require  local  variables  to  become  inacces 
sible  when  their  procedures  end.  For  such  languages,  each  live  activation 
has  an  activation  record  (or  frame)  on  the  control  stack,  with  the  root  of 
the  activation  tree  at  the  bottom,  and  the  entire  sequence  of  activation 
records  on  the  stack  corresponding  to  the  p a th  in  the  activation  tree  to 
the  activation  where  control  currently  resides.  T he  latter  activation  has 
its  record  at  the  top  of  the  stack. 

•  Access  to  Nonlocal  Data  on  the  Stack.  For  languages  like  C  t h at  do  not 
allow  nested  procedure  declarations,  the  location  for  a  variable  is  either 
global  or  found  in  t he  activation  record  on  top  of  the  run-time  stack.  For 
languages  with  nested  procedures,  we  can  access  nonlocal  d a ta  on  the 
stack  through  access  links,  which  are  pointers  added  to  each  activation 
record.  The  desired  nonlocal  d a ta  is  found  by  following  a  chain  of  access 
links  to  the  appropriate  activation  record.  A  display  is  an  auxiliary  array, 
used  in  conjunction  with  access  links,  t h at  provides  an  efficient  short-cut 
alternative  to  a  chain  of  access  links. 

•  Heap  Management.  The  heap  is  the  portion  of  t he  store  t h at  is  used  for 
d a ta  t h at  can  live  indefinitely,  or  until  t he  program  deletes  it  explicitly. 
The  memory  manager  allocates  and  deallocates  space  within  t he  heap. 
Garbage  collection  finds  spaces  within  the  heap  t h at  are  no  longer  in  use 
and  can  therefore  be  reallocated  to  house  other  d a ta  items.  For  languages 
t h at  require  it,  the  garbage  collector  is  an  important  subsystem  of  t he 
memory  manager. 

•  Exploiting  Locality.  By  making  good  use  of  the  memory  hierarchy,  mem 
ory  managers  can  influence  the  run  time  of  a  program.  The  time  taken  to 
access  different  parts  of  memory  can  vary  from  nanoseconds  to  millisec 
onds.  Fortunately,  most  programs  spend  most  of  their  time  executing  a 
relatively  small  fraction  of  t he  code  and  touching  only  a  small  fraction  of 

7.9. 

SUMMARY  OF  CHAPTER  7 

501 

the  data.  A  program  has  temporal  locality  if  it  is  likely  to  access  the  same 
memory  locations  again  soon;  it  has  spatial  locality  if  it  is  likely  to  access 
nearby  memory  locations  soon. 

4  Reducing  Fragmentation.  As  the  program  allocates  and  deallocates  mem 
ory,  the  heap  may  get  fragmented,  or  broken  into  large  numbers  of  small 
noncontiguous  free  spaces  or  holes.  T he  best  fit  strategy  —  allocate  the 
smallest  available  hole  t h at  satisfies  a  request  —  has  been  found  empir 
ically  to  work  well.  While  best  fit  tends  to  improve  space  utilization,  it 
may  not  be  best  for  spatial  locality.  Fragmentation  can  be  reduced  by 
combining  or  coalescing  adjacent  holes. 

4  Manual  Deallocation.  Manual  memory  management  has 

two  common 
failings:  not  deleting  d a ta  t h at  can  not  be  referenced  is  a  memory-leak 
error,  and  referencing  deleted  d a ta  is  a  dangling-pointer-dereference  error. 

•  Reachability.  Garbage  is  d a ta  t h at  cannot  be  referenced  or  reached.  There 
are  two  basic  ways  of  finding  unreachable  objects:  either  catch  the  tran 
sition  as  a  reachable  object  t u r ns  unreachable,  or  periodically  locate  all 
reachable  objects  and  infer  t h at  all  remaining  objects  are  unreachable. 

•  Reference-Counting  Collectors  maintain  a  count  of  the  references  to  an  ob 
ject;  when  the  count  transitions  to  zero,  the  object  becomes  unreachable. 
Such  collectors  introduce  the  overhead  of  maintaining  references  and  can 
fail  to  find  "cyclic"  garbage,  which  consists  of  unreachable  objects  t h at 
reference  each  other,  perhaps  through  a  chain  of  references. 

•  Trace-Based  Garbage  Collectors  iteratively  examine  or  trace  all  references 
to  find  reachable  objects,  starting  with  the  root  set  consisting  of  objects 
t h at  can  be  accessed  directly  without  having  to  dereference  any  pointers. 

4  Mark-and-Sweep  Collectors  visit  and  mark  all  reachable  objects  in  a  first 
tracing  step  and  then  sweep  the  heap  to  free  up  unreachable  objects. 

4-  Mark-and-Compact  Collectors  improve  upon  mark-and-sweep;  they  relo 
cate  reachable  objects  in  the  heap  to  eliminate  memory  fragmentation. 

4  Copying  Collectors  break  the  dependency  between  tracing  and  finding 
free  space.  They  partition  the  memory  into  two  semispaces,  A  and  B. 
Allocation  requests  are  satisfied  from  one  semispace,  say  A,  until  it  fills 
up,  at  which  point  the  garbage  collector  takes  over,  copies  t he  reachable 
objects  to  the  other  space,  say  B,  and  reverses  the  roles  of the  semispaces. 

4 

Incremental  Collectors.  Simple  trace-based  collectors  stop  the  user  pro 
gram  while  garbage  is  collected. 
Incremental  collectors  interleave  the 
actions  of  the  garbage  collector  and  the  mutator  or  user  program.  T he 
m u t a t or  can  interfere  with  incremental  reachability  analysis,  since  it  can 

502 

CHAPTER 

7. 

RUN-TIME  ENVIRONMENTS 

change  the  references  within  previously  scanned  objects.  Incremental  col 
lectors  therefore  play  it  safe  by  overestimating the  set  of reachable  objects; 
any  "floating  garbage"  can  be  picked  up  in  the  next  round  of  collection. 

•  Partial  Collectors  also  reduce  pauses;  they  collect  a  subset  of  the  garbage 
at  a  time.  The  best  known  of  partial-collection  algorithms,  generational 
garbage  collection,  partitions  objects  according  to  how  long  they  have 
been  allocated  and  collects  t he  newly  created  objects  more  often  because 
they  tend  to  have  shorter  lifetimes.  An  alternative  algorithm,  the  train 
algorithm,  uses  fixed  length  partitions,  called  cars,  t h at  are  collected  into 
trains.  Each  collection  step  is  applied  to  the  first  remaining  car  of the  first 
remaining  train.  When  a  car  is  collected,  reachable  objects  are  moved  out 
to  other  cars,  so  this  car  is  left  with  garbage  and  can  be  removed  from 
t he  train.  These  two  algorithms  can  be  used  together  to  create  a  partial 
collector  t h at  applies  t he  generational  algorithm  to  younger  objects  and 
the  train  algorithm  to  more  m a t u re  objects. 

7.10  References  for  Chapter  7 

In  mathematical  logic,  scope  rules  and  parameter  passing  by  substitution  date 
back  to  Frege  [8].  Church's  lambda  calculus  [3]  uses  lexical  scope;  it  has  been 
used  as  a  model  for  studying  programming  languages.  Algol  60  and  its  succes 
sors,  including  C  and  Java,  use  lexical  scope.  Once  introduced  by  t he  initial 
implementation  of  Lisp,  dynamic  scope  became  a  feature  of  t he  language;  Mc 
Carthy  [14]  gives  the  history. 

Many  of  the  concepts  related  to  stack  allocation  were  stimulated  by  blocks 
and  recursion  in  Algol  60.  The  idea  of  a  display  for  accessing  nonlocals  in 
a  lexically  scoped  language  is  due  to  Dijkstra  [5].  A  detailed  description  of 
stack  allocation,  the  use  of  a  display,  and  dynamic  allocation  of  arrays  appears 
in  Randell  and  Russell  [16].  Johnson  and  Ritchie  [10]  discuss  t he  design  of  a 
calling  sequence  t h at  allows  the  number  of  arguments  of  a  procedure  to  vary 
from  call  to  call. 

Garbage  collection  has  been  an  active  area  of  investigation;  see  for  example 
Wilson  [17].  Reference  counting dates  back to  Collins  [4].  Trace-based collection 
dates  back  to  McCarthy  [13],  who  describes  a  mark-sweep  algorithm  for  fixed-
length  cells.  The  boundary-tag  for  managing  free  space  was  designed  by  K n u th 
in  1962  and  published  in  [11]. 

Algorithm  7.14 is  based on Baker  [1].  Algorithm  7.16 is  based on  Cheney's  [2] 

nonrecursive  version  of  Fenichel  and  Yochelson's  [7]  copying  collector. 

Incremental  reachability  analysis  is  explored  by  Dijkstra  et  al.  [6].  Lieber-
m an  and  Hewitt  [12]  present  a  generational  collector  as  an  extension  of  copying 
collection.  T he  train  algorithm  began  with  Hudson  and  Moss  [9]. 

1.  Baker,  H.  G.  Jr.,  "The  treadmill:  real-time  garbage  collection  without 
motion  sickness,"  ACM  SIGPLAN  Notices  27:3  (Mar.,  1992),  p p.  66-70. 

7.10. 

REFERENCES  FOR  CHAPTER  7 

503 

2.  Cheney,  C.  J.,  "A  nonrecursive  list  compacting  algorithm,"  Comm.  ACM 

13:11  (Nov.,  1970),  pp.  677-678. 

3.  Church,  A.,  The  Calculi  of  Lambda  Conversion,  Annals  of  M a t h.  Studies, 

No.  6,  Princeton  University  Press,  Princeton,  N.  J.,  1941. 

4.  Collins,  G.  E.,  "A  method  for  overlapping  and  erasure  of  lists,"  Comm. 

ACM  2:12  ( D e c,  1960),  pp.  655-657. 

5.  Dijkstra,  E.  W.,  "Recursive  programming,"  Numerische  Math.  2  (1960), 

pp.  312-318. 

6.  Dijkstra,  E.  W.,  L.  Lamport,  A.  J.  Martin,  C.  S.  Scholten,  and  E.  F. 
M.  Steffens,  "On-the-fly  garbage  collection:  an  exercise  in  cooperation," 
Comm.  ACM  21:11  (1978),  p p.  966-975. 

7.  Fenichel,  R.  R.  and  J.  C.  Yochelson,  "A  Lisp  garbage-collector for  virtual-
memory  computer  systems",  Comm.  ACM  12:11  (1969),  pp.  611-612. 

8.  Frege,  G.,  "Begriffsschrift,  a  formula  language,  modeled  upon  t h at  of 
arithmetic,  for  pure  thought,"  (1879).  In  J.  van  Heijenoort,  From  Frege 
to  Gbdel,  Harvard  Univ.  Press,  Cambridge  MA,  1967. 

9.  Hudson,  R.  L.  and  J.  E.  B.  Moss,  "Incremental  Collection  of  Mature 

Objects",  Proc. 
In  Computer  Science  6 37  (1992),  pp.  388-403. 

Intl.  Workshop  on  Memory  Management,  Lecture  Notes 

10.  Johnson,  S.  C.  and  D.  M.  Ritchie,  "The  C  language  calling  sequence," 
Computing  Science  Technical  Report  102,  Bell  Laboratories,  Murray  Hill 
NJ,  1981. 

11.  Knuth,  D.  E.,  Art  of  Computer  Programming,  Volume  1:  Fundamental 

Algorithms,  Addison-Wesley,  Boston  MA,  1968. 

12.  Lieberman,  H.  and  C.  Hewitt,  "A  real-time  garbage  collector  based  on 
the  lifetimes  of  objects,"  Comm.  ACM  26:6  (June  1983),  pp.  419-429. 

13.  McCarthy,  J.,  "Recursive  functions  of symbolic  expressions  and  their  com 
putation  by  machine,"  Comm.  ACM  3:4  (Apr.,  1960),  pp.  184-195. 

14.  McCarthy,  J.,  "History  of Lisp."  See  pp.  173-185 in  R.  L.  Wexelblat  (ed.), 

History  of  Programming  Languages,  Academic  Press,  New  York,  1981. 

15.  Minsky,  M.,  "A  LISP  garbage  collector  algorithm  using  secondary  stor 

age,"  A.  I.  Memo  58,  M IT  Project  MAC,  Cambridge  MA,  1963. 

16.  Randell,  B.  and  L.  J.  Russell,  Algol  60  Implementation,  Academic  Press, 

New  York,  1964. 

17.  Wilson,  P.  R.,  "Uniprocessor  garbage  collection  techniques," 

ftp://ftp.cs.utexas.edu/pub/garbage/bigsurv.ps 

Chapter  8 

Code  Generation 

The  final  phase  in  our  compiler  model  is  the  code  generator.  It  takes  as  input 
the  intermediate  representation  (IR)  produced  by  the  front  end  of  the  com 
piler,  along  with  relevant  symbol  table  information,  and  produces  as  output  a 
semantically  equivalent  target  program,  as  shown  in  Fig.  8.1. 

The  requirements  imposed  on  a  code  generator  are  severe.  T he  target  pro 
gram  must  preserve  t he  semantic  meaning  of  t he  source  program  and  be  of 
high  quality;  t h at  is,  it  must  make  effective  use  of the  available  resources  of the 
target  machine.  Moreover,  t he  code  generator  itself  must  run  efficiently. 

The  challenge  is  t h a t,  mathematically,  the  problem  of generating  an  optimal 
target  program  for  a  given  source  program  is  undecidable;  many  of the  subprob-
lems  encountered  in  code  generation  such  as  register  allocation  are  computa 
tionally  intractable.  In  practice,  we  must  be  content  with  heuristic  techniques 
t h at  generate  good,  but  not  necessarily  optimal,  code.  Fortunately,  heuristics 
have  m a t u r ed  enough  t h at  a  carefully  designed  code  generator  can  produce  code 
t h at  is  several  times  faster  t h an  code  produced  by  a  naive  one. 

Compilers  t h at  need  to  produce  efficient  target  programs,  include  an  op 
timization  phase  prior  to  code  generation.  T he  optimizer  maps  t he  IR  into 
IR  from  which  more  efficient  code  can  be  generated. 
In  general,  the  code-
optimization  and  code-generation  phases  of  a  compiler,  often  referred  to  as  the 
back  end,  may  make  multiple  passes  over  the  IR  before  generating  the  target 
program.  Code  optimization  is  discussed  in  detail  in  Chapter  9.  The  tech 
niques  presented  in  this  chapter  can  be  used  whether  or  not  an  optimization 
phase  occurs  before  code  generation. 

A  code  generator  has  three  primary  tasks: 

instruction  selection,  register 

s o u r c e^ 
p r o g r am 

Front 
Front 
E nd 
E nd 

i n t e r m e d i a te 
code 

Code 
Code 
Optimizer 
Optimizer 

i n t e r m e d i a te 
code 

Code 
Code 
Generator 
Generator 

t a r g et 
p r o g r am 

Figure  8.1:  Position  of  code  generator 

505 

506 

CHAPTER  8. 

CODE  GENERATION 

allocation  and  assignment,  and  instruction  ordering.  T he  importance  of  these 
tasks  is  outlined  in  Section  8.1.  Instruction  selection  involves  choosing  appro 
priate  target-machine  instructions  to  implement  the  IR  statements.  Register 
allocation  and  assignment  involves  deciding  what  values  to  keep  in  which  reg 
Instruction  ordering  involves  deciding  in  what  order  to  schedule  the 
isters. 
execution  of  instructions. 

This  chapter  presents  algorithms  t h at  code  generators  can  use  to  trans 
late  the  IR  into  a  sequence  of  target  language  instructions  for  simple  register 
machines.  The  algorithms  will  be  illustrated  by  using  the  machine  model  in  Sec 
tion  8.2.  Chapter  10  covers  t he  problem  of code  generation  for  complex  modern 
machines  t h at  support  a  great  deal  of  parallelism  within  a  single  instruction. 

After  discussing  the  broad  issues  in  the  design  of  a  code  generator,  we  show 
what  kind  of  target  code  a  compiler  needs  to  generate  to  support  the  abstrac 
tions  embodied  in  a  typical  source  language.  In  Section  8.3,  we  outline  imple 
mentations  of  static  and  stack  allocation  of  d a ta  areas,  and  show  how  names  in 
the  IR  can  be  converted  into  addresses  in  the  target  code. 

Many  code  generators  partition  IR  instructions  into  "basic  blocks,"  which 
consist  of  sequences  of  instructions  t h at  are  always  executed  together.  T he 
partitioning  of  t he  IR  into  basic  blocks  is  the  subject  of  Section  8.4.  T he 
following  section  presents  simple  local  transformations  t h at  can  be  used  to 
transform  basic  blocks  into  modified  basic  blocks  from  which  more  efficient 
code  can  be  generated.  These  transformations  are  a  rudimentary  form  of  code 
optimization,  although  the  deeper  theory  of code  optimization  will  not  be  taken 
up  until  Chapter  9.  An  example  of a  useful,  local  transformation  is  the  discovery 
of  common  subexpressions  at  the  level  of  intermediate  code  and  the  resultant 
replacement  of  arithmetic  operations  by  simpler  copy  operations. 

Section  8.6  presents  a  simple  code-generation  algorithm  t h at  generates  code 
for  each  statement  in  turn,  keeping  operands  in  registers  as  long  as  possible. 
The  output  of  this  kind  of  code  generator  can  be  readily  improved  by  peephole 
optimization  techniques  such  as  those  discussed  in  the  following  Section  8.7. 

The  remaining  sections  explore  instruction  selection  and  register  allocation. 

8.1 

Issues  in  the  Design  of a  Code  Generator 

While  the  details  are  dependent  on  the  specifics  of  the  intermediate  represen 
tation,  t he  target  language,  and  t he  run-time  system,  tasks  such  as  instruction 
selection,  register  allocation  and  assignment,  and  instruction  ordering  are  en 
countered  in  the  design  of almost  all  code  generators. 

The  most  important  criterion  for  a  code  generator  is  t h at  it  produce  cor 
rect  code.  Correctness  takes  on  special  significance  because  of  the  number  of 
special  cases  t h at  a  code  generator  might  face.  Given  t he  premium  on  correct 
ness,  designing  a  code  generator  so  it  can  be  easily  implemented,  tested,  and 
maintained  is  an  important  design  goal. 

8.1. 

ISSUES  IN  THE  DESIGN  OF  A  CODE  GENERATOR 

507 

8.1.1 

Input  to  the  Code  Generator 

T he  input  to  the  code  generator  is  the  intermediate  representation  of the  source 
program  produced  by  the  front  end,  along  with  information  in  the  symbol  table 
t h at  is  used  to  determine  the  run-time  addresses  of  the  d a ta  objects  denoted 
by  t he  names  in  t he  IR. 

T he  many  choices  for  the  IR  include  three-address  representations  such  as 
quadruples,  triples,  indirect  triples;  virtual  machine  representations  such  as 
bytecodes  and  stack-machine  code;  linear  representations  such  as  postfix  no 
tation;  and  graphical  representations  such  as  syntax  trees  and  DAG's.  Many 
of  t he  algorithms  in  this  chapter  are  couched  in  terms  of  t he  representations 
considered  in  Chapter  6:  three-address  code,  trees,  and  DAG's.  The  techniques 
we  discuss  can  be  applied,  however,  to  the  other  intermediate  representations 
as  well. 

In  this  chapter,  we  assume  t h at  the  front  end  has  scanned,  parsed,  and 
translated  t he  source  program  into  a  relatively  low-level  IR,  so  t h at  t he  values 
of  the  names  appearing  in  the  IR  can  be  represented  by  quantities  t h at  the 
target  machine  can  directly  manipulate,  such  as  integers  and  floating-point 
numbers.  We  also  assume  t h at  all  syntactic  and  static  semantic  errors  have 
been  detected,  t h at  the  necessary  type  checking  has  taken  place,  and  t h at  type-
conversion  operators  have  been  inserted  wherever  necessary.  T he  code  generator 
can  therefore  proceed  on  the  assumption  t h at  its  input  is  free  of  these  kinds  of 
errors. 

8.1.2  The  Target  Program 

T he  instruction-set  architecture  of  the  target  machine  has  a  significant  im 
pact  on  the  difficulty  of  constructing  a  good  code  generator  t h at  produces 
high-quality  machine  code.  The  most  common  target-machine  architectures 
are  RISC  (reduced  instruction  set  computer),  CISC  (complex  instruction  set 
computer),  and  stack  based. 

A  RISC  machine  typically  has  many  registers,  three-address  instructions, 
simple  addressing  modes,  and  a  relatively  simple  instruction-set  architecture. 
In  contrast,  a  CISC  machine  typically  has  few  registers,  two-address  instruc 
tions,  a  variety  of  addressing  modes,  several  register  classes,  variable-length 
instructions,  and  instructions  with  side  effects. 

In  a  stack-based  machine,  operations  are  done  by  pushing  operands  onto  a 
stack  and  then  performing  the  operations  on  the  operands  at  the  top  of  the 
stack.  To  achieve  high  performance  the  top  of  the  stack  is  typically  kept  in 
registers.  Stack-based  machines  almost  disappeared  because  it  was  felt  t h at 
the  stack  organization  was  too  limiting  and  required  too  many  swap  and  copy 
operations. 

However,  stack-based  architectures  were  revived  with  the  introduction  of 
the  Java  Virtual  Machine  (JVM).  The  J VM  is  a  software  interpreter  for  Java 
bytecodes,  an  intermediate  language  produced  by  Java  compilers.  The  inter-

508 

CHAPTER  8. 

CODE  GENERATION 

preter  provides  software  compatibility  across  multiple  platforms,  a  major  factor 
in  the  success  of  Java. 

To  overcome  the  high  performance  penalty  of  interpretation,  which  can  be 
on  the  order  of  a  factor  of  10,  just-in-time  (JIT)  Java  compilers  have  been 
created.  These  J IT  compilers  translate  bytecodes  during  run  time  to  the  native 
hardware  instruction  set  of the  target  machine.  Another  approach  to  improving 
Java  performance  is  to  build  a  compiler  t h at  compiles  directly  into  the  machine 
instructions  of  the  target  machine,  bypassing  the  Java  bytecodes  entirely. 

Producing  an  absolute  machine-language  program  as  output  has  the  ad 
vantage  t h at  it  can  be  placed  in  a  fixed  location  in  memory  and  immediately 
executed.  Programs  can  be  compiled  and  executed  quickly. 

Producing  a  relocatable  machine-language  program  (often  called  an  object 
module)  as  output  allows  subprograms  to  be  compiled  separately.  A  set  of 
relocatable  object  modules  can  be  linked  together  and  loaded  for  execution  by  a 
linking  loader.  Although  we  must  pay  the  added  expense  of linking  and  loading 
if  we  produce  relocatable  object  modules,  we  gain  a  great  deal  of  flexibility 
in  being  able  to  compile  subroutines  separately  and  to  call  other  previously 
compiled  programs  from  an  object  module. 
If  the  target  machine  does  not 
handle  relocation  automatically,  the  compiler  must  provide  explicit  relocation 
information  to  the  loader  to  link  the  separately  compiled  program  modules. 

Producing  an  assembly-language  program  as  output  makes  the  process  of 
code  generation  somewhat  easier.  We  can  generate  symbolic  instructions  and 
use  the  macro  facilities  of  the  assembler  to  help  generate  code.  The  price  paid 
is  the  assembly  step  after  code  generation. 

In  this  chapter,  we  shall  use  a  very  simple  RISC-like  computer  as  our  target 
machine.  We  add  to  it  some  CISC-like  addressing  modes  so  t h at  we  can  also 
discuss  code-generation  techniques  for  CISC  machines.  For  readability,  we  use 
assembly  code  as  the  target  language  .  As  long  as  addresses  can  be  calculated 
from  offsets  and  other  information  stored  in  the  symbol  table,  the  code  gener 
ator  can  produce  relocatable  or  absolute  addresses  for  names  just  as  easily  as 
symbolic  addresses. 

8.1.3 

Instruction  Selection 

The  code  generator  must  m ap  the  IR  program  into  a  code  sequence  t h at  can  be 
executed  by  the  target  machine.  The  complexity  of performing  this  mapping  is 
determined  by  a  factors  such  as 

•  the  level  of  the  IR 

•  the  n a t u re  of  the  instruction-set  architecture 

•  the  desired  quality  of  the  generated  code. 

If  the  IR  is  high  level,  the  code  generator  may  translate  each  IR  statement 
into  a  sequence  of  machine  instructions  using  code  templates.  Such  statement-
by-statement  code  generation,  however,  often  produces  poor  code  t h at  needs 

8.1. 

ISSUES  IN  THE  DESIGN  OF  A  CODE  GENERATOR 

509 

further  optimization.  If  the  IR  reflects  some  of  the  low-level  details  of  the  un 
derlying  machine,  then  t he  code  generator  can  use  this  information  to  generate 
more  efficient  code  sequences. 

T he  n a t u re  of  t he  instruction  set  of  t he  target  machine  has  a  strong  effect 
on  t he  difficulty  of  instruction  selection.  For  example,  the  uniformity  and  com 
pleteness  of  the  instruction  set  are  important  factors. 
If  the  target  machine 
does  not  support  each  d a ta  type  in  a  uniform  manner,  then  each  exception  to 
the  general  rule  requires  special  handling.  On  some  machines,  for  example, 
floating-point  operations  are  done  using  separate  registers. 

Instruction  speeds  and  machine  idioms  are  other  important  factors. 

If  we 
do  not  care  about  the  efficiency  of  t he  target  program,  instruction  selection  is 
straightforward.  For  each  type  of three-address  statement,  we  can  design  a  code 
skeleton  t h at  defines  the  target  code  to  be  generated  for  t h at  construct.  For 
example,  every  three-address  statement  of  t he  form  x =  y + z,  where  x,  y,  and  z 
are  statically  allocated,  can  be  translated  into  the  code  sequence 

LD  RO,  y 
ADD  RO,  RO,  z 
ST  x,  RO 

//  RO  =  y 
//  RO  =  RO  +  z 
//  x  =  RO 

(load  y  into  register  RO) 
(add  z to  RO) 
(store  RO  into  x) 

This  strategy  often  produces  redundant  loads  and  stores.  For  example,  the 

sequence  of  three-address  statements 

a  =  b  +  c 
d =  a +  e 

would  be  translated  into 

LD  RO,  b 
ADD  RO,  RO,  c 
ST  a,  RO 
LD  RO,  a 
ADD  RO,  RO,  e 
ST  d,  RO 

//  RO  =  b 
//  RO  =  RO 
// a = = RO 
//  RO  =  a 
//  RO  =  RO 
// d = = RO 

Here,  the  fourth  statement  is  redundant  since  it  loads  a  value  t h at  has just  been 
stored,  and  so  is  the  third  if a  is  not  subsequently  used. 

T he  quality  of  t he  generated  code  is  usually  determined  by  its  speed  and 
size.  On  most  machines,  a  given  IR  program  can  be  implemented  by  many 
different  code  sequences,  with  significant  cost  differences  between  the  different 
implementations.  A  naive  translation  of  the  intermediate  code  may  therefore 
lead  to  correct  but  unacceptably  inefficient  target  code. 

For  example,  if  t he  target  machine  has  an  "increment"  instruction (INC), 
then  t he  three-address  statement a = a +  1  may  be  implemented  more  efficiently 
by  t he  single  instruction INC  a,  rather  t h an  by  a  more  obvious  sequence  t h at 
loads a  into  a  register,  adds  one  to  t he  register,  and  then  stores  t he  result  back 
into a: 

510 

CHAPTER  8. 

CODE  GENERATION 

LD  R0,  a 
ADD RO,  RO,  #1  // RO  = RO  +  1 
ST  a,  RO 

//  RO  =  a 

//  a =  RO 

We  need  to  know  instruction  costs  in  order  to  design  good  code  sequences 
but,  unfortunately,  accurate  cost  information  is  often  difficult  to  obtain.  De 
ciding  which  machine-code  sequence  is  best  for  a  given  three-address  construct 
may  also  require  knowledge  about  t he  context  in  which  t h at  construct  appears. 
In  Section  8.9  we  shall  see  t h at  instruction  selection  can  be  modeled  as  a 
tree-pattern  matching  process  in  which  we  represent  the  IR  and  the  machine 
instructions  as  trees.  We  then  a t t e m pt  to  "tile"  an  IR  tree  with  a  set  of  sub 
trees  t h at  correspond  to  machine  instructions.  If  we  associate  a  cost  with  each 
machine-instruction  subtree,  we  can  use  dynamic  programming  to  generate  op 
timal  code  sequences.  Dynamic  programming  is  discussed  in  Section  8.11. 

8.1.4  Register  Allocation 

A  key  problem  in  code  generation  is  deciding  what  values  to  hold  in  what 
registers.  Registers  are  the  fastest  computational  unit  on  t he  target  machine, 
but  we  usually  do  not  have  enough  of  them  to  hold  all  values.  Values  not  held 
in  registers  need  to  reside  in  memory.  Instructions  involving  register  operands 
are  invariably  shorter  and  faster  t h an  those  involving  operands  in  memory,  so 
efficient  utilization  of  registers  is  particularly  important. 

The  use  of  registers  is  often  subdivided  into  two  subproblems: 

1.  Register  allocation,  during  which  we  select  the  set  of  variables  t h at  will 

reside  in  registers  at  each  point  in  the  program. 

2.  Register  assignment,  during  which  we  pick  the  specific  register  t h at  a 

variable  will  reside  in. 

Finding  an  optimal  assignment  of  registers  to  variables  is  difficult,  even 
with  single-register  machines.  Mathematically,  the  problem  is  NP-complete. 
The  problem  is  further  complicated  because  t he  hardware  a n d / or  the  operating 
system  of t he  target  machine  may  require  t h at  certain  register-usage  conventions 
be  observed. 

E x a m p le  8 . 1:  Certain  machines  require  register-pairs  (an  even  and  next  odd-
numbered  register)  for  some  operands  and  results.  For  example,  on  some  ma 
chines,  integer  multiplication  and  integer  division  involve  register  pairs.  T he 
multiplication  instruction  is  of  t he  form 

M  x,  y 

where  x,  the  multiplicand,  is  the  even  register  of  an  even/odd  register  pair  and 
y,  the  multiplier,  is  t he  odd  register.  T he  product  occupies  t he  entire  even/odd 
register  pair.  The  division  instruction  is  of  t he  form 

8.1. 

ISSUES  IN  THE  DESIGN  OF  A  CODE  GENERATOR 

511 

D  x,  y 

where  t he  dividend  occupies  an  even/odd  register  pair  whose  even  register  is  x; 
t he  divisor  is  y.  After  division,  t he  even  register  holds  the  remainder  and  the 
odd  register  the  quotient. 

Now,  consider  t he  two  three-address  code  sequences  in  Fig. 8.2  in  which  t he 
only  difference  in  (a)  and  (b)  is  the  operator  in  the  second  statement.  The 
shortest  assembly-code  sequences  for  (a)  and  (b)  are  given  in  Fig. 8.3. 

t  =  a +  b 

t  =  t  *  c 

t  =  t/  d 

t  =  a + b 

t  = t  +  c 

t  = t  /  d 

(a) 

(b) 

Figure 8.2:  Two  three-address  code  sequences 

L 
A 

M 
D 

Rl,a 

Rl,b 

R0,c 

R0,d 

ST  Rl,t 

L 
A 

RO,  a 
RO,  b 
RO,  c 

A 
SRDA  RO,  32 

D 
ST 

RO,  d 
Rl,  t 

(a) 

(b) 

Figure 8.3:  Optimal  machine-code  sequences 

Ri  stands  for  register  i.  SRDA  stands  for  Shift-Right-Double-Arithmetic  and 
SRDA RO, 32  shifts  t he  dividend  into Rl  and  clears RO  so  all  bits  equal  its  sign 
bit.  L, ST,  and A  stand  for  load,  store,  and  add,  respectively.  Note  t h at  the 
optimal  choice  for  the  register  into  which a  is  to  be  loaded  depends  on  what 
will  ultimately  happen  to t.  • 

Strategies  for  register  allocation  and  assignment  are  discussed  in  Section 8.8. 

Section 8.10  shows  t h at  for  certain  classes  of  machines  we  can  construct  code 
sequences  t h at  evaluate  expressions  using  as  few  registers  as  possible. 

8.1.5  Evaluation  Order 

The  order  in  which  computations  are  performed  can  affect  the  efficiency  of  the 
target  code.  As  we  shall  see,  some  computation  orders  require  fewer  registers 
to  hold  intermediate  results  t h an  others.  However,  picking  a  best  order  in 
Initially,  we  shall  avoid 
the  general  case  is  a  difficult  NP-complete  problem. 

512 

CHAPTER  8. 

CODE  GENERATION 

t he  problem  by  generating  code  for  the  three-address  statements  in  t he  order 
in  which  they  have  been  produced  by  the  intermediate  code  generator. 
In 
Chapter  10,  we  shall  study  code  scheduling  for  pipelined  machines  t h at  can 
execute  several  operations  in  a  single  clock  cycle. 

8.2  The  Target  Language 

Familiarity  with  the  target  machine  and  its  instruction  set  is  a  prerequisite 
for  designing  a  good  code  generator.  Unfortunately,  in  a  general  discussion  of 
code  generation  it  is  not  possible  to  describe  any  target  machine  in  sufficient 
detail  to  generate  good  code  for  a  complete  language  on  t h at  machine. 
In 
this  chapter,  we  shall  use  as  a  target  language  assembly  code  for  a  simple 
computer  t h at  is  representative  of many  register  machines.  However,  the  code-
generation  techniques  presented  in  this  chapter  can  be  used  on  many  other 
classes  of  machines  as  well. 

8.2.1  A  Simple  Target  Machine  Model 

Our  target  computer  models  a  three-address  machine  with  load  and  store  oper 
ations,  computation  operations,  j u mp  operations,  and  conditional  jumps.  The 
underlying  computer  is  a  byte-addressable  machine  with  n  general-purpose  reg 
isters,  R 0 , R 1 , . ..  ,Rn  -  1.  A  full-fledged  assembly  language  would  have  scores 
of  instructions.  To  avoid  hiding  the  concepts  in  a  myriad  of  details,  we  shall 
use  a  very  limited  set  of instructions  and  assume  t h at  all  operands  are  integers. 
Most  instructions  consists  of  an  operator,  followed  by  a  target,  followed  by  a 
list  of  source  operands.  A  label  may  precede  an  instruction.  We  assume  t he 
following  kinds  of  instructions  are  available: 

•  Load  operations:  T he  instruction LD  dst,  addr  loads  the  value  in  location 
addr into  location  dst  This  instruction  denotes  the  assignment  dst  =  addr. 
The  most  common  form  of this  instruction  is LD  r, x  which  loads  the  value 
in  location  x  into  register  r.  An  instruction  of  the  form LD  r±,r2  is  a 
register-to-register  copy  in  which  the  contents  of  register  r2  are  copied 
into  register  r\. 

•  Store  operations:  T he  instruction ST  x, r  stores  the  value  in  register  r  into 

t he  location  x.  This  instruction  denotes  the  assignment  x  =  r. 

•  Computation  operations  of  the  form  OP  dst,  src\,src2,  where  OP  is  a  op 
erator like ADD  or SUB,  and  dst,  srcy,  and  src2  are  locations,  not  necessarily 
distinct.  The  effect  of  this  machine  instruction  is  to  apply  t he  operation 
represented  by  OP  to  the  values  in  locations  srci  and  src2,  and  place  the 
result  of  this  operation  in  location  dst.  For  example,  SUB  n,r2,r3  com 
putes  n  =  r2  -  r3.  Any  value  formerly  stored  in  n  is  lost,  but  if  r\  is 
r2  or  r3,  t he  old  value  is  read  first.  Unary  operators  t h at  take  only  one 
operand  do  not  have  a  src2. 

8.2. 

THE  TARGET  LANGUAGE 

513 

•  Unconditional  jumps:  T he  instruction  BR  L  causes  control  to  branch  to 

t he  machine  instruction  with  label  L.  (BR  stands  for  branch.) 

•  Conditional  jumps  of  the  form  Bcond  r,  L,  where  r  is  a  register,  L  is  a  label, 
and  cond  stands  for  any  of  t he  common  tests  on  values  in  t he  register  r. 
For  example,  BLTZ  r,  L  causes  a j u mp  to  label  L  if t he  value  in  register  r  is 
less  t h an  zero,  and  allows  control  to  pass  to  the  next  machine  instruction 
if  not. 

We  assume  our  target  machine  has  a  variety  of  addressing  modes: 

•  In  instructions,  a  location  can  be  a  variable  name  x  referring  to  the  mem 

ory  location  t h at  is  reserved  for  x  (that  is,  the  /-value  of  x). 

•  A  location  can  also  be  an  indexed  address  of  the  form  a(r),  where  a  is 
a  variable  and  r  is  a  register.  T he  memory  location  denoted  by  a(r)  is 
computed  by  taking  the  I-value  of  a  and  adding  to  it  the  value  in  register 
r.  For  example,  the  instruction  LD  R l,  a(R2)  has  the  effect  of  setting 
Rl  =  contents (a  +  contents (R2)),  where  contentsix)  denotes  the  contents 
of  the  register  or  memory  location  represented  by  x.  TJiis  addressing 
mode  is  useful  for  accessing  arrays,  where  a  is  the  base  address  of  the 
array  (that  is,  t he  address  of  t he  first  element),  and  r  holds  t he  number 
of  bytes  past  t h at  address  we  wish  to  go  to  reach  one  of  t he  elements  of 
array  a. 

•  A  memory  location  can  be  an  integer  indexed  by  a  register.  For  ex 
ample,  LD  R l, 100(R2)  has  t he  effect  of  setting  Rl  =  contents(100  + 
contents(R2)),  t h at  is,  of  loading  into  Rl  the  value  in  t he  memory  loca 
tion  obtained  by  adding 100  to  the  contents  of  register R2.  This  feature 
is  useful  for  following  pointers,  as  we  shall  see  in  the  example  below-

•  We  also  allow  two  indirect  addressing  modes:  *r  means  t he  memory  lo 
cation  found  in  the  location  represented  by  the  contents  of  register  r  and 
*100(r)  means  the  memory  location  found  in  the  location  obtained  by 
adding 100  to  the  contents  of r.  For  example,  LD  R l, *100(R2)  has  the 
effect  of  setting  Rl  =  contents(contents(10Q  +  contents(R2))),  t h at  is,  of 
loading  into  Rl  t he  value  in  the  memory  location  stored  in  the  memory 
location  obtained  by  adding 100  to  the  contents  of  register R2. 

•  Finally,  we  allow  an  immediate  constant  addressing  mode.  T he  constant 
is  prefixed  by  #.  T he  instruction  LD  R l, #100  loads  the  integer 100  into 
register  Rl,  and  ADD  R l,  R l, #100  adds  the  integer 100  into  register  Rl. 

' 

Comments  at  the  end  of  instructions  are  preceded  by  / /. 

E x a m p le  8.2  :  T he  three-address  statement  x  =  y  -  z  can  be  implemented  by 
t he  machine  instructions: 

514 

CHAPTER  8. 

CODE  GENERATION 

LD  Rl,  y 

LD  R2,  z 

SUB Rl, Rl, R2 

ST  x,  Rl 

// Rl = y 
// R2 = z 
// Rl = Rl  - R2 
//  x  =  Rl 

We  can  do  better,  perhaps.  One  of the  goals  of a good  code-generation  algorithm 
is  to  avoid  using  all  four  of these  instructions,  whenever  possible.  For  example, 
y  a n d / or z  may  have  been  computed  in  a  register,  and  if so  we  can  avoid  the LD 
step(s).  Likewise,  we  might  be  able  to  avoid  ever  storing  x  if  its  value  is  used 
within  the  register  set  and  is  not  subsequently  needed. 

Suppose  a  is  an  array  whose  elements  are  8-byte  values,  perhaps  real  num 
bers.  Also  assume  elements  of  a  are  indexed  starting  at  0.  We  m ay  execute  t he 
three-address  instruction  b  =  a [ i]  by  the  machine  instructions: 

LD  Rl,  i 

// Rl = i 

MUL Rl,  Rl,  8 
LD  R2,  a(Rl) 
ST  b,  R2 

// Rl = Rl  *  8 
// R2 = contents(a  + contents(Rl)) 
//  b  =  R2 

T h at  is,  t he  second  step  computes  Si,  and  the  third  step  places  in  register R2 
the  value  in  the  zth  element  of  a  —  the  one  found  in  the  location  t h at  is  8i 
bytes  past  the  base  address  of  the  array  a. 

Similarly,  the  assignment  into  the  array  a  represented  by  three-address  in 

struction  a [ j]  =  c  is  implemented  by: 

LD  Rl,  c 

LD  R2,  j 

// Rl = c 

// R2 = j 

MUL R2,  R2,  8 
a( R 2 ),  Rl 
ST 

// R2 = R2 *  8 
//  contents(a  +  contents(R2))  =  Rl 

To  implement  a  simple  pointer  indirection,  such  as  t he  three-address  state 

ment  x  =  *p,  we  can  use  machine  instructions  like: 

LD  Rl,  p 
LD  R2,  0(R1) 

// Rl  =  p 
// R2 = contents(0 + contents(Rl)) 

ST  x,  R2 

//  x  =  R2 

The  assignment  through  a  pointer  *p  =  y  is  similarly  implemented  in  machine 

code  by: 

LD  Rl,  p 
LD  R2,  y 

// Rl  =  p 
//  R2  =  y 

ST  0(R1),  R2 

//  contents(0  +  contents(Rl))  =  R2 

Finally,  consider  a  conditional-jump  three-address  instruction  like 

if x < y goto L 

8.2. 

THE  TARGET  LANGUAGE 

515 

T he  m a c h i n e - c o de  equivalent  w o u ld  be  s o m e t h i ng  like: 

LD  R l,  x 

LD  R 2,  y 

SUB  R l,  R l,  R2 
BLTZ  R l,  M 

//  Rl  =  x 
//  R2  =  y 
//  Rl  =  Rl  -  R2 
// 

if  Rl  <  0  jump  to  M 

Here,  M  is  t he  label  t h at  represents  t he  first  m a c h i ne  i n s t r u c t i on  g e n e r a t ed  from 

t he  t h r e e - a d d r e ss  i n s t r u c t i on  t h at  h as  label  L.  As  for  a ny  t h r e e - a d d r e ss  instruc 

t i o n,  we  h o pe  t h at  we  c an  save  s o me  of  t h e se  m a c h i ne  i n s t r u c t i o ns  b e c a u se  t he 

n e e d ed  o p e r a n ds  are  already  in  registers  or  b e c a u se  t he  result  n e ed  never  be 

stored. 

• 

8.2.2  Program  and  Instruction  Costs 

We  often  a s s o c i a te  a  cost  w i th  c o m p i l i ng  and  r u n n i ng  a  p r o g r a m.  D e p e n d i ng 

on  w h at  a s p e ct  of  a  p r o g r am  we  are  interested  in  o p t i m i z i n g,  s o me  c o m m on 

cost  m e a s u r es  are  t he  l e n g th  of  c o m p i l a t i on  t i me  a nd  t he  size,  r u n n i ng  t i me 

a nd  p o w er  c o n s u m p t i on  of  t he  t a r g et  p r o g r a m. 

D e t e r m i n i ng  t he  a c t u al  cost  of  c o m p i l i ng  a nd  r u n n i ng  a  p r o g r am  is  a  c o m 

p l ex  p r o b l e m.  F i n d i ng  an  o p t i m al  t a r g et  p r o g r am  for  a  g i v en  source  p r o g r am  is 

an  u n d e c i d a b le  p r o b l em  in  general,  a nd  m a ny  of  t he  s u b p r o b l e ms  i n v o l v ed  are 

N P - h a r d.  As  we  h a ve  i n d i c a t e d,  in  c o de  g e n e r a t i on  we  m u st  often  be  c o n t e nt 

w i th  heuristic  t e c h n i q u es  t h at  p r o d u ce  g o od  but  n ot  necessarily  o p t i m al  t a r g et 

p r o g r a m s. 

For  t he  r e m a i n d er  of  t h is  chapter,  we  shall  a s s u me  e a ch  t a r g e t - l a n g u a ge 

i n s t r u c t i on  h as  an  a s s o c i a t ed  cost.  For  simplicity,  we  t a ke  t he  cost  of  an  in 

s t r u c t i on  to  be  o ne  plus  t he  c o s ts  a s s o c i a t ed  w i th  t he  a d d r e s s i ng  m o d es  of  t he 

o p e r a n d s.  T h is  cost  c o r r e s p o n ds  to  t he  l e n g th  in  w o r ds  of  t he  i n s t r u c t i o n. 

A d d r e s s i ng  m o d es  i n v o l v i ng  registers  h a ve  zero  a d d i t i o n al  c o s t,  w h i le  t h o se  in 

v o l v i ng  a  m e m o ry  l o c a t i on  or  c o n s t a nt  in  t h em  h a ve  an  a d d i t i o n al  cost  of  o n e, 

b e c a u se  such  o p e r a n ds  h a ve  to  be  stored  in  t he  words  following  t he  i n s t r u c t i o n. 

S o me  e x a m p l e s: 

•  T he  i n s t r u c t i on  LD  RO,  Rl  copies  t he  c o n t e n ts  of  register  Rl  i n to  register 
RO.  T h is  i n s t r u c t i on  has  a  cost  of  o ne  b e c a u se  no  a d d i t i o n al  m e m o ry 
w o r ds  are  required. 

•  T he  i n s t r u c t i on  LD  RO,  M  l o a ds  t he  c o n t e n ts  of  m e m o ry  l o c a t i on  M  i n to 
register  RO.  T he  cost  is  t wo  since  t he  address  of  m e m o ry  l o c a t i on  M  is  in 
t he  w o rd  following  t he  i n s t r u c t i o n. 

•  T he  i n s t r u c t i on  LD  R l,  * 1 0 0 ( R 2)  loads  into  register  Rl  t he  value  g i v en 

by  contents(contents(100  +  contents(K2))).  T he  cost 
c o n s t a nt  100  is  stored  in  t he  word  following  t he  i n s t r u c t i o n. 

is  t h r ee  b e c a u se  t he 

516 

CHAPTER  8. 

CODE  GENERATION 

In  this  chapter  we  assume  t he  cost  of  a  target-language  program  on  a  given 

input  is  the  sum  of  costs  of  t he  individual  instructions  executed  when  t he  pro 
gram  is  run  on  t h at  input.  Good  code-generation  algorithms  seek  to  minimize 
the  sum  of  the  costs  of  the  instructions  executed  by  the  generated  target  pro 
gram  on  typical  inputs.  We  shall  see  t h at  in  some  situations  we  can  actually 
generate  optimal  code  for  expressions  on  certain  classes  of  register  machines. 

8.2.3  Exercises  for  Section  8.2 

E x e r c i se  8 . 2 . 1:  Generate  code  for  t he  following  three-address  statements  as 
suming  all  variables  are  stored  in  memory  locations. 

a)  x  =  1 

b)  x  =  a 

c)  x  =  a  +  1 

d)  x  =  a  +  b 

e)  T he  two  statements 

x  =  b  *  c 
y  =  a  +  x 

E x e r c i se  8 . 2 . 2:  Generate  code  for  t he  following  three-address  statements  as 
suming  a  and  b  are  arrays  whose  elements  are  4-byte  values. 

a)  T he  four-statement  sequence 

x  =  a [ i] 
y  =  b [ j] 
a [ i]  =  y 
b [ j]  =  x 

b)  T he  three-statement  sequence 

x  =  a [ i] 
y  =  b [ i] 
z  =  x  *  y 

c)  T he  three-statement  sequence 

x  =  a [ i] 
y  =  b [ x] 
a [ i]  =  y 

8.2. 

THE  TARGET  LANGUAGE 

517 

Exercise  8 . 2 . 3:  Generate  code  for  the  following  three-address  sequence  as 
suming  t h at p  and q  are  in  memory  locations: 

y =  *q 
q =  q +  4 
*p = y 
p = p +  4 

Exercise  8 . 2 . 4:  Generate  code  for  the  following  sequence  assuming  t h at x, y, 
and z  are  in  memory  locations: 

if  x  <  y goto  LI 
z  =  0 
goto  L2 

LI: z = 1 

Exercise  8 . 2 . 5:  Generate  code  for  the  following  sequence  assuming  h at  n  is 
in  a  memory  location: 

s  = 0 
i = 0 

LI:  if  i  >  n goto L2 

s = s + i 
i = i +  1 
goto  LI 

L2: 

Exercise  8 . 2 . 6:  Determine  the  costs  of  the  following  instruction  sequences: 

a) 

b) 

c) 

d) 

LD  RO,  y 
LD  Rl,  z 
ADD RO, RO, Rl 
ST  x,  RO 

LD  RO,  i 
MUL RO, RO,  8 
LD  Rl,  a(R0) 
ST  b,  Rl 

LD  RO,  c 
LD  Rl,  i 
MUL Rl, Rl, 8 
a( R l ),  RO 
ST 

LD RO, p 
LD Rl,  0(R0) 
ST x,  Rl 

CHAPTER  8. 

CODE  GENERATION 

518 

f) 

LD  RO,  p 
LD  R l,  x 
ST  0 ( R 0 ),  Rl 

RO,  x 
LD 
LD 
R l,  y 
SUB  RO,  RO,  Rl 
BLTZ  *R3,  RO 

8.3  Addresses  in  the  Target  Code 

In  this  section,  we  show  how  names  in  the  IR  can  be  converted  into  addresses 
in  the  target  code  by  looking  at  code  generation  for  simple  procedure  calls  and 
returns  using  static  and  stack  allocation.  In  Section  7.1,  we  described  how  each 
executing  program  runs  in  its  own  logical  address  space  t h at  was  partitioned 
into  four  code  and  d a ta  areas: 

1.  A  statically  determined  area  Code  t h at  holds  the  executable  target  code. 

The  size  of  the  target  code  can  be  determined  at  compile  time. 

2.  A  statically  determined  d a ta  area  Static  for  holding  global  constants  and 
other  d a ta  generated  by  t he  compiler.  T he  size  of  the  global  constants 
and  compiler  d a ta  can  also  be  determined  at  compile  time. 

3.  A  dynamically  managed  area  Heap  for  holding  d a ta  objects  t h at  are  allo 
cated  and  freed  during  program  execution.  T he  size  of  the  Heap  cannot 
be  determined  at  compile  time. 

4.  A  dynamically  managed  area  Stack  for  holding  activation  records  as  they 
are  created  and  destroyed  during  procedure  calls  and  returns.  Like  the 
Heap,  the  size  of  the  Stack  cannot  be  determined  at  compile  time. 

8.3.1 

Static  Allocation 

To  illustrate  code  generation  for  simplified  procedure  calls  and  returns,  we  shall 
focus  on  the  following  three-address  statements: 

•  c a ll  callee 

•  return 

•  h a lt 

•  a c t i o n,  which  is  a  placeholder  for  other  three-address  statements. 

The  size  and  layout  of  activation  records  are  determined  by  the  code  gener 
ator  via  the  information  about  names  stored  in  t he  symbol  table.  We  shall  first 
illustrate  how  to  store  the  return  address  in  an  activation  record  on  a  procedure 

8.3. 

ADDRESSES  IN  THE  TARGET  CODE 

519 

call  and  how  to  return  control  to  it  after  the  procedure  call.  For  convenience, 
we  assume  the  first  location  in  the  activation  holds  the  return  address. 

Let  us  first  consider  the  code  needed  to  implement  the  simplest  case,  static 
allocation.  Here,  a call  callee  statement  in  the  intermediate  code  can  be  im 
plemented  by  a  sequence  of  two  target-machine  instructions: 

ST  callee.  static  Area,  #here  + 20 
BR  callee.  code  Area 

T he ST  instruction  saves  the  return  address  at  the  beginning  of the  activation 
record  for  callee,  and  the BR  transfers  control  to  the  target  code  for  the  called 
procedure  callee.  T he  a t t r i b u te  before  callee.  static  Area  is  a  constant  t h at  gives 
the  address  of t he  beginning  of t he  activation  record  for  callee,  and  t he  a t t r i b u te 
callee.  code  Area  is  a  constant  referring  to  the  address  of  t he  first  instruction  of 
the  called  procedure  callee  in  the  Code  area  of  the  run-time  memory. 

The  operand  #here+ 20  in  the ST  instruction  is  the  literal  return  address;  it 
is  the  address  of  the  instruction  following  the BR  instruction.  We  assume  t h at 
#here  is  t he  address  of  the  current  instruction  and  t h at  the  three  constants  plus 
t he  two  instructions  in  t he  calling  sequence  have  a length  of 5  words  or 20  bytes. 
T he  code  for  a  procedure  ends  with  a  return  to  t he  calling  procedure,  except 
t h at  the  first  procedure  has  no  caller,  so  its  final  instruction  is HALT,  which 
returns  control  to  the  operating  system.  A return  callee  statement  can  be 
implemented  by  a  simple  j u mp  instruction 

BR *  callee.  static  Area 

which  transfers  control  to  the  address  saved  at  t he  beginning  of  t he  activation 
record  for  callee. 

E x a m p le  8 . 3:  Suppose  we  have  t he  following  three-address  code: 

//  code  for c 

//  code  for  p 

actioni 
call  p 
a c t i o n2 
halt 

actions 
return 

Figure 8.4  shows  the  target  program  for  this  three-address  code.  We  use  the 
pseudoinstruction ACTION  to  represent  the  sequence  of  machine  instructions  to 
execute  the  statement action,  which  represents  three-address  code  t h at  is  not 
relevant  for  this  discussion.  We  arbitrarily  start  t he  code  for  procedure c  at 
address 100  and  for  procedure  p  at  address 200.  We  t h at  assume  each ACTION 
instruction  takes 20  bytes.  We  further  assume  t h at  the  activation  records  for 
these  procedures  are  statically  allocated  starting  at  locations 300  and 364,  re 
spectively. 

T he  instructions  starting  at  address 100  implement  t he  statements 

520 

CHAPTER  8. 

CODE  GENERATION 

a c t i o n i;  c a ll  p;  actiori2;  h a lt 

of the  first  procedure  c.  Execution  therefore  starts  with  the  instruction  ACTIONi 
at  address  100.  T he  ST  instruction  at  address  120  saves  the  return  address  140 
in  the  machine-status  field,  which  is  the  first  word  in  t he  activation  record  of p. 
T he  BR  instruction  at  address  132  transfers  control  t he  first  instruction  in  t he 
target  code  of  the  called  procedure  p. 

ST  3 6 4,  #140 

100:  ACTIONi 
120: 
132:  BR  200 
140:  ACTI0N2 
160:  HALT 

200:  ACTION3 
220:  BR  *364 

300: 
304: 

364: 
368: 

//  code  for  c 
//  code  for  a c t i o ni 
//  save  return  address  140  in  location  364 
//  call  p 

II 

return  to  operating  system 

//  code  for  p 

II  return  to  address  saved  in  location  364 

//  300-363  hold  activation  record  for  c 
// 
// 

return  address 
local  d a ta  for  c 

//  364-451  hold  activation  record  for  p 
// 
// 

return  address 
local  d a ta  for  p 

Figure  8.4:  Target  code  for  static  allocation 

After  executing ACTION3,  the  j u mp  instruction  at  location  220  is  executed. 
Since  location  140  was  saved  at  address  364  by  t he  call  sequence  above,  *364 
represents  140  when  the  BR  statement  at  address  220  is  executed.  Therefore, 
when  procedure  p  terminates,  control  returns  to  address  140  and  execution  of 
procedure  c  resumes. 

• 

8.3.2 

Stack  Allocation 

Static  allocation  can  become  stack  allocation  by  using  relative  addresses  for 
storage  in  activation  records.  In  stack  allocation,  however,  the  position  of  an 
activation  record  for  a  procedure  is  not  known  until  run  time.  This  position  is 
usually  stored  in  a  register,  so  words  in  t he  activation  record  can  be  accessed  as 
offsets  from  the  value  in  this  register.  The  indexed  address  mode  of  our  target 
machine  is  convenient  for  this  purpose. 

Relative  addresses  in  an  activation  record  can  be  taken  as  offsets  from  any 
known  position  in  the  activation  record,  as  we  saw  in  Chapter  7.  For  conve-

8.3. 

ADDRESSES  IN  THE  TARGET  CODE 

521 

nience,  we  shall  use  positive  offsets  by  maintaining  in  a  register SP  a  pointer  to 
the  beginning  of  the  activation  record  on  top  of  the  stack.  W h en  a  procedure 
call  occurs,  the  calling  procedure  increments SP  and  transfers  control  to  t he 
called  procedure.  After  control  returns  to  the  caller,  we  decrement SP,  thereby 
deallocating  t he  activation  record  of  t he  called  procedure. 

The  code  for  the  first  procedure  initializes  the  stack  by  setting SP  to  the 

start  of  the  stack  area  in  memory: 

LD  SP, 
code  for  the  first  procedure 
HALT 

ftstackStart 

II 

initialize  the  stack 

// 

terminate  execution 

A  procedure  call  sequence increments SP,  saves the  return  address,  and  transfers 
control  to  the  called  procedure: 

ADD  SP,  SP,  #caller.recordSize 
ST  *SP,  #here + 16 
BR 
code 
callee. 

Area 

II  increment  stack  pointer 

//  save  return  address 
return  to  caller 
II 

T he  operand  t caller.recordSize  represents  the  size  of  an  activation  record,  so 
t he ADD  instruction  makes SP  point  to  the  next  activation  record.  T he  operand 
there +16  in  the ST  instruction  is  the  address  of  the  instruction  following BR; 
it  is  saved  in  the  address  pointed  to  by SP. 

T he  r e t u rn  sequence  consists  of  two  p a r t s.  T he  called  procedure  transfers 

control  to  the  return  address  using 

BR  *0(SP) 

// 

return  to  caller 

T he  reason  for  using *0(SP)  in  the BR  instruction  is  t h at  we  need  two  levels 
of  indirection:  0(SP)  is  the  address  of  the  first  word  in  the  activation  record 
a nd *0(SP)  is  t he  r e t u rn  address  saved  there. 

The  second  p a rt  of  the  return  sequence  is  in  the  caller,  which  decrements 
SP,  thereby  restoring SP  to  its  previous  value.  T h at  is,  after  the  subtraction SP 
points  to  the  beginning  of  the  activation  record  of  the  caller: 

SUB  SP,  SP,  #caller.recordSize 

II  decrement  stack  pointer 

Chapter  7  contains  a  broader  discussion  of  calling  sequences  and  t he  trade 

offs  in  the  division  of  labor  between  the  calling  and  called  procedures. 

E x a m p le  8 . 4:  T he  program  in  Fig.  8.5  is  an  abstraction  of  the  quicksort 
program  in  the  previous  chapter.  Procedure  q  is  recursive,  so  more  t h an  one 
activation  of  q  can  be  alive  at  the  same  time. 

Suppose  t h at  the  sizes  of  the  activation  records  for  procedures m,  p,  and q 
have  been  determined  to  be  msize,  psize,  and  qsize,  respectively.  T he  first  word 
in  each  activation  record  will  hold  a  return  address.  We  arbitrarily  assume  t h at 
the code for these procedures starts at addresses 100, 200, and 300,  respectively, 

522 

CHAPTER  8. 

CODE  GENERATION 

//  code  for  m 

//  code  for  p 

//  code  for  q 

a c t i o ni 
c a ll  q 
actiori2 
h a lt 

a c t i o ns 
r e t u rn 

a c t i o n4 
c a ll  p 
a c t i o ns 
c a ll  q 
a c t i o ns 
c a ll  q 
r e t u rn 

Figure  8.5:  Code  for  Example  8.4 

and  t h at  t he  stack  starts  at  address  600.  T he  target  program  is  shown  in 
Figure  8.6. 

We  assume  t h at  ACTION4  contains  a  conditional j u mp  to  t he  address  456  of 
the  return  sequence  from  q;  otherwise,  t he  recursive  procedure  q  is  condemned 
to  call  itself  forever. 

If  msize,  psize,  and  qsize  are  20,  40,  and  60,  respectively,  t he  first  instruction 
at  address  100  initializes  the  SP  to  600,  t he  starting  address  of  t he  stack.  SP 
holds  620  j u st  before  control  transfers  from  m  to  q,  because  msize  is  20.  Sub 
sequently,  when  q  calls  p,  t he  instruction  at  address  320  increments  SP  to  680, 
where  the  activation  record  for  p  begins;  SP  reverts  to  620  after  control  returns 
to  q.  If the  next  two  recursive  calls  of q  r e t u rn  immediately,  t he  maximum  value 
of SP  during  this  execution  680.  Note,  however,  t h at  the  last  stack  location  used 
is  739,  since  t he  activation  record  of  q  starting  at  location  680  extends  for  60 
bytes. 

• 

8.3.3  Run-Time  Addresses  for  Names 

T he  storage-allocation  strategy  and  the  layout  of  local  d a ta  in  an  activation 
record  for  a  procedure  determine  how  the  storage  for  names  is  accessed. 
In 
Chapter  6,  we  assumed  t h at  a  n a me  in  a  three-address  statement  is  really  a 
pointer  to  a  symbol-table  entry  for  t h at  name.  This  approach  has  a  significant 
advantage;  it  makes  the  compiler  more  portable,  since  t he  front  end  need  not 
be  changed  even  when  t he  compiler  is  moved  to  a  different  machine  where  a 
different  run-time  organization  is  needed.  On  the  other  hand,  generating  t he 
specific  sequence  of  access  steps  while  generating  intermediate  code  can  be  of 

8.3. 

ADDRESSES  IN  THE  TARGET  CODE 

523 

100-
108 
128 
136 
144 
152 
160 
180 

LD SP,  #600 
ACTIONi 
ADD  SP,  SP,  #msize 
ST  *SP,  #152 
BR  300 
SUB  SP,  SP,  ftmsize 
ACTIONi 2 
HALT 

initialize  t he  stack 

/ /  code  for  m 
// 
//  code  for  a c t i o ni 
//  call  sequence  begins 
//  push  return  address 
//  call  q 
// 

restore  SP 

200 

220 

ACTION3 

BR  *0(SP) 

//  code  for  p 

// 

return 

ACTION4 
ADD  SP,  SP,  ftqsize 
ST  *SP,  #344 
BR  200 
SUB  SP,  SP,  #qsize 
ACTION5 
ADD  SP,  SP,  #qsize 
BR  *SP,  #396 
BR  300 
SUB  SP,  SP,  ftqsize 
ACTI0N6 
ADD  SP,  SP,  #qsize 
ST  *SP,  #440 
BR  300 
SUB  SP,  SP,  #qsize 
BR  *0(SP) 

300 
320 
328 
336 
344 
352 
372 
380 
388 
396 
404 
424 
432 
440 
448 
456 

600: 

//  code  for  q 
//  contains  a  conditional  j u mp  to  456 

//  push  return  address 
/ /  call  p 

/ /  push  return  address 
//  call  q 

//  push  return  address 
//  call  q 

// 

return 

// 

stack  starts  here 

Figure  8.6:  Target  code  for  stack  allocation 

524 

CHAPTER  8. 

CODE  GENERATION 

significant  advantage  in  an  optimizing  compiler,  since  it  lets  t he  optimizer  take 
advantage  of  details  it  would  not  see  in  the  simple  three-address  statement. 

In  either  case,  names  must  eventually  be  replaced  by  code  to  access  storage 
locations.  We  thus  consider  some  elaborations  of the  simple  three-address  copy 
statement  x  =  0.  After  the  declarations  in  a  procedure  are  processed,  suppose 
the  symbol-table  entry  for  x  contains  a  relative  address  12  for  x.  For  consider 
the  case  in  which  x  is  in  a  statically  allocated  area  beginning  at  address  static. 
Then  the  actual  run-time  address  of  x  is  static +12.  Although  t he  compiler  can 
eventually  determine  the  value  of  static  +  12  at  compile  time,  the  position  of 
the  static  area  may  not  be  known  when  intermediate  code  to  access  the  name 
In  t h at  case,  it  makes  sense  to  generate  three-address  code  to 
is  generated. 
"compute"  static  +  12,  with  the  understanding  t h at  this  computation  will  be 
carried  out  during  t he  code  generation  phase,  or  possibly  by  the  loader,  before 
the  program  runs.  The  assignment  x  =  0  then  translates  into 

s t a t i c [ 1 2]  =  0 

If  t he  static  area  starts  at  address  100,  t he  target  code  for  this  statement  is 

LD  112,  #0 

8.3.4  Exercises  for  Section  8.3 

E x e r c i se  8 . 3 . 1:  Generate  code  for  the  following  three-address  statements  as 
suming  stack  allocation  where  register  SP  points  to  t he  top  of  the  stack. 

c a ll  p 
c a ll  q 
r e t u rn 
c a ll 
r 
r e t u rn 
r e t u rn 

E x e r c i se  8 . 3 . 2:  Generate  code  for  the  following  three-address  statements  as 
suming  stack  allocation  where  register  SP  points  to  the  top  of  t he  stack. 

a)  x  =  1 

b)  x  =  a 

c)  x  =  a  +  1 

d)  x  =  a  +  b 

e)  T he  two  statements 

8.4. 

BASIC  BLOCKS  AND  FLOW  GRAPHS 

525 

E x e r c i se  8 . 3 . 3:  Generate  code  for  t he  following  three-address  statements 
again  assuming  stack  allocation  and  assuming  a  and  b  are  arrays  whose  ele 
ments  are  4-byte  values. 

a)  T he  four-statement  sequence 

x  =  a [ i] 
y  =  b [ j] 
a [ i]  =  y 
b [ j]  =  x 

b)  T he  three-statement  sequence 

x  =  a [ i] 
y  =  b [ i] 
z  =  x  *  y 

c)  T he  three-statement  sequence 

x  =  a [ i] 
y  =  b [ x] 
a [ i]  =  y 

8.4  Basic  Blocks  and  Flow  Graphs 

This  section  introduces  a  graph  representation  of intermediate  code  t h at  is  help 
ful  for  discussing  code  generation  even  if  the  graph  is  not  constructed  explicitly 
by  a  code-generation  algorithm.  Code  generation  benefits  from  context.  We 
can  do  a  better  job  of  register  allocation  if  we  know  how  values  are  defined 
and  used,  as  we  shall  see  in  Section  8.8.  We  can  do  a  better  job  of  instruction 
selection  by  looking  at  sequences  of three-address  statements,  as  we  shall  see  in 
Section  8.9. 

T he  representation  is  constructed  as  follows: 

1.  Partition  t he  intermediate  code  into  basic  blocks,  which  are  maximal  se 
quences  of  consecutive  three-address  instructions  with  t he  properties  t h at 

(a)  T he  flow  of  control  can  only  enter  t he  basic  block  through  the  first 
instruction  in  the  block.  T h at  is,  there  are  no  jumps  into  t he  middle 
of  t he  block. 

(b)  Control  will  leave  the  block  without  halting  or  branching,  except 

possibly  at  the  last  instruction  in  the  block. 

2.  T he  basic  blocks  become  the  nodes  of  a  flow  graph,  whose  edges  indicate 

which  blocks  can  follow  which  other  blocks. 

526 

CHAPTER  8. 

CODE  GENERATION 

The  Effect  of  Interrupts 

The  notion  t h at  control,  once  it  reaches  the  beginning  of  a  basic  block  is 
certain  to  continue  through  to  t he  end  requires  a  bit  of thought.  There  are 
many  reasons  why  an  interrupt,  not  reflected  explicitly  in  the  code,  could 
cause  control  to  leave  the  block,  perhaps  never  to  return.  For  example,  an 
instruction  like  x  =  y /z  appears  not  to  affect  control  flow,  but  if  z  is  0  it 
could  actually  cause  the  program  to  abort. 

We  shall  not  worry  about  such  possibilities.  The  reason  is  as  follows. 
The  purpose  of  constructing  basic  blocks  is  to  optimize  the  code.  Gener 
ally,  when  an  interrupt  occurs,  either  it  will  be  handled  and  control  will 
come  back  to  t he  instruction  t h at  caused  the  interrupt,  as  if  control  had 
never  deviated,  or  the  program will  halt  with  an  error.  In  the  latter  case,  it 
doesn't  m a t t er  how  we  optimized  the  code,  even  if we  depended  on  control 
reaching  the  end  of  t he  basic  block,  because  t he  program  didn't  produce 
its  intended  result  anyway. 

Starting  in  Chapter  9,  we  discuss  transformations  on  flow  graphs  t h at  t u rn 
the  original  intermediate  code  into  "optimized"  intermediate  code  from  which 
better  target  code  can  be  generated.  T he  "optimized"  intermediate  code  is 
turned  into  machine  code  using  the  code-generation  techniques  in  this  chapter. 

8.4.1  Basic  Blocks 

Our  first  job  is  to  partition  a  sequence  of  three-address  instructions  into  basic 
blocks.  We  begin  a  new  basic  block  with  the  first  instruction  and  keep  adding 
instructions  until  we  meet  either  a  j u m p,  a  conditional  j u m p,  or  a  label  on 
t he  following  instruction.  In  the  absence  of j u m ps  and  labels,  control  proceeds 
sequentially  from  one  instruction  to  the  next.  This  idea  is  formalized  in  the 
following  algorithm. 

A l g o r i t hm  8.5  :  Partitioning  three-address  instructions  into  basic  blocks. 

INPUT:  A  sequence  of  three-address  instructions. 

OUTPUT:  A  list  of t he  basic  blocks  for  t h at  sequence  in  which  each  instruction 
is  assigned  to  exactly  one  basic  block. 

METHOD:  First,  we  determine  those  instructions  in  the  intermediate  code  t h at 
are  leaders,  t h at  is,  the  first  instructions  in  some  basic  block.  T he  instruction 
just  past  the  end  of  the  intermediate  program  is  not  included  as  a  leader.  The 
rules  for  finding  leaders  are: 

1.  T he  first  three-address  instruction  in  the  intermediate  code  is  a  leader. 

8.4.  BASIC  BLOCKS  AND  FLOW  GRAPHS 

527 

2.  Any  instruction  t h at  is  the  target  of  a  conditional  or  unconditional  j u mp 

is  a  leader. 

3.  Any  instruction  t h at  immediately  follows  a  conditional  or  unconditional 

j u mp  is  a  leader. 

Then,  for  each  leader,  its  basic  block  consists  of itself  and  all  instructions  up  to 
• 
but  not  including  the  next  leader  or  the  end  of  t he  intermediate  program. 

1) 
2) 

3) 
4) 
5) 
6) 
7) 
8) 
9) 
i
o) 
11) 
12) 
13) 
14) 
15) 
16) 
17) 

-  88 

i  =  1 
j  =  1 
tl  =  10  *  i 
t2  = 
tl 
+  J 
t3  =  8  *  t2 
t4  = 
t3 
a [ t 4]  =  0 .0 
j  =  j  +  1 
if  j  <=  10  g o to 
i  =  i  +  1 
if 
i 
i  =  1 
t5  =  i  -
t6  =  88  * 
a [ t 6]  =  1.0 
i  =  i  +  1 
<= 
if 

10  g o to 

10  g o to 

t5 

1 

i 

<= 

Figure  8.7:  Intermediate  code  to  set  a  10  x  10  matrix  to  an  identity  matrix 

E x a m p le  8 . 6:  T he  intermediate  code  in  Fig.  8.7  t u r ns  a  10  x  10  m a t r ix  a  into 
an  identity  matrix.  Although  it  is  not  important  where  this  code  comes  from, 
it  might  be  the  translation  of  the  pseudocode  in  Fig.  8.8. 
In  generating  the 
intermediate  code,  we  have  assumed  t h at  the  real-valued  array  elements  take  8 
bytes  each,  and  t h at  the  matrix  a  is  stored  in  row-major  form. 

for  i  from  1  to  10  do 

for  j  from  1  to  10  do 

a[i,j) 

=  0.0; 

for  i  from  1  to  10  do 

a[i,  i]  =  1.0; 

Figure  8.8:  Source  code  for  Fig.  8.7 

528 

CHAPTER  8. 

CODE  GENERATION 

First,  instruction  1  is  a  leader  by  rule  (1)  of  Algorithm  8.5.  To  find  the 
other  leaders,  we  first  need  to  find  the  jumps.  In  this  example,  there  are  three 
jumps,  all  conditional,  at  instructions  9,  11,  and  17.  By  rule  (2),  the  targets  of 
these  j u m ps  are  leaders;  they  are  instructions  3,  2,  and  13,  respectively.  Then, 
by  rule  (3),  each  instruction  following  a j u mp  is  a  leader;  those  are  instructions 
10  and  12.  Note  t h at  no  instruction  follows  17  in  this  code,  but  if  there  were 
code  following,  t he  18th  instruction  would  also  be  a  leader. 

We  conclude  t h at  the  leaders  are  instructions  1,  2,  3,  10,  12,  and  13.  The 
basic  block  of  each  leader  contains  all  the  instructions  from  itself  until  just 
before  the  next  leader.  Thus,  the  basic  block  of  1  is  just  1,  for  leader  2  t he 
block  is  just  2.  Leader  3,  however,  has  a  basic  block  consisting  of instructions  3 
through  9,  inclusive.  Instruction  10's  block  is  10  and  11;  instruction  12's  block 
is  just  12,  and  instruction  13's  block  is  13  through  17. 

• 

8.4.2  Next-Use  Information 

Knowing  when  the  value  of a variable  will  be  used  next  is  essential  for  generating 
good  code.  If  the  value  of  a  variable  t h at  is  currently  in  a  register  will  never  be 
referenced  subsequently,  then  t h at  register  can  be  assigned  to  another  variable. 
The  use of a name  in  a three-address  statement  is  defined  as  follows.  Suppose 
If  statement  j  has  x  as  an 
three-address  statement  i  assigns  a  value  to  x. 
operand,  and  control  can  flow  from  statement  i  to  j  along  a  p a th  t h at  has 
no  intervening  assignments  to  x,  then  we  say  statement  j  uses  t he  value  of  x 
computed  at  statement  i.  We  further  say  t h at  x  is  live  at  statement  i. 

We  wish  to  determine  for  each  three-address  statement  x  =  y  +  z  what  the 
next  uses  of  x,  y,  and  z  are.  For  the  present,  we  do  not  concern  ourselves  with 
uses  outside  t he  basic  block  containing  this  three-address  statement. 

Our  algorithm  to  determine  liveness  and  next-use  information  makes  a  back 
ward  pass  over  each  basic  block.  We  store  the  information  in  the  symbol  table. 
We  can  easily  scan  a  stream  of  three-address  statements  to  find  the  ends  of  ba 
sic  blocks  as  in  Algorithm  8.5.  Since  procedures  can  have  arbitrary  side  effects, 
we  assume  for  convenience  t h at  each  procedure  call  starts  a  new  basic  block. 

A l g o r i t hm  8 . 7:  Determining  the  liveness  and  next-use  information  for  each 
statement  in  a  basic  block. 

INPUT:  A  basic  block  B  of  three-address  statements.  We  assume  t h at  t he 
symbol  table  initially  shows  all  nontemporary  variables  in  B  as  being  live  on 
exit. 

OUTPUT:  At  each  statement  i:  x  =  y  +  z  in  B,  we  attach  to  i  t he  liveness  and 
next-use  information  of  x,  y,  and  z. 

METHOD:  We  start  at  t he  last  statement  in  B  and  scan  backwards  to  t he 
beginning  of  B.  At  each  statement  i:  x  =  y  +  z  in  B,  we  do  the  following: 

1.  Attach  to  statement  i  t he  information  currently  found  in  t he  symbol  table 

regarding  the  next  use  and  liveness  of  x,  y,  and  y. 

8.4. 

BASIC  BLOCKS  AND 

FLOW  GRAPHS 

529 

2.  In  the  symbol  table,  set  x  to  "not  live"  and  "no  next  use." 

3.  In  t he  symbol  table,  set  y  and  z  to  "live"  and  the  next  uses  of  y  and  z  to 

i. 

Here  we  have  used  +  as  a  symbol  representing  any  operator.  If the  three-address 
statement  i  is  of  the  form  x  =  +  y  or  x  =  y,  the  steps  are  the  same  as  above, 
ignoring  z.  Note  t h at  the  order  of  steps  (2)  and  (3)  may  not  be  interchanged 
because  x  may  be  y  or  z. 

• 

8.4.3  Flow  Graphs 

Once  an  intermediate-code  program  is  partitioned  into  basic  blocks,  we  repre 
sent  the  flow  of  control  between  them  by  a  flow  graph.  T he  nodes  of  the  flow 
graph  are  t he  basic  blocks.  There  is  an  edge  from  block  B  to  block  C  if  and 
only  if  it  is  possible  for  t he  first  instruction  in  block  C  to  immediately  follow 
t he  last  instruction  in  block  B.  There  are  two  ways  t h at  such  an  edge  could  be 
justified: 

•  There  is  a  conditional  or  unconditional  j u mp  from  the  end  of  B  to  the 

beginning  of  C. 

•  C  immediately  follows  B  in  t he  original  order  of t he  three-address  instruc 

tions,  and  B  does  not  end  in  an  unconditional  j u m p. 

We  say  t h at  B  is  a  predecessor  of  C,  and  C  is  a  successor  of  B. 

Often  we  add  two  nodes,  called  the  entry  and  exit,  t h at  do  not  correspond 
to  executable  intermediate  instructions.  There  is  an  edge  from  the  entry  to  the 
first  executable  node  of  the  flow  graph,  t h at  is,  to  the  basic  block  t h at  comes 
from  t he  first  instruction  of  the  intermediate  code.  There  is  an  edge  to  t he 
exit  from  any  basic  block  t h at  contains  an  instruction  t h at  could  be  t he  last 
executed  instruction  of  the  program.  If  the  final  instruction  of  t he  program  is 
not  an  unconditional  j u m p,  then  t he  block  containing  t he  final  instruction  of 
t he  program  is  one  predecessor  of  the  exit,  but  so  is  any  basic  block  t h at  has  a 
j u mp  to  code  t h at  is  not  part  of  the  program. 

E x a m p le  8 . 8:  The  set  of  basic  blocks  constructed  in  Example  8.6  yields  the 
flow  graph  of  Fig.  8.9.  The  entry  points  to  basic  block  B\,  since  B\  contains 
the  first  instruction  of  the  program.  The  only  successor  of  B\  is  B2,  because 
B\  does  not  end  in  an  unconditional  j u m p,  and  the  leader  of  B2  immediately 
follows  the  end  of  B\. 

Block  B3  has  two  successors.  One  is  itself,  because  the  leader  of  B3,  instruc 
tion  3,  is  the  target  of the  conditional j u mp  at  t he  end  of £3,  instruction  9.  T he 
other  successor  is  B4,  because  control  can  fall  through  the  conditional  j u mp  at 
the  end  of  B3  and  next  enter  the  leader  of  B±. 

Only  BQ  points  to  the  exit  of  the  flow  graph,  since  the  only  way  to  get  to 
code  t h at  follows  the  program  from  which  we  constructed  the  flow  graph  is  to 
fall  through  the  conditional  j u mp  t h at  ends  BG. 

• 

530 

CHAPTER  8. 

CODE  GENERATION 

ENTRY 

B2 

B3 

B4 

B5 

Be 

EXIT 

Figure  8.9:  Flow  graph  from  Fig.  8.7 

8.4.4  Representation  of  Flow  Graphs 

First,  note  from  Fig.  8.9  t h at  in  the  flow  graph,  it  is  normal  to  replace  the j u m ps 
to  instruction  numbers  or  labels  by  j u m ps  to  basic  blocks.  Recall  t h at  every 
conditional  or  unconditional  j u mp  is  to  the  leader  of  some  basic  block,  and  it 
is  to  this  block  t h at  the  j u mp  will  now  refer.  T he  reason  for  this  change  is  t h at 
after  constructing  the  flow  graph,  it  is  common  to  make  substantial  changes 
to  the  instructions  in  the  various  basic  blocks.  If j u m ps  were  to  instructions, 
we  would  have  to  fix  the  targets  of  the  jumps  every  time  one  of  t he  target 
instructions  was  changed. 

Flow  graphs,  being  quite  ordinary  graphs,  can  be  represented  by  any  of  the 
d a ta  structures  appropriate  for  graphs.  The  content  of  nodes  (basic  blocks) 
need  their  own  representation.  We  might  represent  the  content  of  a  node  by  a 

8.4. 

BASIC  BLOCKS  AND  FLOW  GRAPHS 

531 

pointer  to  the  leader  in  the  array  of  three-address  instructions,  together  with  a 
count  of  the  number  of  instructions  or  a  second  pointer  to  the  last  instruction. 
However,  since  we  may  be  changing  the  number  of  instructions  in  a  basic  block 
frequently,  it  is  likely  to  be  more  efficient  to  create  a  linked  list  of  instructions 
for  each  basic  block. 

8.4.5  Loops 

Programming-language  constructs  like  while-statements,  do-while-statements, 
and  for-statements  naturally  give  rise  to  loops  in  programs.  Since  virtually every 
program  spends  most  of its  time  in  executing  its  loops,  it  is  especially  important 
for  a  compiler  to  generate  good  code  for  loops.  Many  code  transformations 
depend  upon  t he  identification  of  "loops"  in  a  flow  graph.  We  say  t h at  a  set  of 
nodes  L  in  a  flow  graph  is  a  loop  if 

1.  There  is  a  node  in  L  called  the  loop  entry  with  the  property  t h at  no  other 
node  in  L  has  a  predecessor  outside  L.  T h at  is,  every  p a th  from  t he  entry 
of  t he  entire  flow  graph  to  any  node  in  L  goes  through  the  loop  entry. 

2.  Every  node  in  L  has  a  nonempty  path,  completely  within  L,  to  the  entry 

of  L. 

E x a m p le  8 . 9:  The  flow  graph  of  Fig.  8.9  has  three  loops: 

1.  B3  by  itself. 

2.  B6  by  itself. 

3.  {B2,  B3,  B4}. 

T he  first  two  are  single  nodes  with  an  edge  to  the  node  itself.  For  instance, 
B3  forms  a  loop  with  B3  as  its  entry.  Note  t h at  the  second  requirement  for  a 
loop  is  t h at  there  be  a  nonempty  p a th  from  B3  to  itself.  Thus,  a  single  node 
like  B2,  which  does  not  have  an  edge  B2  ->•  B2,  is  not  a  loop,  since  there  is  no 
nonempty  p a th  from  B2 

to  itself  within  {B2}. 

The  third  loop,  L  =  {B2,  B3,  B4},  has  B2  as  its  loop  entry.  Note  t h at  among 
these  three  nodes,  only  B2  has  a  predecessor,  Bi,  t h at  is  not  in  L.  Further,  each 
of  the  three  nodes  has  a  nonempty  p a th  to  B2  staying  within  L.  For  instance, 
B2  has  t he  p a th  B2  ->•  B3  ->•  B4  ->  B2. 

• 

8.4.6  Exercises  for  Section  8.4 

E x e r c i se  8 . 4. 1:  Figure  8.10  is  a  simple  matrix-multiplication  program. 

a)  Translate  the  program  into  three-address  statements  of  the  type  we  have 
been  using  in  this  section.  Assume  the  matrix  entries  are  numbers  t h at 
require  8  bytes,  and  t h at  matrices  are  stored  in  row-major  order. 

532 

CHAPTER  8. 

CODE  GENERATION 

b)  Construct  the  flow  graph  for  your  code  from  (a). 

c)  Identify  the  loops  in  your  flow  graph  from  (b). 

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

for (j=0; j<n; j++) 

c[i] [j] = 0.0; 

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

for (j=0; j<n; j++) 

for (k=0; k<n; k++) 

c[i][j]  = c[i][j]  + a[i][k]*b[k][j]; 

Figure  8.10:  A  matrix-multiplication  algorithm 

Exercise 8.4.2:  Figure  8.11  is  code  to  count  t he  number  of  primes  from  2  to 
n,  using  t he  sieve  method  on  a  suitably  large  array  a.  T h at  is,  a[i]  is TRUE  at 
the  end  only  if  there  is  no  prime  Vi  or  less  t h at  evenly  divides  i.  We  initialize 
all  a[i]  to TRUE  and  then  set  a\j]  to FALSE  if  we  find  a  divisor  of  j. 

a)  Translate  t he  program  into  three-address  statements  of  the  type  we  have 

been  using  in  this  section.  Assume  integers  require  4  bytes. 

b)  Construct  t he  flow  graph  for  your  code  from 

(a). 

c)  Identify  the  loops  in  your  flow  graph  from  (b). 

for  (i=2;  i<=n;  i++) 
a[i]  = TRUE; 

count  =  0; 
s  =  sqrt(n); 
for  (i=2;  i<=s;  i++) 

if  (a[i])  /*  i has been found to be  a prime  */  { 

count++; 
for  (j=2*i;  j<=n;  j  = j+i) 

a[j]  = FALSE;  /* no multiple of  i  is  a prime  */ 

} 

Figure 8.11:  Code  to  sieve  for  primes 

8.5. 

OPTIMIZATION  OF  BASIC  BLOCKS 

533 

8.5  Optimization  of Basic  Blocks 

We  can  often  obtain  a  substantial  improvement  in  the  running  time  of  code 
merely  by  performing  local  optimization  within  each  basic  block  by  itself.  More 
thorough  global  optimization,  which  looks  at  how  information  flows  among  t he 
basic  blocks  of  a  program,  is  covered  in  later  chapters,  starting  with  Chapter  9. 
It  is  a  complex  subject,  with  many  different  techniques  to  consider. 

8.5.1  The  DAG  Representation  of  Basic  Blocks 

Many  important  techniques  for  local  optimization  begin  by  transforming  a  basic 
block  into  a  DAG  (directed  acyclic  graph).  In  Section  6.1.1,  we  introduced  t he 
DAG  as  a  representation  for  single  expressions.  T he  idea  extends  naturally 
to  the  collection  of  expressions  t h at  are  created  within  one  basic  block.  We 
construct  a  DAG  for  a  basic  blockas  follows: 

1.  There  is  a  node  in  the  DAG  for  each  of  the  initial  values  of  the  variables 

appearing  in  the  basic  block. 

2.  There  is  a  node  N  associated  with  each  statement  s  within  the  block. 
T he  children  of  N  are  those  nodes  corresponding  to  statements  t h at  are 
the  last  definitions,  prior  to  s,  of  the  operands  used  by  s. 

3.  Node  N  is  labeled  by  the  operator  applied  at  s,  and  also  attached  to  N 
is  t he  list  of  variables  for  which  it  is  t he  last  definition  within  t he  block. 

4.  Certain  nodes  are  designated  output  nodes.  These  are  the  nodes  whose 
variables  are  live  on  exit  from  the  block;  t h at  is,  their  values  may  be 
used  later,  in  another  block  of  the  flow  graph.  Calculation  of  these  "live 
variables"  is  a  m a t t er  for  global  flow  analysis,  discussed  in  Section  9.2.5. 

T he  DAG  representation  of  a  basic  block  lets  us  perform  several  code-

improving  transformations  on  the  code  represented  by  the  block. 

a)  We  can  eliminate  local  common  subexpressions,  t h at  is,  instructions  t h at 

compute  a  value  t h at  has  already  been  computed. 

b)  We  can  eliminate  dead  code,  t h at  is,  instructions  t h at  compute  a  value 

t h at  is  never  used. 

c)  We  can  reorder  statements  t h at  do  not  depend  on  one  another;  such 
reordering  may  reduce  the  time  a  temporary  value  needs  to  be  preserved 
in  a  register. 

d)  We  can  apply  algebraic  laws  to  reorder  operands  of three-address  instruc 

tions,  and  sometimes  thereby  simplify  the  computation. 

534 

CHAPTER  8. 

CODE  GENERATION 

8.5.2  Finding  Local  Common  Subexpressions 

Common  subexpressions  can  be  detected  by  noticing,  as  a  new  node  M  is  about 
to  be  added,  whether  there  is  an  existing  node  N  with  the  same  children,  in 
the  same  order,  and  with  the  same  operator.  If  so,  TV  computes  t he  same  value 
as  M  and  may  be  used  in  its  place.  This  technique  was  introduced  as  the 
"value-number"  method  of  detecting  common  subexpressions  in  Section  6.1.1. 

E x a m p le  8. 1 0:  A  DAG  for  t he  block 

a  =  b  +  c 
b  =  a  -  d 
c  =  b  +  c 
d  =  a  -  d 

is  shown  in  Fig.  8.12.  When  we  construct  t he  node  for  the  third  statement 
c  = b + c,  we  know  t h at  the  use  of  b  in  b + c  refers  to  the  node  of  Fig.  8.12 
labeled  -,  because  t h at  is  the  most  recent  definition  of  b.  Thus,  we  do  not 
confuse  the  values  computed  at  statements  one  and  three. 

Figure  8.12:  DAG  for  basic  block  in  Example  8.10 

However,  the  node  corresponding  to  the  fourth  statement  d  = a -  d  has  the 
operator  -  and  t he  nodes  with  attached  variables a  and  do  as  children.  Since 
the  operator  and  the  children  are  the  same  as  those  for  t he  node  corresponding 
to  statement  two,  we  do  not  create  this  node,  but  add  d  to  t he  list  of definitions 
for  t he  node  labeled  —. 

• 

It  might  appear  t h a t,  since  there  are  only  three  nonleaf nodes  in  the  DAG  of 
Fig.  8.12,  t he  basic  block  in  Example  8.10  can  be  replaced  by  a  block  with  only 
three  statements.  In  fact,  if b  is  not  live  on  exit  from  the  block,  then  we  do  not 
need  to  compute  t h at  variable,  and  can  use  d  to  receive  t he  value  represented 
by  t he  node  labeled  —.  in  Fig.  8.12.  T he  block  then  becomes 

8.5. 

OPTIMIZATION  OF  BASIC  BLOCKS 

535 

However,  if  b o th  b  and  d  are  live  on  exit,  then  a  fourth  statement  must  be 

used  to  copy  t he  value  from  one  to  the  other.1 

E x a m p le 8.11:  W h en  we  look  for  common  subexpressions,  we  really  are  look 
ing  for  expressions  t h at  are  guaranteed  to  compute  the  same  value,  no  m a t t er 
how  t h at  value  is  computed.  Thus,  the  DAG  method  will  miss  the  fact  t h at  the 
expression  computed  by  the  first  and  fourth  statements  in  the  sequence 

a  =  b  +  c; 
b  =  b  -  d 
c  =  c  +  d 
e  =  b  +  c 

is  the  same,  namely  bo 4- en.  T h at  is,  even  though  b  and  c  b o th  change  between 
t he  first  and  last  statements,  their  sum  remains  the  same,  because  b  +  c  = 
(b  -  d)  +  (c  +  d).  The  DAG  for  this  sequence  is  shown  in  Fig.  8.13,  but  does 
not  exhibit  any  common  subexpressions.  However,  algebraic  identities  applied 
to  t he  DAG,  as  discussed  in  Section  8.5.4,  may  expose  the  equivalence. 

• 

bo 

co 

do 

Figure  8.13:  DAG  for  basic  block  in  Example  8.11 

8.5.3  Dead  Code  Elimination 

The  operation  on  DAG's  t h at  corresponds  to  dead-code  elimination  can  be  im 
plemented  as  follows.  We  delete  from  a  DAG  any  root  (node  with  no  ancestors) 
t h at  has  no  live  variables  attached.  Repeated  application  of this  transformation 
will  remove  all  nodes  from  the  DAG  t h at  correspond  to  dead  code. 

E x a m p le 8.12:  If,  in  Fig.  8.13, a  and  b  are  live  but  c  and  e  are  not,  we  can 
immediately  remove  the  root  labeled  e.  Then,  t he  node  labeled  c  becomes  a 
root  and  can  be  removed.  The  roots  labeled a  and  b  remain,  since  they  each 
have  live  variables  attached. 

• 

1In  general,  we  must  be  careful,  when  reconstructing  code  from  D A G ' s,  how  we  choose 
the  names  of variables.  If  a  variable  x  is  defined  twice,  or  if  it  is  assigned  once  and  the  initial 
value  xq  is  also  used,  then  we  must  make  sure  that  we  do  not  change  the  value  of  x  until  we 
have  made  all  uses  of  the  node  whose  value  x  previously  held. 

5 36 

CHAPTER  8. 

CODE  GENERATION 

8.5.4  The  Use  of  Algebraic  Identities 

Algebraic  identities  represent  another  important  class  of optimizations  on  basic 
blocks.  For  example,  we  may  apply  arithmetic  identities,  such  as 

x  +  0  =  0  +  x  -  x 
xxl  =  lxx  =  x 

x  -  0  =  x 
x/1  =  x 

to  eliminate  computations  from  a  basic  block. 

Another  class  of  algebraic  optimizations  includes  local  reduction  in  strength, 

t h at  is,  replacing  a  more  expensive  operator  by  a  cheaper  one  as  in: 

E X P E N S I VE 
x2 
2  x  x 
x/2 

C H E A P ER 

xxx 
x  +  x 
x  x  0 .5 

= 
= 
= 

A  third  class  of  related  optimizations  is  constant  folding.  Here  we  evaluate 
constant  expressions  at  compile  time  and  replace  the  constant  expressions  by 
their  values.2  Thus  the  expression  2  *  3 . 14  would  be  replaced  by  6 . 2 8.  Many 
constant  expressions  arise  in  practice  because  of  the  frequent  use  of  symbolic 
constants  in  programs. 

T he  DAG-construction  process  can  help  us  apply  these  and  other  more 
general  algebraic  transformations  such  as  commutativity  and  associativity.  For 
example,  suppose the  language reference  manual  specifies  t h at  *  is  commutative; 
t h at  is,  x*y  =  y*x.  Before  we  create  a  new  node  labeled  *  with  left  child  M  and 
right  child  N,  we  always  check  whether  such  a  node  already  exists.  However, 
because  *  is  commutative,  we  should  then  check  for  a  node  having  operator  *, 
left  child  N,  and  right  child  M. 

The  relational  operators  such  as  <  and  —  sometimes  generate  unexpected 
common  subexpressions.  For  example,  the  condition  x  >  y  can  also  be  tested 
by  subtracting  the  arguments  and  performing  a  test  on  the  condition  code  set 
by  the  subtraction.3  Thus,  only  one  node  of the  DAG  may  need  to  be  generated 
for  x  —  y  and  x  >  y. 

Associative  laws  might  also  be  applicable  to  expose  common  subexpressions. 

For  example,  if  t he  source  code  has  t he  assignments 

a  =  b  +  c; 

e  =  c  +  d  +  b; 

the  following  intermediate  code  might  be  generated: 

2  Arithmetic  expressions  should  be  evaluated  the  same  way  at  compile  time  as  they  are  at 
run  time.  K.  Thompson  has  suggested  an  elegant  solution  to  constant  folding:  compile  the 
constant  expression,  execute  the  target  code  on  the  spot,  and  replace  the  expression  with  the 
result.  Thus,  the  compiler  does  not  need  to  contain  an  interpreter. 

3T he  subtraction  can,  however,  introduce  overflows  and  underflows  while  a  compare  in 

struction  would  not. 

8.5. 

OPTIMIZATION  OF  BASIC  BLOCKS 

537 

a  =  b  +  c 
t  =  c  +  d 
e  =  t  +  b 

If  t  is  not  needed  outside  this  block,  we  can  change  this  sequence  to 

a  =  b  +  c 
e  =  a  +  d 

using  b o th  the  associativity  and  commutativity  of  +. 

T he  compiler  writer  should  examine  the  language  reference  manual  care 
fully  to  determine  what  rearrangements  of  computations  are  permitted,  since 
(because  of  possible  overflows  or  underflows)  computer  arithmetic  does  not  al 
ways  obey  the  algebraic  identities  of  mathematics.  For  example,  the  Fortran 
s t a n d a rd  states  t h at  a  compiler  may  evaluate  any  mathematically  equivalent 
expression,  provided  t h at  the  integrity  of  parentheses  is  not  violated.  Thus, 
a  compiler  may  evaluate  x  *  y  —  x  *  z  a,s  x  *  (y  -  z),  but  it  may  not  evaluate 
a + (6 — c)  as  (a + b)  — c.  A  Fortran  compiler  must  therefore  keep  track  of where 
parentheses  were  present  in  the  source  language  expressions  if  it  is  to  optimize 
programs  in  accordance  with  the  language  definition. 

8.5.5  Representation  of  Array  References 

At  first  glance,  it  might  appear  t h at  the  array-indexing  instructions  can  be 
treated  like  any  other  operator.  Consider  for  instance  the  sequence  of  three-
address  statements: 

x  =  a[ i] 
a [ j]  =  y 
z  =  a[ i] 

If  we  think  of  a[ i]  as  an  operation  involving  a  and  i,  similar  to  a  +  i,  then 
it  might  appear  as  if  the  two  uses  of  a[ i]  were  a  common  subexpression.  In 
t h at  case,  we  might  be  tempted  to  "optimize"  by  replacing  t he  third  instruction 
z  =  a[ i]  by  the  simpler  z  =  x.  However,  since  j  could  equal  i,  the  middle 
statement  may  in  fact  change  the  value  of  a [ i ];  thus,  it  is  not  legal  to  make 
this  change. 

T he  proper  way  to  represent  array  accesses  in  a  DAG  is  as  follows. 

1.  An  assignment  from  an  array,  like  x  =  a[ i ],  is  represented  by  creating  a 
node  with  operator  = []  and  two  children  representing  t he  initial  value  of 
the  array,  a0  in  this  case,  and  the  index  i.  Variable  x  becomes  a  label  of 
this  new  node. 

2.  An  assignment  to  an  array,  like  a [ j]  =  y,  is  represented  by  a  new  node 
with  operator  []=  and  three  children  representing  a0,  j  and  y.  There  is 
no  variable  labeling  this  node.  W h at  is  different  is  t h at  the  creation  of 

538 

CHAPTER  8. 

CODE  GENERATION 

this  node  kills  all  currently  constructed  nodes  whose  value  depends  on  a0. 
A  node  t h at  has  been  killed  cannot  receive  any  more  labels;  t h at  is,  it 
cannot  become  a  common  subexpression. 

E x a m p le  8 . 1 3:  T he  DAG  for  the  basic  block 

x  =  a [ i] 
a [ j]  =  y 
z  =  a [ i] 

is  shown  in  Fig-  8.14.  T he  node  N  for  x  is  created  first,  but  when  t he  node 
labeled  [ ]=  is  created,  N  is  killed.  Thus,  when  the  node  for  z  is  created,  it 
cannot  be  identified  with  N,  and  a  new  node  with  t he  same  operands  a0  and 
i0  must  be  created  instead. 

• 

ao 

io 

j0 

Yo 

Figure  8.14:  T he  DAG  for  a  sequence  of  array  assignments 

E x a m p le  8 . 1 4:  Sometimes,  a  node  must  be  killed  even  though  none  of  its 
children  have  an  array  like  a0  in  Example  8.13  as  attached  variable.  Likewise, 
a  node  can  kill  if  it  has  a  descendant  t h at  is  an  array,  even  though  none  of  its 
children  are  array  nodes.  For  instance,  consider  t he  three-address  code 

b  =  12  +  a 
x  =  b [ i] 
b [ j]  =  y 

W h at  is  happening  here  is  t h a t,  for  efficiency  reasons,  b  has  been  defined  to 
be  a position  in  an  array  a.  For  example,  if the  elements  of a  are  four  bytes  long, 
then  b  represents  the  fourth  element  of  a.  If  j  and  i  represent  the  same  value, 
then  b [ i]  and  b [ j]  represent  t he  same  location.  Therefore  it  is  important 
to  have  the  third  instruction,  b [ j]  =  y,  kill  the  node  with  x  as  its  attached 
variable.  However,  as  we  see  in  Fig.  8.15,  b o th  t he  killed  node  and  t he  node 
t h at  does  the  killing  have  cio  as  a  grandchild,  not  as  a  child. 

• 

8.5. 

OPTIMIZATION  OF  BASIC  BLOCKS 

539 

Figure  8.15:  A  node  t h at  kills  a  use  of  an  array  need  not  have  t h at  array  as  a 
child 

8.5.6  Pointer  Assignments  and  Procedure  Calls 

When  we  assign  indirectly  through  a  pointer,  as  in  the  assignments 

x  =  *p 

*q  =  y 

we  do  not  know  what  p  or  q  point  to. 
In  effect,  x  =  *p  is  a  use  of  every 
variable  whatsoever,  and  *q  =  y  is  a  possible  assignment  to  every  variable.  As 
a  consequence,  the  operator  =*  must  take  all  nodes  t h at  are  currently  associated 
with  identifiers  as  arguments,  which  is  relevant  for  dead-code  elimination.  More 
importantly,  the  *=  operator  kills  all  other  nodes  so  far  constructed  in  the  DAG. 
There  are  global  pointer  analyses  one  could  perform  t h at  might  limit  t he  set 
of  variables  a  pointer  could  reference  at  a  given  place  in  the  code.  Even  local 
analysis  could  restrict  the  scope  of  a  pointer.  For  instance,  in  the  sequence 

p  =  &x 
*p  =  y 

we  know  t h at  x,  and  no  other  variable,  is  given  the  value  of y,  so  we  don't  need 
to  kill  any  node  but  the  node  to  which  x  was  attached. 

Procedure  calls  behave  much  like  assignments  through  pointers. 

In  the 
absence  of  global  data-flow  information,  we  must  assume  t h at  a  procedure  uses 
and  changes  any  d a ta  to  which  it  has  access.  Thus,  if  variable  x  is  in  the  scope 
of  a  procedure  P,  a  call  to  P  both  uses  the  node  with  attached  variable  x  and 
kills  t h at  node. 

8.5.7  Reassembling  Basic  Blocks  From  DAG's 

After  we  perform  whatever  optimizations  are  possible  while  constructing  t he 
DAG  or  by  manipulating  the  DAG  once  constructed,  we  may  reconstitute  the 
three-address  code  for  the  basic  block  from  which  we  built  t he  DAG.  For  each 

540 

CHAPTER  8. 

CODE  GENERATION 

node  t h at  has  one  or  more  attached  variables,  we  construct  a  three-address 
statement  t h at  computes  the  value  of  one  of  those  variables.  We  prefer  to 
compute  the  result  into  a  variable  t h at  is  live  on  exit  from  the  block.  However,  if 
we  do  not  have  global  live-variable  information  to  work  from,  we  need  to  assume 
t h at  every  variable  of  the  program  (but  not  temporaries  t h at  are  generated  by 
the  compiler  to  process  expressions)  is  live  on  exit  from  the  block. 

If  the  node  has  more  t h an  one  live  variable  attached,  then  we  have  to  in 

troduce  copy  statements  to  give  the  correct  value  to  each  of  those  variables. 
Sometimes,  global  optimization  can  eliminate  those  copies,  if  we  can  arrange  to 
use  one  of  two  variables  in  place  of  the  other. 

E x a m p le  8 . 1 5:  Recall  the  DAG  of  Fig.  8.12. 
In  the  discussion  following 
Example  8.10,  we  decided  t h at  if  b  is  not  live  on  exit  from  the  block,  then  t he 
three  statements 

a  =  b  +  c 
d  =  a  -  d 
c  =  d  +  c 

suffice  to  reconstruct  the  basic  block.  T he  third  instruction,  c  =  d +  c,  must  use 
d  as  an  operand  rather  t h an  b,  because  the  optimized  block  never  computes  b. 
If  both  b  and  d  are  live  on  exit,  or  if  we  are  not  sure  whether  or  not  they 
are  live  on  exit,  then  we  need  to  compute  b  as  well  as  d.  We  can  do  so  with  the 
sequence 

a  =  b  +  c 
d  =  a  -  d 
b  =  d 
c  =  d  +  c 

This  basic  block  is  still  more  efficient  t h an  the  original.  Although  the  number 
of  instructions  is  t he  same,  we  have  replaced  a  subtraction  by  a  copy,  which 
tends  to  be  less  expensive  on  most  machines.  Further,  it  may  be  t h at  by  doing 
a  global  analysis,  we  can  eliminate  t he  use  of  this  computation  of  b  outside 
the  block  by  replacing  it  by  uses  of  d.  In  t h at  case,  we  can  come  back  to  this 
basic  block  and  eliminate  b  =  d  later.  Intuitively,  we  can  eliminate  this  copy  if 
wherever  this  value  of b  is  used,  d  is  still  holding  the  same  value.  T h at  situation 
may  or  may  not  be  true,  depending  on  how  t he  program  recomputes  d. 

• 

W h en  reconstructing  the  basic  block  from  a  DAG,  we  not  only  need  to  worry 
about  what  variables  are  used  to  hold  the  values  of  t he  DAG's  nodes,  but  we 
also  need  to  worry  about  the  order  in  which  we  list  t he  instructions  computing 
the  values  of  the  various  nodes.  The  rules  to  remember  are 

1.  The  order  of  instructions  must  respect  the  order  of  nodes  in  t he  DAG. 
T h at  is,  we  cannot  compute  a  node's  value  until  we  have  computed  a 
value  for  each  of its  children. 

8.5. 

OPTIMIZATION  OF  BASIC  BLOCKS 

541 

2.  Assignments  to  an  array  must  follow  all  previous  assignments  to,  or  eval 
uations  from,  t he  same  array,  according  to  t he  order  of  these  instructions 
in  t he  original  basic  block. 

3.  Evaluations  of  array  elements  must  follow  any  previous  (according  to  t he 
original  block)  assignments  to  t he  same  array.  T he  only  permutation 
allowed  is  t h at  two  evaluations  from  the  same  array  may  be  done  in  either 
order,  as  long  as  neither  crosses  over  an  assignment  to  t h at  array. 

4.  Any  use  of  a  variable  must  follow  all  previous  (according  to  the  original 

block)  procedure  calls  or  indirect  assignments  through  a  pointer. 

5.  Any  procedure  call  or  indirect  assignment  through  a  pointer  must  follow 
all  previous  (according  to  the  original  block)  evaluations  of  any  variable. 

T h at  is,  when  reordering  code,  no  statement  may  cross  a  procedure  call  or 
assignment  through  a  pointer,  and  uses  of the  same  array  may  cross  each  other 
only  if  b o th  are  array  accesses,  but  not  assignments  to  elements  of  the  array. 

8.5.8  Exercises  for  Section  8.5 

E x e r c i se  8 . 5 . 1:  Construct  the  DAG  for  the  basic  block 

d  =  b  *  c 
e  =  a  +  b 
b  =  b  *  c 
a  =  e  -  d 

E x e r c i se  8 . 5 . 2:  Simplify  the  three-address  code  of  Exercise  8.5.1,  assuming 

a)  Only  a  is  live  on  exit  from  t he  block. 

b)  a,  b,  and  c  are  live  on  exit  from  the  block. 

E x e r c i se  8 . 5 . 3:  Construct  the  basic  block  for  the  code  in  block  B6  of Fig.  8.9. 
Do  not  forget  to  include  the  comparison  i  <  10. 

E x e r c i se  8 . 5 . 4:  Construct  t he  basic  block  for  t he  code  in  block  B3  of  Fig.  8.9. 

E x e r c i se  8 . 5 . 5:  Extend  Algorithm  8.7  to  process  three-statements  of t he  form 

a)  a [ i]  =  b 

b)  a  =  b [ i] 

c)  a  =  *b 

c)  *a  =  b 

E x e r c i se  8 . 5 . 6:  Construct  the  DAG  for  the  basic  block 

542 

CHAPTER  8. 

CODE  GENERATION 

a [ i]  =  b 
*p  =  c 
d  =  a [ j] 
e  =  *p 
*p  =  a [ i] 

on  the  assumption  t h at 

a)  p  can  point  anywhere. 

b)  p  can  point  only  to  b  or  d. 

E x e r c i se  8 . 5 . 7:  If a  pointer  or  array expression,  such  as  a [ i]  or  *p  is  assigned 
and  then  used,  without  the  possibility  of  being  changed  in  t he  interim,  we  can 
take  advantage  of  the  situation  to  simplify  t he  DAG.  For  example,  in  t he 
code  of  Exercise  8.5.6,  since  p  is  not  assigned  between  the  second  and  fourth 
statements,  the  statement  e  =  *p  can  be  replaced  by  e  =  c,  regardless  of what 
p  points  to.  Revise  the  DAG-construction  algorithm  to  take  advantage  of  such 
situations,  and  apply  your  algorithm  to  the  code  of  Example  8.5.6. 

E x e r c i se  8 . 5 . 8:  Suppose  a  basic  block  is  formed  from  t he  C  assignment  state 
ments 

x  =  a  +  b  +  c  +  d  +  e  +  f; 
y  =  a  +  c  +  e; 

a)  Give  t he  three-address  statements  (only  one  addition  per  statement)  for 

this  block. 

b)  Use  the  associative  and  commutative  laws  to  modify  the  block  to  use  t he 
fewest  possible  number  of instructions,  assuming  both  x  and  y  are  live  on 
exit  from  the  block. 

8.6  A  Simple  Code  Generator 

In  this  section,  we  shall  consider  an  algorithm  t h at  generates  code  for  a  single 
basic  block.  It  considers  each  three-address  instruction  in  t u r n,  and  keeps  track 
of what  values  are  in  what  registers  so  it  can  avoid  generating  unnecessary  loads 
and  stores. 

One  of  t he  primary  issues  during  code  generation  is  deciding  how  to  use 

registers  to  best  advantage.  There  are  four  principal  uses  of  registers: 

•  In  most  machine  architectures,  some  or  all  of the  operands  of an  operation 

must  be  in  registers  in  order  to  perform  t he  operation. 

•  Registers  make  good  temporaries  —  places  to  hold  t he  result  of  a  subex 
pression  while  a  larger  expression  is  being  evaluated,  or  more  generally,  a 
place  to  hold  a  variable  t h at  is  used  only  within  a  single  basic  block. 

8.6. 

A  SIMPLE  CODE  GENERATOR 

543 

•  Registers  are  used  to  hold  (global)  values  t h at  are  computed  in  one  basic 
block  and  used  in  other  blocks,  for  example,  a  loop  index  t h at  is  incre 
mented  going  around  the  loop  and  is  used  several  times  within  the  loop. 

•  Registers  are  often  used  to  help  with  run-time  storage  management,  for 
example,  to  manage  t he  run-time  stack,  including  the  maintenance  of 
stack  pointers  and  possibly  the  top  elements  of  the  stack  itself. 

These  are  competing  needs,  since  the  number  of  registers  available  is  limited. 

T he  algorithm  in  this  section  assumes  t h at  some  set  of  registers  is  available 
to  hold  the  values  t h at  are  used  within  the  block.  Typically,  this  set  of  regis 
ters  does  not  include  all  t he  registers  of  t he  machine,  since  some  registers  are 
reserved  for  global  variables  and  managing  the  stack.  We  assume  t h at  the  basic 
block  has  already  been  transformed  into  a  preferred  sequence  of  three-address 
instructions,  by  transformations  such  as  combining  common  subexpressions. 
We  further  assume  t h at  for  each  operator,  there  is  exactly  one  machine  instruc 
tion  t h at  takes  the  necessary  operands  in  registers  and  performs  t h at  operation, 
leaving  the  result  in  a  register.  The  machine  instructions  are  of  the  form 

•  LD  reg,  mem 

•  ST  mem,  reg 

•  OP reg,  reg,  reg 

8.6.1  Register  and  Address  Descriptors 

Qur  code-generation  algorithm  considers  each  three-address  instruction  in  t u rn 
and  decides  what  loads  are  necessary  to  get  the  needed  operands  into  registers. 
After  generating  the  loads,  it  generates  the  operation  itself.  Then,  if  there  is  a 
need  to  store  the  result  into  a  memory  location,  it  also  generates  t h at  store. 

In  order  to  make  the  needed  decisions,  we  require  a  d a ta  structure  t h at  tells 
us  what  program  variables  currently  have  their  value  in  a  register,  and  which 
register  or  registers,  if  so.  We  also  need  to  know  whether  the  memory  location 
for  a  given  variable  currently  has  the  proper  value  for  t h at  variable,  since  a  new 
value  for  the  variable  may  have  been  computed  in  a  register  and  not  yet  stored. 
T he  desired  d a ta  structure  has  the  following  descriptors: 

1.  For  each  available  register,  a  register  descriptor  keeps  track  of  t he  variable 
names  whose  current  value  is  in  t h at  register.  Since  we  shall  use  only  those 
registers  t h at  are  available  for  local  use  within  a  basic  block,  we  assume 
t h at  initially,  all  register  descriptors  are  empty.  As  the  code  generation 
progresses,  each  register  will  hold  the  value  of  zero  or  more  names. 

2.  For  each  program  variable,  an  address  descriptor  keeps  track  of  the  loca 
tion  or  locations  where  the  current  value  of  t h at  variable  can  be  found. 
T he  location  might  be  a  register,  a  memory  address,  a  stack  location,  or 
some  set  of more  t h an  one  of these.  T he  information  can  be  stored  in  the 
symbol-table  entry  for  t h at  variable  name. 

544 

CHAPTER  8. 

CODE  GENERATION 

8.6.2  The  Code-Generation  Algorithm 

An  essential  part  of  the  algorithm  is  a  function  getReg(I),  which  selects  regis 
ters  for  each  memory  location  associated  with  the  three-address  instruction  I. 
Function  getReg  has  access  to  the  register  and  address  descriptors  for  all  t he 
variables  of t he  basic  block,  and  may  also  have  access  to  certain  useful  data-flow 
information  such  as  the  variables  t h at  are  live  on  exit  from  the  block.  We  shall 
discuss  getReg  after  presenting  the  basic  algorithm.  While  we  do  not  know  the 
total  number  of  registers  available  for  local  d a ta  belonging  to  a  basic  block,  we 
assume  t h at  there  are  enough  registers  so  t h a t,  after  freeing  all  available  regis 
ters  by  storing  their  values  in  memory^  there  are  enough  registers  to  accomplish 
any  three-address  operation. 

In  a  three-address  instruction  such  as  x = y + z,  we  shall  treat  +  as  a  generic 
operator  and ADD  as  the  equivalent  machine  instruction.  We  do  not,  therefore, 
take  advantage  of commutativity  of +.  Thus,  when  we  implement  the  operation, 
the  value  of  y  must  be  in  the  second  register  mentioned  in  t he ADD  instruction, 
never  the  third.  A  possible  improvement  to  the  algorithm  is  to  generate  code 
for  both  x = y + z  and  x = z + y  whenever  +  is  a  commutative  operator,  and  pick 
the  better  code  sequence. 

M a c h i ne  I n s t r u c t i o ns  for  O p e r a t i o ns 

For  a  three-address  instruction  such  as  x  =  y  +  z,  do  the  following: 

1.  Use  getReg(x  =  y  +  z)  to  select  registers  for  x,  y,  and  z.  Call  these  Rx, 

Ry, 

and  Rz. 

2.  If  y  is  not  in  Ry  (according  to  the  register  descriptor  for  Ry),  then  issue 
an  instruction LD  Ry,y',  where  y'  is  one  of  t he  memory  locations  for  y 
(according  to  the  address  descriptor  for  y). 

3.  Similarly,  if  z  is  not  in  Rz,  issue  and  instruction LD  Rz,z',  where  z'  is  a 

location  for  z. 

4.  Issue 

the 

instruction  ADD  Rx,Ry,Rz. 

M a c h i ne  I n s t r u c t i o ns  for  C o py  S t a t e m e n ts 

There  is  an  important  special  case:  a  three-address  copy  statement  of the  form 
x  =  y.  We  assume  t h at  getReg  will  always  choose  the  same  register  for  b o th 
x  and  y. 
If  y  is  not  already  in  t h at  register  Ry,  then  generate  the  machine 
instruction LD  Ry,  y.  If  y  was  already  in  Ry,  we  do  nothing.  It  is  only  necessary 
t h at  we  adjust  the  register  description  for  Ry  so  t h at  it  includes  x  as  one  of t he 
values  found  there. 

8.6. 

A  SIMPLE  CODE  GENERATOR 

545 

E n d i ng  t he  B a s ic  B l o ck 

As  we  have  described  t he  algorithm,  variables  used  by  the  block  may  wind  up 
with  their  only  location  being  a  register. 
If  the  variable  is  a  temporary  used 
only  within  t he  block,  t h at  is  fine;  when  t he  block  ends,  we  can  forget  about 
t he  value  of  t he  temporary  and  assume  its  register  is  empty.  However,  if  t he 
variable  is  live  on  exit  from  the  block,  or  if  we  don't  know  which  variables  are 
live  on  exit,  then  we  need  to  assume  t h at  t he  value  of  t he  variable  is  needed 
later.  In  t h at  case,  for  each  variable  x  whose  location  descriptor  does  not  say 
t h at  its  value  is  located  in  the  memory  location  for  x,  we  must  generate  the 
instruction ST  x, R,  where  R  is  a  register  in  which  #'s  value  exists  at  t he  end  of 
t he  block. 

M a n a g i ng  R e g i s t er  a nd  A d d r e ss  D e s c r i p t o rs 

As  t he  code-generation  algorithm  issues  load,  store,  and  other  machine  instruc 
tions,  it  needs  to  u p d a te  the  register  and  address  descriptors.  The  rules  are  as 
follows: 

1.  For  the  instruction LD  R:x 

(a)  Change  the  register  descriptor  for  register  R  so  it  holds  only  x. 

(b)  Change  the  address  descriptor  for  x  by  adding  register  R  as  an  ad 

ditional  location. 

2.  For  the  instruction ST  x,  R,  change  the  address  descriptor  for  x  to  include 

its  own  memory  location. 

3.  For  an  operation  such  as  ADD  Rx,Ry,Rz 

implementing  a  three-address 

instruction  x  —  y  +  z 

(a)  Change  the  register  descriptor  for  Rx  so  t h at  it  holds  only  x. 

(b)  Change  the  address  descriptor  for  x  so  t h at  its  only  location  is  Rx. 
Note  t h at  the  memory  location  for  x  is  not  now  in  the  address  de 
scriptor  for  x. 

(c)  Remove  Rx  from  the  address  descriptor  of  any  variable  other  t h an 

x. 

4.  When  we  process  a  copy  statement  x  =  y,  after  generating  t he  load  for  y 
into  register  Ry,  if  needed,  and  after  managing  descriptors  as  for  all  load 
statements  (per  rule  1): 

(a)  Add  x  to  t he  register  descriptor  for  Ry. 

(b)  Change  t he  address  descriptor  for  x  so  t h at  its  only  location  is  Ry. 

E x a m p le  8.16  :  Let  us  translate  the  basic  block  consisting  of the  three-address 
statements 

546 

CHAPTER  8. 

CODE  GENERATION 

t  =  a  -  b 
u  = a  -  c 
v =  t  +  u 
a =  d 
d  =  v  +  u 

Here we  assume t h at t, u,  and v  are temporaries,  local to the  block,  while a, b, 
c,  and  d  are  variables  t h at  are  live  on  exit  from  the  block.  Since  we  have  not 
yet  discussed  how  the  function  getReg  might  work,  we  shall  simply  assume  t h at 
there  are  as  many  registers  as  we  need,  but  t h at  when  a  register's  value  is  no 
longer  needed  (for  example,  it  holds  only  a  temporary,  all  of  whose  uses  have 
been  passed),  then  we  reuse  its  register. 

A  summary  of  all  the  machine-code  instructions  generated  is  in  Fig.  8.16. 
T he  figure  also  shows  the  register  and  address  descriptors  before  and  after  the 
translation  of  each  three-address  instruction. 

Rl 

R2 

R3 

a 

b 

c 

d 

t 

u 

v 

t  =  a  -  b 

LD Rl,  a 

LD R 2,  b 

SUB R 2,  Rl,  R2 

u  =  a  -  c 

LD R3,  c 
SUB  R l,  R l,  R3 

v  =  t  +  u 

ADD R3,  R 2,  Rl 

a  =  d 

LD R 2,  d 

d  =  v  +  u 

ADD  R l,  R3,  Rl 

exit 

ST  a,  R2 

St  d,  Rl 

a 

t 

a,Rl  b 

c 

d 

R2 

u 

t 

c 

a 

b 

c,R3  d 

R2 

Rl 

U 

t 

V 

a 

b 

c 

d 

R2 

Rl 

R3 

u 

a, d  v 

R2 

b 

c  d,R2 

Rl 

R3 

d 

a 

v 

R2 

b 

c 

Rl 

R3 

d 

a 

v 

|a,R2|  b 

c  |d,Rl 

R3 

Figure  8.16:  Instructions  generated  and  t he  changes  in  t he  register  and  address 
descriptors 

For  the  first  three-address  instruction, t = a -b  we  need  to  issue  three  in 
structions,  since  nothing  is  in  a  register  initially.  Thus,  we  see a  and b  loaded 

8.6. 

A  SIMPLE  CODE  GENERATOR 

547 

into  registers Rl  and R2,  and  the  value t  produced  in  register R2.  Notice  t h at 
we  can  use R2  for t  because  the  value  b  previously  in R2  is  not  needed  within 
t he  block.  Since  b  is  presumably  live  on  exit  from  t he  block,  had  it  not  been 
in  its  own  memory  location  (as  indicated  by  its  address  descriptor),  we  would 
have  had  to  store R2  into  b  first.  The  decision  to  do  so,  had  we  needed R2, 
would  be  taken  by  getReg. 

T he  second  instruction,  u = a- c,  does  not  require  a  load  of a,  since  it  is 
already  in  register Rl.  Further,  we  can  reuse Rl  for  the  result,  u,  since  the  value 
of a,  previously  in  t h at  register,  is  no  longer  needed  within  the  block,  and  its 
value  is  in  its  own  memory  location  if a  is  needed  outside  the  block.  Note  t h at 
we  change  t he  address  descriptor  for a  to  indicate  t h at  it  is  no  longer  in Rl,  but 
is  in  the  memory  location  called a. 

T he  third  instruction,  v  = t + u,  requires  only  the  addition.  Further,  we  can 
use R3  for  the  result,  v,  since  the  value  of  c  in  t h at  register  is  no  longer  needed 
within  t he  block,  and  c  has  its  value  in  its  own  memory  location. 

T he  copy  instruction, a =  d,  requires  a  load  of  d,  since  it  is  not  in  memory. 
We  show  register R2's  descriptor  holding  both a  and  d.  The  addition  of a  to 
the  register  descriptor  is  the  result  of  our  processing  the  copy  statement,  and 
is  not  t he  result  of  any  machine  instruction. 

T he  fifth  instruction,  d  =  v + u,  uses  two  values  t h at  are  in  registers.  Since 
u  is  a  temporary  whose  value  is  no  longer  needed,  we  have  chosen  to  reuse  its 
register Rl  for  the  new  value  of  d.  Notice  t h at  d  is  now  in  only Rl,  and  is  not 
in  its  own  memory  location.  The  same  holds  for a,  which  is  in R2  and  not  in 
t he  memory  location  called a.  As  a  result,  we  need  a  "coda"  to  the  machine 
code  for  the  basic  block  t h at  stores  t he  live-on-exit  variables a  and  d  into  their 
memory  locations.  We  show  these  as  the  last  two  instructions. 

• 

8.6.3  Design  of the  Function  getReg 

let  us  consider  how  to  implement  getReg(I),  for  a  three-address  in 
Lastly, 
struction  /.  There  are  many  options,  although  there  are  also  some  absolute 
prohibitions  against  choices  t h at  lead  to  incorrect  code  due  to  the  loss  of  the 
value  of one  or  more  live  variables.  We  begin  our  examination  with  the  case  of 
an  operation  step,  for  which  we  again  use  x  =  y  +  z  as  the  generic  example. 
First,  we  must  pick  a  register  for  y  and  a  register  for  z.  The  issues  are  the  same, 
so  we  shall  concentrate  on  picking  register  Ry  for  y.  The  rules  are  as  follows: 

1.  If  2/  is  currently  in  a  register,  pick  a  register  already  containing  y  as  Ry. 
Do  not  issue  a  machine  instruction  to  load  this  register,  as  none  is  needed. 

2.  If  y  is  not  in  a  register,  but  there  is  a  register  t h at  is  currently  empty, 

pick  one  such  register  as  Ry. 

3.  T he  difficult  case  occurs  when  y  is  not  in  a register,  and  there  is  no  register 
t h at  is  currently  empty.  We  need  to  pick  one  of  the  allowable  registers 
anyway,  and  we  need  to  make  it  safe  to  reuse.  Let  R  be  a  candidate 

548 

CHAPTER  8. 

CODE  GENERATION 

register,  and  suppose  v  is  one  of  the  variables  t h at  the  register  descriptor 
for  R  says  is  in  R.  We  need  to  make  sure  t h at  u's  value  either  is  not  really 
needed,  or  t h at  there  is  somewhere  else  we  can  go  to  get  the  value  of  R. 
T he  possibilities  are: 

(a)  If  the  address  descriptor  for  v  says  t h at  v  is  somewhere  besides  R, 

then  we  are  OK. 

(b)  If  v  is  x,  the  value  being  computed  by  instruction  /,  and  x  is  not 
also  one  of  the  other  operands  of  instruction 7  (z  in  this  example), 
then  we  are  OK.  The  reason  is  t h at  in  this  case,  we  know  this  value 
of  x  is  never  again  going  to  be  used,  so  we  are  free  to  ignore  it. 

(c)  Otherwise,  if v  is  not  used  later  (that  is,  after  the  instruction  /,  there 
are  no  further  uses  of  v,  and  if  v  is  live  on  exit  from  t he  block,  then 
v  is  recomputed  within  the  block),  then  we  are  OK. 

(d)  If  we  are  not  OK  by  one  of  the  first  two  cases,  then  we  need  to 
generate  t he  store  instruction  ST  v,  R  to  place  a  copy  of  v  in  its  own 
memory  location.  This  operation  is  called  a  spill. 

Since  R  may  hold  several  variables  at  t he  moment,  we  repeat  the  above 
steps  for  each  such  variable  v.  At  the  end,  R's  "score"  is  t he  number  of 
store  instructions  we  needed  to  generate.  Pick  one  of  the  registers  with 
the  lowest  score. 

Now,  consider  the  selection  of  t he  register  Rx.  The  issues  and  options  are 

almost  as  for  y,  so  we  shall  only  mention  t he  differences. 

1.  Since  a  new  value  of  x  is  being  computed,  a  register  t h at  holds  only  x  is 
always  an  acceptable  choice  for  Rx.  This  statement  holds  even  if  x  is  one 
of  y  and  z,  since  our  machine  instructions  allows  two  registers  to  be  the 
same  in  one  instruction. 

2.  If y  is  not  used  after  instruction  I,  in  the  sense  described  for  variable  v  in 
item  (3c),  and  Ry  holds  only  y  after  being  loaded,  if  necessary,  then  Ry 
can  also  be  used  as  Rx.  A  similar  option  holds  regarding  z  and  Rz. 

T he  last  m a t t er  to  consider  specially  is  t he  case  when  I  is  a  copy  instruction 

x  —  y.  We  pick  the  register  Ry  as  above.  Then,  we  always  choose  Rx  =  Ry. 

8.6.4  Exercises  for  Section  8.6 

E x e r c i se  8 . 6 . 1:  For  each  of t he  following  C  assignment  statements 

a)  x  =  a +  b*c; 

b)  x  =  a/(b+c)  -  d * ( e + f ); 

c)  x  =  a[i]  +  1; 

8.7. 

PEEPHOLE  OPTIMIZATION 

549 

d)  a[ i]  =  b[ c[ i ] ]; 

e)  a [ i ] [ j]  =  b [ i ] [ k]  +  c[ k] [ j ]; 

f)  *p++  =  *q++; 

generate  three-address  code,  assuming  t h at  all  array  elements  are  integers  tak 
ing  four  bytes  each.  In  p a r ts  (d)  and  (e),  assume  t h at  a,  b,  and c  are  constants 
giving  t he  location  of  t he  first  (Oth)  elements  of  t he  arrays  with  those  names, 
as  in  all  previous  examples  of  array  accesses  in  this  chapter. 

! Exercise 8.6.2:  Repeat  Exercise  8.6.1  p a r ts  (d)  and  (e),  assuming  t h at  the 
arrays  a,  b,  and c  are  located  via pointers,  pa,  pb,  and pc,  respectively,  pointing 
to  the  locations  of  their  respective  first  elements. 

Exercise 8.6.3:  Convert  your three-address  code  from  Exercise  8.6.1  into  ma 
chine  code  for  the  machine  model  of this  section.  You  may  use  as  many  registers 
as  you  need. 

Exercise 8.6.4:  Convert  your three-address code  from  Exercise 8.6.1  into  ma 
chine  code,  using  the  simple  code-generation  algorithm  of this  section,  assuming 
three  registers  are  available.  Show  the  register  and  address  descriptors  after 
each  step. 

Exercise 8.6.5:  Repeat  Exercise  8.6.4,  but  assuming  only  two  registers  are 
available. 

8.7  Peephole  Optimization 

While  most  production  compilers  produce  good  code  through  careful  instruc 
tion  selection  and  register  allocation,  a  few  use  an  alternative  strategy: 
they 
generate  naive  code  and  then  improve  the  quality  of the  target  code  by  applying 
"optimizing"  transformations  to  the  target  program.  T he  t e rm  "optimizing"  is 
somewhat  misleading  because  there  is  no  guarantee  t h at  the  resulting  code  is 
optimal  under  any  mathematical  measure.  Nevertheless,  many  simple  transfor 
mations  can  significantly  improve  the  running  time  or  space  requirement  of  the 
target  program. 

A  simple  b ut  effective  technique  for  locally  improving  the  target  code  is 
peephole  optimization,  which  is  done  by  examining  a  sliding  window  of  target 
instructions  (called  t he  peephole)  and  replacing  instruction  sequences  within 
the  peephole  by  a  shorter  or  faster  sequence,  whenever  possible.  Peephole 
optimization  can  also  be  applied  directly  after  intermediate  code  generation  to 
improve  the  intermediate  representation. 

T he  peephole  is  a  small,  sliding  window  on  a  program.  T he  code  in  t he 
peephole  need  not  be  contiguous,  although  some  implementations  do  require 
this.  It  is  characteristic  of  peephole  optimization  t h at  each  improvement  may 

550 

CHAPTER  8. 

CODE  GENERATION 

spawn  opportunities  for  additional  improvements.  In  general,  repeated  passes 
over  the  target  code  are  necessary  to  get  the  maximum  benefit. 
In  this  sec 
tion,  we  shall  give  the  following  examples  of  program  transformations  t h at  are 
characteristic  of  peephole  optimizations: 

•  Redundant-instruction  elimination 

•  Flow-of-control  optimizations 

•  Algebraic  simplifications 

•  Use  of  machine  idioms 

8.7.1  Eliminating  Redundant  Loads  and  Stores 

If  we  see  the  instruction  sequence 

LD a,  RO 
ST  RO,  a 

in  a  target  program,  we  can  delete  t he  store  instruction  because  whenever  it  is 
executed,  the  first  instruction  will  ensure  t h at  the  value  of a  has  already  been 
loaded  into  register  RO.  Note  t h at  if  the  store  instruction  had  a  label,  we  could 
not  be  sure  t h at  the  first  instruction  is  always  executed  before  t he  second,  so  we 
could  not  remove  t he  store  instruction.  P ut  another  way,  the  two  instructions 
have  to  be  in  the  same  basic  block  for  this  transformation  to  be  safe. 

Redundant  loads  and  stores  of  this  n a t u re  would  not  be  generated  by  the 
simple  code  generation  algorithm  of the  previous  section.  However,  a naive  code 
generation  algorithm  like  the  one  in  Section  8.1.3  would  generate  redundant 
sequences  such  as  these. 

8.7.2  Eliminating  Unreachable  Code 

Another  opportunity  for  peephole  optimization  is  t he  removal  of  unreachable 
instructions.  An  unlabeled  instruction  immediately  following  an  unconditional 
j u mp  may  be  removed.  This  operation  can  be  repeated  to  eliminate  a  sequence 
of  instructions.  For  example,  for  debugging  purposes,  a  large  program  may 
have  within  it  certain  code  fragments  t h at  are  executed  only  if  a  variable  debug 
is  equal  to  1.  In  the  intermediate  representation,  this  code  may  look  like 

if  debug  ==  1  g o to  LI 
g o to  L2 

L I:  print  debugging  information 
L2: 

One  obvious  peephole  optimization  is  to  eliminate j u m ps  over j u m p s.  Thus, 
no  m a t t er  what  the  value  of  debug,  the  code  sequence  above  can  be  replaced 
by 

8.7. 

PEEPHOLE  OPTIMIZATION 

551 

if  debug  !=  1  goto  L2 
print  debugging  information 

L2: 

If debug  is  set  to  0  at  t he  beginning  of  t he  program,  constant  propagation 

would  transform  this  sequence  into 

if  0  !=  1  goto  L2 
print  debugging  information 

L2: 

Now  the  argument  of  the  first  statement  always  evaluates  to  true,  so  the 
statement  can  be  replaced  by goto  L2.  Then  all  statements  t h at  print  debug 
ging  information  are  unreachable  and  can  be  eliminated  one  at  a  time. 

8.7.3 

Flow-of-Control  Optimizations 

Simple  intermediate  code-generation  algorithms  frequently  produce  j u m ps  to 
jumps,  j u m ps  to  conditional  jumps,  or  conditional  jumps  to  jumps.  These 
unnecessary  j u m ps  can  be  eliminated  in  either  the  intermediate  code  or  t he 
target  code  by  the  following  types  of  peephole  optimizations.  We  can  replace 
t he  sequence 

goto  Li 

LI:  goto L2 

by  t he  sequence 

goto  L2 

LI:  goto L2 

If  there  are  now  no  j u m ps  to LI,  then  it  may  be  possible  to  eliminate  the 

statement LI:  goto L2  provided  it  is  preceded  by  an  unconditional j u m p. 

Similarly,  t he  sequence 

if  a  <  b  goto  LI 

LI:  goto L2 

Can  be  replaced  by  the  sequence 

if  a  <  b  goto  L2 

LI:  goto L2 

Finally,  suppose  there  is  only  one  j u mp  to LI  and LI  is  preceded  by  an 

unconditional  goto.  Then  t he  sequence 

552 

CHAPTER  8. 

CODE  GENERATION 

goto  LI 

LI:  if  a < b goto L2 
L3: 

may  be  replaced  by  the  sequence 

if  a  <  b  goto  L2 
goto  L3 

L3: 

While the  number  of instructions  in  the  two  sequences  is  the  same,  we  sometimes 
skip  the  unconditional j u mp  in  the  second  sequence,  but  never in  the  first.  Thus, 
the  second  sequence  is  superior  to  the  first  in  execution  time, 

8.7.4  Algebraic  Simplification  and  Reduction  in  Strength 

In  Section  8.5  we  discussed  algebraic  identities  t h at  could  be  used  to  simplify 
DAG's.  These  algebraic  identities  can  also  be  used  by  a  peephole  optimizer  to 
eliminate  three-address  statements  such  as 

x  =  x  +  0 

or 

x  =  x  *  1 

in  the  peephole. 

Similarly,  reduction-in-strength  transformations  can  be  applied  in  the  peep 
hole  to  replace  expensive  operations  by  equivalent  cheaper  ones  on  t he  target 
machine.  Certain  machine  instructions  are  considerably  cheaper  t h an  others 
and  can  often  be  used  as  special  cases  of  more  expensive  operators.  For  ex 
ample,  x2  is  invariably  cheaper  to  implement  as  x  *  x  t h an  as  a  call  to  an 
exponentiation  routine.  Fixed-point  multiplication  or  division  by  a  power  of 
two  is  cheaper  to  implement  as  a  shift.  Floating-point  division  by  a  constant 
can  be  approximated  as  multiplication  by  a  constant,  which  may  be  cheaper. 

8.7.5  Use  of  Machine  Idioms 

The  target  machine  may  have  hardware  instructions  to  implement  certain  spe 
cific  operations  efficiently.  Detecting  situations  t h at  permit  t he  use  of  these 
instructions  can  reduce  execution  time  significantly.  For  example,  some  ma 
chines  have  auto-increment  and  auto-decrement  addressing  modes.  These  add 
or  subtract  one  from  an  operand  before  or  after  using  its  value.  The  use  of  t he 
modes  greatly  improves  t he  quality  of  code  when  pushing  or  popping  a  stack, 
as  in  parameter  passing.  These  modes  can  also  be  used  in  code  for  statements 
like  x = x + 1. 

8.8. 

REGISTER  ALLOCATION  AND  ASSIGNMENT 

553 

8.7.6  Exercises  for  Section  8.7 

Exercise  8 . 7 . 1:  Construct  an  algorithm  t h at  will  perform  redundant-instruc 
tion  elimination  in  a  sliding  peephole  on  target  machine  code. 

Exercise  8.7.2  :  Construct  an  algorithm  t h at  will  do flow-of-control optimiza 
tions  in  a  sliding  peephole  on  target  machine  code. 

Exercise  8 . 7 . 3:  Construct  an  algorithm  t h at  will  do  simple  algebraic  simpli 
fications  and  reductions  in  strength  in  a  sliding  peephole  on  target  machine 
code. 

8.8  Register  Allocation  and  Assignment 

Instructions  involving  only  register  operands  are  faster  t h an  those  involving 
memory  operands.  On  modern  machines,  processor  speeds  are  often  an  order 
of magnitude  or  more  faster  t h an  memory  speeds.  Therefore,  efficient  utilization 
of  registers  is  vitally  important  in  generating  good  code.  This  section  presents 
various  strategies  for  deciding  at  each  point  in  a  program  what  values  should 
reside  in  registers  (register  allocation)  and  in  which  register  each  value  should 
reside  (register  assignment). 

One  approach  to  register  allocation  and  assignment  is  to  assign  specific 
values  in  t he  target  program  to  certain  registers.  For  example,  we  could  decide 
to  assign  base  addresses  to  one  group  of  registers,  arithmetic  computations  to 
another,  t he  t op  of  t he  stack  to  a  fixed  register,  and  so  on. 

This  approach  has  the  advantage  t h at  it  simplifies  the  design  of a  code  gener 
ator.  Its  disadvantage  is  t h a t,  applied  too  strictly,  it  uses  registers  inefficiently; 
certain  registers  may  go  unused  over  substantial  portions  of  code,  while  unnec 
essary  loads  and  stores  are  generated  into  the  other  registers.  Nevertheless,  it  is 
reasonable  in  most  computing  environments  to  reserve  a  few  registers  for  base 
registers,  stack  pointers,  and  t he  like,  and  to  allow  t he  remaining  registers  to 
be  used  by  the  code  generator  as  it  sees  fit. 

8.8.1  Global  Register  Allocation 

T he  code  generation  algorithm  in  Section  8.6  used  registers  to  hold  values  for 
the  duration  of  a  single  basic  block.  However,  all  live  variables  were  stored 
at  the  end  of  each  block.  To  save  some  of  these  stores  and  corresponding 
loads,  we  might  arrange  to  assign  registers  to  frequently  used  variables  and  keep 
these  registers  consistent  across  block  boundaries  (globally).  Since  programs 
spend  most  of  their  time  in  inner  loops,  a  natural  approach  to  global  register 
assignment  is  to  try  to  keep  a frequently  used  value  in  a fixed register throughout 
a  loop.  For  t he  time  being,  assume  t h at  we  know  the  loop  structure  of  a  flow 
graph,  and  t h at  we  know  what  values  computed  in  a  basic  block  are  used  outside 
t h at  block.  T he  next  chapter  covers  techniques  for  computing  this  information. 

554 

CHAPTER  8. 

CODE  GENERATION 

One  strategy  for  global  register  allocation  is  to  assign  some  fixed  number 
of  registers  to  hold  the  most  active  values  in  each  inner  loop.  T he  selected 
values  may  be  different  in  different  loops.  Registers  not  already  allocated  may 
be  used  to  hold  values  local  to  one  block  as  in  Section  8.6.  This  approach 
has  the  drawback  t h at  t he  fixed  number  of  registers  is  not  always  t he  right 
number  to  make  available  for  global  register  allocation.  Yet  the  method  is 
simple  to  implement  and  was  used  in  Fortran  H,  the  optimizing  Fortran  compiler 
developed  by  IBM  for  the  360-series  machines  in  the  late  1960s. 

W i th  early  C  compilers,  a  programmer  could  do  some  register  allocation 
explicitly  by  using  register  declarations  to  keep  certain  values  in  registers  for 
the  duration  of  a  procedure.  Judicious  use  of  register  declarations  did  speed 
up  many  programs,  but  programmers  were  encouraged  to  first  profile  their 
programs  to  determine  the  program's  hotspots  before  doing  their  own  register 
allocation. 

8.8.2  Usage  Counts 

In  this  section  we  shall  assume  t h at  the  savings  to  be  realized  by  keeping  a 
variable  x  in  a  register  for  the  duration  of  a  loop  L  is  one  unit  of  cost  for  each 
reference  to  x  if  x  is  already  in  a  register.  However,  if  we  use  the  approach  in 
Section  8.6  to  generate  code  for  a  block,  there  is  a  good  chance  t h at  after  x  has 
been  computed  in  a  block  it  will  remain  in  a  register  if  there  are  subsequent 
uses  of  x  in  t h at  block.  Thus  we  count  a  savings  of  one  for  each  use  of  x  in 
loop  L  t h at  is  not  preceded  by  an  assignment  to  x  in  the  same  block.  We  also 
save  two  units  if  we  can  avoid  a  store  of  x  at  t he  end  of  a  block.  Thus,  if  x 
is  allocated  a  register,  we  count  a  savings  of  two  for  each  block  in  loop  L  for 
which  x  is  live  on  exit  and  in  which  x  is  assigned  a  value. 

On  t he  debit  side,  if  x  is  live  on  entry  to  the  loop  header,  we  must  load  x 
into  its  register just  before  entering  loop  L.  This  load  costs  two  units.  Similarly, 
for  each  exit  block  B  of loop  L  at  which  x  is  live  on  entry  to  some  successor  of 
B  outside  of  L,  we  must  store  x  at  a  cost  of  two.  However,  on  t he  assumption 
t h at  the  loop  is  iterated  many  times,  we  may  neglect  these  debits  since  they 
occur  only  once  each  time  we  enter  the  loop.  Thus,  an  approximate  formula  for 
the  benefit  to  be  realized  from  allocating  a  register  x  within  loop  L  is 

blocks  B  in  L 

(8.1) 

where  use(x,  B)  is  t he  number  of  times  x  is  used  in  B  prior  to  any  definition  of 
x;  live(x, B)  is  1  if  x  is  live  on  exit  from  B  and  is  assigned  a  value  in  B,  and 
live(x,  B)  is  0  otherwise.  Note  t h at  (8.1)  is  approximate,  because  not  all  blocks 
in  a  loop  are  executed  with  equal  frequency  and  also  because  (8.1)  is  based 
on  t he  assumption  t h at  a  loop  is  iterated  many  times.  On  specific  machines  a 
formula  analogous  to  (8.1),  but  possibly  quite  different  from  it,  would  have  to 
be  developed. 

8.8. 

REGISTER  ALLOCATION  AND 

ASSIGNMENT 

555 

E x a m p le  8 . 1 7:  Consider  the  the  basic  blocks  in  the  inner  loop  depicted  in 
Fig. 8.17,  where  j u mp  and  conditional  j u mp  statements  have  been  omitted. 
Assume  registers RO, Rl,  and R2  are  allocated  to  hold  values  throughout  t he 
loop.  Variables  live  on  entry  into  and  on  exit  from  each  block  are  shown  in 
Fig. 8.17 for  convenience,  immediately  above  and  below  each block,  respectively. 
There  are  some  subtle  points  about  live  variables  t h at  we  address  in  t he  next 
chapter.  For  example,  notice  t h at  b o th  e  and  f  are  live  at  t he  end  of  B\,  but  of 
these,  only  e  is  live  on  entry  to  B2  and  only  f  on  entry  to  B3.  In  general,  the 
variables  live  at  t he  end  of  a  block  are  the  union  of  those  live  at  the  beginning 
of  each  of  its  successor  blocks. 

b, c, d, e, f live 

Figure 8.17:  Flow  graph  of  an  inner  loop 

To  evaluate (8.1)  for  x  = a,  we  observe  t h at a  is  live  on  exit  from  Bi  and 
is  assigned  a  value  there,  b ut  is  not  live  on  exit  from  B2,  B3,  or  B4.  T h u s, 
J2B  in  L  use(a.:B)  — 2.  Hence  t he  value  of (8.1)  for  x  — a  is 4.  T h at  is,  four 
units  of  cost  can  be  saved  by  selecting a  for  one  of  the  global  registers.  T he 
values  of (8.1)  for  b, c,  d,  e,  and  f  are 5, 3, 6, 4,  and 4,  respectively.  Thus, 
we  may  select a,  b,  and  d  for  registers RO, Rl,  and R2,  respectively.  Using RO 
for  e  or  f  instead  of a  would  be  another  choice  with  the  same  apparent  benefit. 
Figure 8.18  shows  t he  assembly  code  generated  from  Fig. 8.17,  assuming  t h at 
the  strategy  of  Section 8.6  is  used  to  generate  code  for  each  block.  We  do  not 
show  the  generated  code  for  t he  omitted  conditional  or  unconditional  j u m ps 
t h at  end  each  block  in  Fig. 8.17,  and  we  therefore  do  not  show  t he  generated 
code  as  a  single  stream  as  it  would  appear  in  practice. 

• 

556 

CHAPTER  8. 

CODE  GENERATION 

LD  Rl,  b 
LD  R 2,  d 

LD  R3,  c 
ADD  RO,  Rl,  R3 
SUB  R 2,  R2,  Rl 
LD  R3,  f 
ADD  R3,  RO,  R3 
ST  e,  R3 

Bx 

SUB R3,  RO,  R2 
ST  f,  R3 

Bo 

LD  R3,  f 
ADD Rl,  R 2,  R3 
LD  R3,  c 
SUB R3,  RO,  R3 
ST  e,  R3 

Ba 

LD  R3, 
ADD  Rl, 

c 
R 2,  R3 

ST  b,  Rl 
ST  a,  R2 

ST  b,  Rl 
ST  d,  R2 

Figure  8.18:  Code  sequence  using  global  register  assignment 

8.8.3  Register  Assignment  for  Outer  Loops 

Having  assigned  registers  and  generated  code  for  inner  loops,  we  may  apply  t he 
same  idea  to  progressively  larger  enclosing  loops.  If  an  outer  loop  L\  contains 
an  inner  loop  L2,  the  names  allocated  registers  in  L2  need  not  be  allocated 
registers  in  L\  —  L2.  Similarly,  if  we  choose  to  allocate  x  a  register  in  L2  but 
not  Li,  we  must  load  x  on  entrance  to  L2  and  store  x  on  exit  from  L2.  We  leave 
as  an  exercise  the  derivation  of  a  criterion  for  selecting  names  to  be  allocated 
registers  in  an  outer  loop  L,  given  t h at  choices  have  already  been  made  for  all 
loops  nested  within  L. 

8.8.4  Register  Allocation  by  Graph  Coloring 

When  a  register  is  needed  for  a  computation  but  all  available  registers  are  in 
use,  t he  contents  of  one  of  the  used  registers  must  be  stored  (spilled)  into  a 
memory  location  in  order  to  free  up  a  register.  G r a ph  coloring  is  a  simple, 
systematic  technique  for  allocating  registers  and  managing  register  spills. 

In  t he  method,  two  passes  are  used. 

In  the  first,  target-machine  instruc 
tions  are  selected  as  though  there  are  an  infinite  number  of  symbolic  registers; 
in  effect,  names  used  in  t he  intermediate  code  become  names  of  registers  and 

8.8. 

REGISTER  ALLOCATION  AND  ASSIGNMENT 

557 

If  ac 
the  three-address  instructions  become  machine-language  instructions. 
cess  to  variables  requires  instructions  t h at  use  stack  pointers,  display  pointers, 
base  registers,  or  other  quantities  t h at  assist  access,  then  we  assume  t h at  these 
quantities  are  held  in  registers  reserved  for  each  purpose.  Normally,  their  use  is 
directly  translatable  into  an  access  mode  for  an  address  mentioned  in  a  machine 
instruction.  If  access  is  more  complex,  the  access  must  be  broken  into  several 
machine  instructions,  and  a  temporary  symbolic  register  (or  several)  may  need 
to  be  created. 

Once  the  instructions  have  been  selected,  a  second  pass  assigns  physical 
registers  to  symbolic  ones.  The  goal  is  to  find  an  assignment  t h at  minimizes 
t he  cost  of  spills. 

In  t he  second  pass,  for  each  procedure  a  register-interference  graph  is  con 
structed  in  which  the  nodes  are  symbolic  registers  and  an  edge  connects  two 
nodes  if one  is  live  at  a point  where  t he  other  is  defined.  For  example,  a  register-
interference  graph  for  Fig.  8.17  would  have  nodes  for  names  a  and  d.  In  block 
By,  a  is  live  at  the  second  statement,  which  defines  d;  therefore,  in  the  graph 
there  would  be  an  edge  between  t he  nodes  for  a  and  d. 

An  a t t e m pt  is  made  to  color  the  register-interference  graph  using  k  colors, 
where  k  is  the  number  of  assignable  registers.  A  graph  is  said  to  be  colored  if 
each  node  has  been  assigned  a  color  in  such  a  way  t h at  no  two  adjacent  nodes 
have  the  same  color.  A  color  represents  a  register,  and  the  color  makes  sure 
t h at  no  two  symbolic  registers  t h at  can  interfere  with  each  other  are  assigned 
t he  same  physical  register. 

Although  the  problem  of  determining  whether  a  graph  is fc-colorable is  N P-
complete  in  general,  t he  following  heuristic  technique  can  usually  be  used  to  do 
the  coloring  quickly  in  practice.  Suppose  a  node  n  in  a  graph  G  has  fewer  t h an 
k  neighbors  (nodes  connected  to  n  by  an  edge).  Remove  n  and  its  edges  from 
G  to  obtain  a  graph  G'.  A  ^-coloring  of  G'  can  be  extended  to  a  fc-coloring  of 
G  by  assigning  n  a  color  not  assigned  to  any  of  its  neighbors. 

By  repeatedly  eliminating  nodes  having  fewer  t h an  k  edges  from  the  register-
interference  graph,  either  we  obtain  the  empty  graph,  in  which  case  we  can 
produce  a  ^-coloring  for  the  original  graph  by  coloring  the  nodes  in  the  reverse 
order  in  which  they  were  removed,  or  we  obtain  a  graph  in  which  each  node  has 
k  or  more  adjacent  nodes.  In  the  latter  case  a  ^-coloring  is  no  longer  possible. 
At  this  point  a  node  is  spilled  by  introducing  code  to  store  and  reload  the 
register.  Chaitin  has  devised  several  heuristics  for  choosing  the  node  to  spill. 
A  general  rule  is  to  avoid  introducing  spill  code  into  inner  loops. 

8.8.5  Exercises  for  Section  8.8 

E x e r c i se  8 . 8 . 1:  Construct  the  register-interference  graph  for  the  program  in 
Fig.  8.17. 

E x e r c i se  8 . 8 . 2:  Devise  a  register-allocation  strategy  on  the  assumption  t h at 
we  automatically  store  all  registers  on  the  stack  before  each  procedure  call  and 
restore  t h em  after  t he  return. 

558 

CHAPTER  8. 

CODE  GENERATION 

8.9 

Instruction  Selection  by  Tree  Rewriting 

Instruction  selection  can  be  a  large  combinatorial  task,  especially  on  machines 
t h at  are  rich  in  addressing  modes,  such  as  CISC  machines,  or  on  machines  with 
special-purpose  instructions,  say,  for  signal  processing.  Even  if  we  assume  t h at 
the  order  of  evaluation  is  given  and  t h at  registers  are  allocated  by  a  separate 
mechanism,  instruction  selection  —  the  problem  of  selecting  target-language 
instructions  to  implement  the  operators  in  the  intermediate  representation  — 
remains  a  large  combinatorial  task. 

In  this  section,  we  treat  instruction  selection  as  a  tree-rewriting  problem. 
Tree  representations  of  target  instructions  have  been  used  effectively  in  code-
generator  generators,  which  automatically  construct  the  instruction-selection 
phase  of  a  code  generator  from  a  high-level  specification  of  the  target  machine. 
Better  code  might  be  obtained  for  some  machines  by  using  DAG's  rather  t h an 
trees,  but  DAG  matching  is  more  complex  t h an  tree  matching. 

8.9.1  Tree-Translation  Schemes 

Throughout  this  section,  t he  input  to  the  code-generation  process  will  be  a 
sequence  of  trees  at  the  semantic  level  of  t he  target  machine.  T he  trees  are 
what  we  might  get  after  inserting  run-time  addresses  into  the  intermediate 
representation,  as  described  in  Section  8.3.  In  addition,  the  leaves  of  the  trees 
contain  information  about  the  storage  types  of  their  labels. 

E x a m p le  8 . 1 8:  Figure  8.19  contains  a  tree  for  the  assignment  statement 
a [ i]  = b + l,  where  the  array  a  is  stored  on  the  run-time  stack  and  the  vari 
able  b  is  a  global  in  memory  location 
The  run-time  addresses  of  locals  a 
and  i  are  given  as  constant  offsets  Ca  and  Ci  from  SP,  t he  register  containing 
the  pointer  to  the  beginning  of  t he  current  activation  record. 

The  assignment  to  a [ i]  is  an  indirect  assignment  in  which  the  r-value  of 
the  location  for  a [ i]  is  set  to  the  r-value  of  the  expression  b+  1.  T he  addresses 
of  array  a  and  variable  i  are  given  by  adding  t he  values  of the  constant  Ca  and 
Ci,  respectively,  to  t he  contents  of register  SP.  We  simplify  array-address  calcu 
lations  by  assuming  t h at  all  values  are  one-byte  characters.  (Some  instruction 
sets  make  special  provisions  for  multiplications  by  constants,  such  as  2,  4,  and 
8,  during  address  calculations.) 

In  the  tree,  the  i nd  operator  treats  its  argument  as  a  memory  address.  As 
the  left  child  of  an  assignment  operator,  the  i nd  node  gives  t he  location  into 
which  t he  r-value  on  the  right  side  of  t he  assignment  operator  is  to  be  stored. 
If  an  argument  of  a  +  or  i nd  operator  is  a  memory  location  or  a  register,  then 
t he  contents  of  t h at  memory  location  or  register  are  taken  as  the  value.  T he 
leaves  in  the  tree  are  labeled  with  attributes;  a  subscript  indicates  the  value  of 
t he  attribute. 

• 

The  target  code  is  generated  by  applying  a  sequence  of  tree-rewriting  rules 
to  reduce  the  input  tree  to  a  single  node.  Each  tree-rewriting  rule  has  t he  form 

8.9. 

INSTRUCTION  SELECTION  BY 

TREE  REWRITING 

559 

replacement  -f-  template  {  action  } 

where  replacement  is  a  single  node,  template  is  a  tree,  and  action  is  a  code 
fragment,  as  in  a  syntax-directed  translation  scheme. 

A  set  of  tree-rewriting  rules  is  called  a  tree-translation  scheme. 
Each  tree-rewriting  rule  represents  the  translation  of  a  portion  of  the  tree 
given  by  the  template.  The  translation  consists  of  a  possibly  empty  sequence  of 
machine  instructions  t h at  is  emitted  by  t he  action  associated  with  t he  template. 
T he  leaves  of  the  template  are  attributes  with  subscripts,  as  in  the  input  tree. 
Sometimes,  certain  restrictions  apply  to  the  values  of  the  subscripts  in  the 
templates;  these  restrictions  are  specified  as  semantic  predicates  t h at  must  be 
satisfied  before  the  template  is  said  to  match.  For  example,  a  predicate  might 
specify  t h at  the  value  of  a  constant  fall  in  a  certain  range. 

A  tree-translation  scheme  is  a  convenient  way  to  represent  the  instruction-
selection  phase  of  a  code  generator.  As  an  example  of  a  tree-rewriting  rule, 
consider  the  rule  for  the  register-to-register  add  instruction: 

Ri 

4- 

+  ^ 

{ ADD  Ri,  Ri,  Rj  } 

Ri 

Rj 

This  rule  is  used  as  follows.  If  the  input  tree  contains  a  subtree  t h at  matches 
this  tree  template,  t h at  is,  a  subtree  whose  root  is  labeled  by  the  operator  + 
and  whose  left  and  right  children  are  quantities  in  registers  i  and  j,  then  we 
can  replace  t h at  subtree  by  a  single  node  labeled  Ri  and  emit  the  instruction 
ADD  Ri,Ri,Rj  as  output.  We  call  this  replacement  a  tiling  of  the  subtree. 
More  t h an  one  template  may  match  a  subtree  at  a  given  time;  we  shall  describe 
shortly  some  mechanisms  for  deciding  which  rule  to  apply  in  cases  of  conflict. 

E x a m p le  8. 1 9:  Figure  8.20  contains  tree-rewriting  rules  for  a  few  instructions 
of our  target  machine.  These  rules  will  be  used  in  a  running  example  throughout 
this  section.  T he  first  two  rules  correspond  to  load  instructions,  the  next  two 

560 

CHAPTER  8. 

CODE  GENERATION 

to  store  instructions,  and  the  remainder  to  indexed  loads  and  additions.  Note 
t h at  rule  (8)  requires  the  value  of  the  constant  to  be  1.  This  condition  would 
be  specified  by  a  semantic  predicate. 

• 

8.9.2  Code  Generation  by  Tiling  an  Input  Tree 

A  tree-translation  scheme  works  as  follows.  Given  an  input  tree,  t he  templates 
in  the  tree-rewriting  rules  are  applied  to  tile  its  subtrees.  If a template  matches, 
the  matching  subtree  in  the  input  tree  is  replaced  with  the  replacement  node  of 
t he  rule  and  the  action  associated  with  t he  rule  is  done.  If the  action  contains  a 
sequence  of  machine  instructions,  the  instructions  are  emitted.  This  process  is 
repeated  until  t he  tree  is  reduced  to  a  single  node,  or  until  no  more  templates 
match.  The  sequence  of  machine  instructions  generated  as  the  input  tree  is 
reduced  to  a  single  node  constitutes  the  output  of  the  tree-translation  scheme 
on  t he  given  input  tree. 

T he  process  of  specifying  a  code  generator  becomes  similar  to  t h at  of  us 

ing  a  syntax-directed  translation  scheme  to  specify  a  translator.  We  write  a 
tree-translation  scheme  to  describe  the  instruction  set  of  a  target  rnachine.  In 
practice,  we  would  like  to  find  a  scheme  t h at  causes  a  minimal-cost  instruction 
sequence  to  be  generated  for  each  input  tree.  Several  tools  are  available  to  help 
build  a  code  generator  automatically  from  a  tree-translation  scheme. 

E x a m p le  8 . 2 0:  Let  us  use  t he  tree-translation  scheme  in  Fig.  8.20  to  generate 
code  for  the  input  tree  in  Fig.  8.19.  Suppose  t h at  the  first  rule  is  applied  to 
load  the  constant  Ca  into  register RO: 

1) 

R0 

^ 

Ca 

{  LD  RO,  #a  } 

The  label  of  the  leftmost  leaf  then  changes  from  Ca  to  R0  and  t he  instruction 
LD RO, #a  is  generated.  T he  seventh  rule  now  matches  the  leftmost  subtree 
with  root  labeled  +: 

7) 

R0  <- 

+ 

{  ADD RO,  RO,  SP  } 

/ 

Ro 

\ 
Tigp 

Using  this  rule,  we  rewrite  this  subtree  as  a  single  node  labeled  RQ  and  generate 
the instruction ADD RO, RO, SP.  Now t he tree looks like 

INSTRUCTION 

SELECTION 

BY 

TREE 

REWRITING 

561 

1) 

2) 

3) 

4) 

Ca 

Mx 

Ri 

•<— 

Ri 

<- 

M  «— 

/ 

Mx 

\ 
Ri 

{  LD  Ri,  #a  } 

{ LD  Ri>  x  } 

{ ST  x,  Ri  } 

M  <r-

{  ST  *Ri,  Rj  } 

/ 

. 
ind 

\ 
Rj 

Ri 

5) 

Ri  <— 

ind 

{  LD  Ri,  a(Rj)  } 

+ 

/ 
Ca 

\ 
Rj 

6) 

Ri  <r~ 

+ 

{  ADD  Ri,  Ri,  a(Rj)  } 

/ 
Ri 

\ 
ind 

+ 

7) 

8) 

\ 
Rj 

/ 

Ca 

+ 

Ri 

<- 

/ 

Ri 

Ri  <r- 

+ 

/ 

Ri 

\ 
Rj 

\ 
C\ 

{  ADD  Ri,  Ri,  Rj  } 

{  INC  Ri  } 

Figure  8.20:  Tree-rewriting  rules  for  some  target-machine  instructions 

562 

CHAPTER  8. 

CODE  GENERATION 

At  this  point,  we  could  apply  rule  (5)  to  reduce  the  subtree 

i nd 
I 

d 

R$p 

to  a  single  node  labeled,  say,  R\.  We  could  also  use  rule  (6)  to  reduce  the  larger 
subtree 

Ro 

ind 

+ 

Ci 

i?gp 

to  a  single  node  labeled  Ro  and  generate  the  instruction ADD RO, RO, i(SP). 
Assuming  t h at  it  is  more  efficient  to  use  a  single  instruction  to  compute  the 
larger  subtree  rather  t h an  the  smaller  one,  we  choose  rule  (6)  to  get 

In  the  right  subtree,  rule  (2)  applies  to  the  leaf 
to  load  b  into  register Rl,  say.  Now,  using  rule  (8)  we  can  match  t he  subtree 

It  generates  an  instruction 

+ 

\ 
Ci 

/ 

Ri 

and  generate  the  increment  instruction INC Rl.  At  this  point,  the  input  tree 
has  been  reduced  to 

incf^ 

.Ri 

-Ro 

This  remaining  tree  is  matched  by  rule  (4),  which  reduces  t he  tree  to  a  single 
node  and  generates the  instruction ST  *R0, Rl.  We  generate the  following  code 
sequence: 

LD  RO,  #a 
ADD RO,  RO,  SP 
ADD RO,  RO,  i(SP) 
LD  Rl,  b 
INC Rl 
ST 

* R 0,  Rl 

8.9. 

INSTRUCTION  SELECTION  BY 

TREE  REWRITING 

563 

in  the  process  of  reducing  the  tree  to  a  single  node. 

• 

In  order  to  implement  the  tree-reduction  process  in  Example  8.18,  we  must 

address  some  issues  related  to  tree-pattern  matching: 

•  How  is  tree-pattern  matching  to  be  done?  T he  efficiency  of  the  code-
generation  process  (at  compile  time)  depends  on  the  efficiency  of the  tree-
matching  algorithm. 

•  W h at  do  we  do  if  more  t h an  one  template  matches  at  a  given  time? 
The  efficiency  of  the  generated  code  (at  run  time)  may  depend  on  t he 
order  in  which  templates  are  matched,  since  different  match  sequences 
will  in  general  lead  to  different  target-machine  code  sequences,  some  more 
efficient  t h an  others. 

If  no  template  matches,  then  the  code-generation  process  blocks.  At  the 
other  extreme,  we  need  to  guard  against  the  possibility  of  a  single  node  being 
rewritten  indefinitely,  generating  an  infinite  sequence  of  register  move  instruc 
tions  or  an  infinite  sequence  of  loads  and  stores. 

To  prevent  blocking,  we  assume  t h at  each  operator  in  the  intermediate  code 
can  be  implemented  by  one  or  more  target-machine  instructions.  We  further 
assume  t h at  there  are  enough  registers  to  compute  each  tree  node  by  itself. 
Then,  no  m a t t er  how  the  tree  matching  proceeds,  the  remaining  tree  can  always 
be  translated  into  target-machine  instructions. 

8.9.3  Pattern  Matching  by  Parsing 

Before  considering  general  tree  matching,  we  consider  a  specialized  approach 
t h at  uses  an  LR  parser  to  do  the  p a t t e rn  matching.  The  input  tree  can  be 
treated  as  a  string  by  using  its  prefix  representation.  For  example,  the  prefix 
representation  for  the  tree  in  Fig.  8.19  is 

= 

i nd  +  +  Ca 

i ?SP 

i nd  +  d  R$P  +  Mb  d 

T he  tree-translation  scheme  can  be  converted  into  a  syntax-directed  trans 
lation  scheme  by  replacing  the  tree-rewriting  rules  with  the  productions  of  a 
context-free  grammar  in  which  the  right  sides  are  prefix  representations  of  the 
instruction  templates. 

E x a m p le  8 . 2 1:  The  syntax-directed  translation  scheme  in  Fig.  8.21  is  based 
on  the  tree-translation  scheme  in  Fig.  8.20. 

The  nonterminals  of  the  underlying  grammar  are  R  and  M.  The  terminal 
m  represents  a  specific  memory  location,  such  as  the  location  for  the  global 
variable  b  in  Example  8.18.  The  production  M 
m  in  Rule  (10)  can  be 
thought  of  as  matching  M  with  m  prior  to  using  one  of the  templates  involving 
M.  Similarly,  we  introduce  a  terminal  sp  for  register  SP  and  add  t he  production 
R 

S P.  Finally,  terminal  c  represents  constants. 

Using  these  terminals,  the  string  for  the  input  tree  in  Fig.  8.19  is 

564 

CHAPTER  8. 

CODE  GENERATION 

1)  Ri 
Ri 
2) 
3)  M 
4)  M 
5)  Ri 
Ri 
6) 
7)  Ri 
Ri 
8) 
R 
9) 
10)  M 

-t 
-> 
->  = 

jRJ  Rj 
=  ind 
ind  +  ca  Rj 
->  +  Ri  ind  +  ca 
->  +  ^  it^-
->  +  Ri  ci 
->  sp 
->  m 

{ LD  Ri,  #a  } 
{ LD  Ri,  x  } 
{ ST  a:,  Ri } 
{ ST  *Ri,  Rj } 
{ LD  Ri,  o(Rj)  } 
{ ADD Ri,  Ri,  o(Rj)  } 
{ ADD Ri,  Ri,  Rj } 
{  INC Ri } 
{  INC Ri } 

Figure  8.21:  Syntax-directed  translation  scheme  constructed  from  Fig.  8.20 

= ind +  +  ca  sp ind +  c$  sp  +  m&  ci 

• 

From  the  productions  of the  translation  scheme  we  build  an  LR  parser  using 
one  of  the  LR-parser  construction  techniques  of  Chapter  4.  The  target  code  is 
generated  by  emitting  the  machine  instruction  corresponding  to  each  reduction. 
A  code-generation  g r a m m ar  is  usually  highly  ambiguous,  and  some  care 
needs  to  be  given  to  how  the  parsing-action  conflicts  are  resolved  when  the 
parser  is  constructed.  In  the  absence  of  cost  information,  a  general  rule  is  to 
favor  larger  reductions  over  smaller  ones.  This  means  t h at  in  a  reduce-reduce 
conflict,  the  longer  reduction  is  favored; 
in  a  shift-reduce  conflict,  the  shift 
move  is  chosen.  This  "maximal  munch"  approach  causes  a  larger  number  of 
operations  to  be  performed  with  a  single  machine  instruction. 

There  are  some  benefits  to  using  LR  parsing  in  code  generation.  First, 
the  parsing  method  is  efficient  and  well  understood,  so  reliable  and  efficient 
code  generators  can  be  produced  using  t he  algorithms  described  in  Chapter  4. 
Second,  it  is  relatively  easy  to  retarget  the  resulting  code  generator;  a  code 
selector  for  a  new  machine  can  be  constructed  by  writing  a  g r a m m ar  to  describe 
the  instructions  of  the  new  machine.  Third,  the  quality  of  the  code  generated 
can  be  made  efficient  by  adding  special-case  productions  to  take  advantage  of 
machine  idioms. 

However,  there  are  some  challenges  as  well.  A  left-to-right  order  of  evalua 
tion  is  fixed  by  the  parsing method.  Also,  for  some  machines  with  large  numbers 
of addressing  modes,  the  machine-description  grammar  and  resulting  parser  can 
become  inordinately  large.  As  a  consequence,  specialized  techniques  are  neces 
sary  to  encode  and  process  the  machine-description  grammars.  We  must  also 
be  careful  t h at  t he  resulting  parser  does  not  block  (has  no  next  move)  while 
parsing  an  expression  tree,  either  because  the  grammar  does  not  handle  some 
operator  patterns  or  because  the  parser  has  made  the  wrong  resolution  of  some 
parsing-action  conflict.  We  must  also  make  sure  t he  parser  does  not  get  into  an 

8.9. 

INSTRUCTION  SELECTION  BY  TREE  REWRITING 

565 

infinite  loop  of  reductions  of  productions  with  single  symbols  on  t he  right  side. 
T he  looping  problem  can  be  solved  using  a  state-splitting  technique  at  t he  time 
t he  parser  tables  are  generated. 

8.9.4  Routines  for  Semantic  Checking 

In  a  code-generation  translation  scheme,  the  same  attributes  appear  as  in  an 
input  tree,  but  often  with  restrictions  on  what  values  the  subscripts  can  have. 
For  example,  a  machine  instruction  m ay  require  t h at  an  a t t r i b u te  value  fall  in 
a  certain  range  or  t h at  the  values  of  two  attributes  be  related. 

These  restrictions  on  a t t r i b u te  values  can  be  specified  as  predicates  t h at  are 
invoked  before  a  reduction  is  made.  In  fact,  t he  general  use  of semantic  actions 
and  predicates  can  provide  greater  flexibility  and  ease  of  description  t h an  a 
purely  grammatical  specification  of  a  code  generator.  Generic  templates  can 
be  used  to  represent  classes  of  instructions  and  t he  semantic  actions  can  then 
be  used  to  pick  instructions  for  specific  cases.  For  example,  two  forms  of  the 
addition  instruction  can  be  represented  with  one  template: 

Ri 

*-

+ 

{ 

if  (a  =  1) 
INC  Ri 

else 

a 

ADD  Ri,  Ri,  #a 

} 

Parsing-action  conflicts  can  be  resolved  by  disambiguating  predicates  t h at 
can  allow  different  selection  strategies  to  be  used  in  different  contexts.  A 
smaller  description  of  a  target  machine  is  possible  because  certain  aspects  of 
the  machine  architecture,  such  as  addressing  modes,  can  be  factored  into  the 
attributes.  The  complication  in  this  approach  is  t h at  it  may  become  difficult 
to  verify  the  accuracy  of  the  translation  scheme  as  a  faithful  description  of  the 
target  machine,  although  this  problem  is  shared  to  some  degree  by  all  code 
generators. 

8.9.5  General  Tree  Matching 

The  LR-parsing  approach  to  p a t t e rn  matching  based  on  prefix  representations 
favors  t he  left  operand  of  a  binary  operator.  In  a  prefix  representation  op  E\  E2, 
t he  limited-lookahead  LR  parsing  decisions  must  be  made  on  the  basis  of  some 
prefix  of  Ei,  since  E\  can  be  arbitrarily  long.  Thus,  p a t t e rn  matching  can  miss 
nuances  of  the  target-instruction  set  t h at  are  due  to  right  operands. 

Instead  prefix  representation,  we  could  use  a  postfix  representation.  But, 

then  an  LR-parsing  approach  to  p a t t e rn  matching  would  favor  the  right  oper 
and. 

For  a hand-written  code  generator,  we  can  use  tree  templates,  as  in  Fig.  8.20, 
as  a  guide  and  write  an  ad-hoc  matcher.  For  example,  if  the  root  of  the  input 
tree  is  labeled  i n d,  then  the  only  p a t t e rn  t h at  could  match  is  for  rule  (5); 
otherwise,  if  the  root  is  labeled  +,  then  the  patterns  t h at  could  match  are  for 
rules  (6-8). 

566 

CHAPTER  8. 

CODE  GENERATION 

For  a  code-generator  generator,  we  need  a  general  tree-matching  algorithm. 

An  efficient  top-down  algorithm  can  be  developed  by  extending  t he  string-
pattern-matching  techniques  of  Chapter  3.  T he  idea  is  to  represent  each  tem 
plate  as  a  set  of  strings,  where  a  string  corresponds  to  a  p a th  from  the  root  to 
a  leaf  in  t he  template.  We  t r e at  all  operands  equally  by  including  t he  position 
number  of  a  child,  from  left  to  right,  in  the  strings. 

E x a m p le  8 . 2 2:  In  building  t he  set  of  strings  for  an  instruction  set,  we  shall 
drop  the  subscripts,  since  p a t t e rn  matching  is  based  on  the  attributes  alone, 
not  on  their  values. 

T he  templates  in  Fig.  8.22  have  t he  following  set  of  strings  from  t he  root  to 

a  leaf: 

C 
+  1  R 
+  2  i nd  1  +  1  C 
+  2  i nd  1  +  2  R 
+  2  R 

The  string  C  represents  t he  template  with  C  at  t he  root.  T he  string  +1R 
represents  the  +  and  its  left  operand  R  in  the  two  templates  t h at  have  +  at 
the  root. 

• 

Ri 

i- 

Ca 

Ri  <- 

+ 

Ri  <- 

+ 

Ca 

Rj 

Figure  8.22:  An  instruction  set  for  tree  matching 

Using  sets  of strings  as  in  Example  8.22,  a  tree-pattern  matcher  can  be  con 

structed  by  using  techniques  for  efficiently  matching  multiple  strings  in  parallel. 
In  practice,  the  tree-rewriting  process  can  be  implemented  by  running  the 
tree-pattern  matcher  during  a  depth-first  traversal  of  the  input  tree  and  per 
forming  the  reductions  as  the  nodes  are  visited  for  the  last  time. 

Instruction  costs  can  be  taken  into  account  by  associating  with  each  tree-
rewriting  rule  the  cost  of t he  sequence  of machine  instructions  generated  if t h at 
rule  is  applied.  In  Section  8.11,  we  discuss  a  dynamic  programming  algorithm 
t h at  can  be  used  in  conjunction  with  tree-pattern  matching. 

By  running  the  dynamic  programming  algorithm  concurrently,  we  can  select 
an  optimal  sequence  of  matches  using  t he  cost  information  associated  with 
each  rule.  We  may  need  to  defer  deciding  upon  a  match  until  the  cost  of  all 
alternatives  is  known.  Using  this  approach,  a  small,  efficient  code  generator  can 

8.10. 

OPTIMAL  CODE  GENERATION  FOR  EXPRESSIONS 

567 

be  constructed  quickly  from  a  tree-rewriting  scheme.  Moreover,  the  dynamic 
programming  algorithm  frees  the  code-generator  designer  from  having  to  resolve 
conflicting  matches  or  decide  upon  an  order  for  the  evaluation. 

8.9.6  Exercises  for  Section  8.9 

Exercise 8.9.1:  Construct  syntax  trees  for  each  of  the  following  statements 
assuming  all  nonconstant  operands  are  in  memory  locations: 

a )x  = 

a * b + c * d; 

b)  x [ i]  =  y [ j]  *  z[ k ]; 

c)  x  =  x  +  1; 

Use  the  tree-rewriting  scheme  in  Fig. 8.20  to  generate  code  for  each  statement. 

Exercise 8.9.2 :  Repeat  Exercise 8.9.1  above  using  the  syntax-directed  trans 
lation  scheme  in  Fig. 8.21  in  place  of  the  tree-rewriting  scheme. 

! Exercise 8.9.3:  Extend  the  tree-rewriting  scheme  in  Fig. 8.20  to  apply  to 

while- st at ement s. 

! Exercise 8.9.4:  How  would  you  extend  tree  rewriting  to  apply  to  DAG's? 

8.10  Optimal  Code  Generation  for  Expressions 

We  can  choose  registers  optimally  when  a  basic  block  consists  of a  single  expres 
sion  evaluation,  or  if  we  accept  t h at  it  is  sufficient  to  generate  code  for  a  block 
one  expression  at  a  time.  In  the  following  algorithm,  we  introduce  a  numbering 
scheme  for  the  nodes  of  an  expression  tree  (a  syntax  tree  for  an  expression)  t h at 
allows  us  to  generate  optimal  code  for  an  expression  tree  when  there  is  a  fixed 
number  of  registers  with  which  to  evaluate  the  expression. 

8.10.1  Ershov  Numbers 

We  begin  by  assigning  to  the  nodes  of  an  expression  tree  a  number  t h at  tells 
how  many  registers  are  needed  to  evaluate  t h at  node  without  storing  any  tem 
poraries.  These  numbers  are  sometimes  called  Ershov  numbers,  after  A.  Ershov, 
who  used  a  similar  scheme  for  machines  with  a  single  arithmetic  register.  For 
our  machine  model,  t he  rules  are: 

1.  Label  any  leaf  1. 

2.  T he  label  of  an  interior  node  with  one  child  is  the  label  of  its  child. 

3.  T he  label  of  an  interior  node  with  two  children  is 

568 

CHAPTER  8. 

CODE  GENERATION 

(a)  The  larger  of  the  labels  of  its  children,  if  those  labels  are  different. 

(b)  One  plus  the  label  of  its  children  if  the  labels  are  the  same. 

E x a m p le  8.23  :  In  Fig.  8.23  we  see  an  expression  tree  (with  operators  omitted) 
t h at  might  be  the  tree  for  expression  (a  —  b)  +  e  x  (c  +  d)  or  the  three-address 
code: 

tl  =  a  -  b 
t2  =  c  +  d 
t3  =  e  *  t2 
t4  =  tl  +  t3 

Each  of  the  five  leaves  is  labeled  1  by  rule  (1).  Then,  we  can  label  the  interior 
node  for  tl  = a - b,  since  b o th  of  its  children  are  labeled.  Rule  (3b)  applies,  so 
it  gets  label  one  more  t h an  t he  labels  of its  children,  t h at  is,  2.  T he  same  holds 
for  the  interior  node  for  t2 =  c + d. 

Figure  8.23:  A  tree  labeled  with  Ershov  numbers 

Now,  we  can  work  on  the  node  for  t3 = e  *  t 2.  Its  children  have  labels  1  and 
2,  so  the  label  of  the  node  for  t3  is  t he  maximum,  2,  by  rule  (3a).  Finally,  t he 
root,  the  node  for  t4 = tl  + t 3,  has  two  children  with  label  2,  and  therefore  it 
gets  label  3. 

• 

8.10.2  Generating  Code  From  Labeled  Expression  Trees 

It  can  be  proved  t h a t,  in  our  machine  model,  where  all  operands  must  be  in 
registers,  and  registers  can  be  used  by  b o th  an  operand  and  t he  result  of  an 
operation,  the  label  of  a  node  is  the  fewest  registers  with  which  the  expression 
can  be  evaluated  using  no  stores  of  temporary  results.  Since  in  this  model,  we 
are  forced  to  load  each  operand,  and  we  are  forced  to  compute  the  result  cor 
responding  to  each  interior  node,  the  only  thing  t h at  can  make  the  generated 
code  inferior  to  the  optimal  code  is  if  there  are  unnecessary  stores  of  tempo 
raries.  T he  argument  for  this  claim  is  embedded  in  the  following  algorithm  for 
generating  code  with  no  stores  of temporaries,  using  a  number  of registers  equal 
to  t he  label  of  the  root. 

A l g o r i t hm  8 . 2 4:  Generating  code  from  a  labeled  expression  tree. 

8.10. 

OPTIMAL  CODE  GENERATION  FOR  EXPRESSIONS 

569 

I N P U T:  A  labeled  tree  with  each  operand  appearing  once  (that  is,  no  common 
subexpressions). 

O U T P U T:  An  optimal  sequence  of  machine  instructions  to  evaluate  the  root 
into  a  register. 

M E T H O D:  T he following is  a recursive  algorithm  to  generate the  machine  code. 
T he  steps  below  are  applied,  starting  at  t he  root  of  t he  tree.  If  t he  algorithm 
is  applied  to  a  node  with  label  k,  then  only  k  registers  will  be  used.  However, 
there  is  a  "base"  6  >  1  for  the  registers  used  so  t h at  the  actual  registers  used 
are  Rb,Rb+i,-  --Rb+k-i-  T he  result  always  appears 

in  Rb+k-i-

1.  To  generate  machine  code  for  an  interior  node  with  label  k  and  two  chil 

dren  with  equal  labels  (which  must  be  k  —  1)  do  the  following: 

(a)  Recursively  generate  code  for  the  right  child,  using  base  6  +  1.  T he 

result  of t he  right  child  appears  in  register  Rb+k • 

(b)  Recursively  generate  code  for  t he  left  child,  using  base  6;  t he  result 

appears 

in  Rb+k-i-

(c)  Generate  the 

instruction  OP  Rb+k,Rb+k-i,Rb+k,  where  OP 

is  t he 

appropriate  operation  for  the  interior  node  in  question. 

2.  Suppose  we  have  an  interior  node  with  label  k  and  children  with  unequal 
labels.  Then  one  of the  children,  which  we'll  call  the  "big"  child,  has  label 
k,  and  t he  other  child,  t he  "little"  child,  has  some  label  m  <  k.  Do  t he 
following  to  generate  code  for  this  interior  node,  using  base  6: 

(a)  Recursively  generate  code  for  the  big  child,  using  base  b;  the  result 

appears  in  register  Rb+k-i-

(b)  Recursively  generate  code  for  the  small  child,  using  base  6;  the  result 
appears  in  register  Rb+m-\.  Note  t h at  since  m  <  k,  neither  Rb+k-i 
nor  any  higher-numbered  register  is  used. 

(c)  Generate  the  instruction  OP  Rb+k-i,  Rb+m-i,  Rb+k-i  or  the  instruc 
tion OP  Rb+k-i,  Rb+k-i,  Rb+m-i5  depending  on  whether  t he  big  child 
is  the  right  or  left  child,  respectively. 

3.  For  a  leaf  representing  operand  x,  if  t he  base  is  6  generate  the  instruction 

LD  Rb,  x. 

• 

E x a m p le  8 . 2 5:  Let  us  apply  Algorithm  8.24  to  the  tree  of  Fig.  8.23.  Since 
the  label  of  the  root  is  3,  the  result  will  appear  in  R3,  and  only  Ry,  R2,  and 
R3  will  be  used.  The  base  for  the  root  is  b  =  1.  Since  the  root  has  children  of 
equal  labels,  we  generate  code  for  the  right  child  first,  with  base  2. 

When  we  generate  code  for  the  right  child  of the  root,  labeled  t 3,  we  find  the 
big  child  is  the  right  child  and  the  little  child  is  t he  left  child.  We  thus  generate 
code  for  the  right  child  first,  with  6  =  2.  Applying  the  rules  for  equal-labeled 
children  and  leaves,  we  generate  the  following  code  for  the  node  labeled  ii: 

570 

CHAPTER  8. 

CODE  GENERATION 

LD  R3,  d 

LD  R2,  c 

ADD R3,  R2,  R3 

Next,  we  generate  code  for  the  left  child  of t he  right  child  of the  root;  this  node 
is  the  leaf labeled  e.  Since  b  —  2,  the  proper  instruction  is 

LD  R2,  e 

Now  we  can  complete  the  code  for  the  right  child  of  the  root  by  adding  t he 
instruction 

MUL R3,  R2,  R3 

T he  algorithm  proceeds  to  generate  code  for  t he  left  child  of  t he  root,  leaving 
the  result  in  R2,  and  with  base 1.  The  complete  sequence  of  instructions  is 
shown  in  Fig. 8.24.  • 

LD  R3,  d 
LD  R2,  c 

ADD R3,  R2,  R3 
LD  R2,  e 

MUL R3,  R2,  R3 

LD  R2,  b 
LD  Rl,  a 
SUB R2,  Rl,  R2 

ADD R3,  R2,  R3 

Figure 8.24:  Optimal  three-register  code  for  t he  tree  of Fig. 8.23 

8.10.3  Evaluating  Expressions  with  an  Insufficient  Supply 

of  Registers 

W h en  there  are  fewer  registers  available  t h an  the  label  of  t he  root  of  t he  tree, 
we  cannot  apply  Algorithm 8.24  directly.  We  need  to  introduce  some  store 
instructions  t h at  spill  values  of subtrees  into  memory,  and  we  then  need  to  load 
those  values  back  into  registers  as  needed.  Here  is  t he  modified  algorithm  t h at 
takes  into  account  a  limitation  on  the  number  of  registers. 

A l g o r i t hm  8 . 2 6:  Generating  code  from  a  labeled  expression  tree. 

I N P U T:  A  labeled  tree  with  each  operand  appearing  once  (i.e.,  no  common 
subexpressions)  and  a  number  of  registers  r  > 2. 

O U T P U T:  An optimal sequence of machine instructions to evaluate the root into 
,Rr-
a  register,  using  no  more  t h an  r  registers,  which  we  assume  are  Ri,  R2,  •.. 

8.10. 

OPTIMAL  CODE  GENERATION  FOR  EXPRESSIONS 

571 

M E T H O D:  Apply  the following recursive  algorithm,  starting  at  the  root  of t he 
tree,  with  base  6  =  1.  For  a  node  JV  with  label  r  or  less,  the  algorithm  is  exactly 
the  same  as  Algorithm  8.24,  and  we  shall  not  repeat  those  steps  here.  However, 
for  interior  nodes  with  a  label  k  >  r,  we  need  to  work  on  each  side  of  the  tree 
separately  and  store  the  result  of  t he  larger  subtree.  T h at  result  is  brought 
back  into  memory  just  before  node  iV  is  evaluated,  and  the  final  step  will  take 
place  in  registers  Rr-\  and  Rr-  T he  modifications  to  t he  basic  algorithm  are 
as  follows: 

1.  Node  N  has  at  least  one  child  with  label  r  or  greater.  Pick  the  larger 
child  (or  either  if  their  labels  are  t he  same)  to  be  the  "big"  child  and  let 
the  other  child  be  the  "little"  child. 

2. Recursively  generate  code  for  the  big  child,  using  base  6  =  1.  T he  result 

of  this  evaluation  will  appear  in  register  Rr. 

3.  Generate  the  machine  instruction  ST  tk,Rr,  where 

is  a  temporary  vari 
able  used  for  temporary  results  used  to  help  evaluate  nodes  with  label 
k. 

4. Generate  code  for  the  little  child  as  follows.  If  the  little  child  has  label  r 
or  greater,  pick  base  6 = 1.  If  the  label  of  the  little  child  is  j  <  r,  then 
pick  6  =  r  —  j.  Then  recursively  apply  this  algorithm  to  the  little  child; 
the  result  appears  in  Rr. 

5.  Generate  the  instruction  LD  Rr^i,tk-

6. If  the  big  child  is  the  right  child  of  N,  then  generate  the  instruction 
If  the  big  child  is  the  left  child,  generate  OP  Rr,  Rr-i,  Rr-

OP  Rr,  Rr,  Rr-\. 

• 

E x a m p le  8 . 2 7:  Let  us  revisit  t he  expression  represented by  Fig.  8.23,  b ut  now 
assume  t h at  r  = 2;  t h at  is,  only  registers Rl  and R2  are  available  to  hold  tem 
poraries  used  in  the  evaluation  of  expressions.  When  we  apply  Algorithm  8.26 
to  Fig.  8.23,  we  see  t h at  the  root,  with  label 3,  has  a  label  t h at  is  larger  t h an 
r  = 2.  Thus,  we  need  to  identify  one  of  the  children  as  the  "big"  child.  Since 
they  have  equal  labels,  either  would  do.  Suppose  we  pick  the  right  child  as  the 
big  child. 

Since  t he  label  of  the  big  child  of  t he  root  is 2,  there  are  enough  registers. 
We  thus  apply  Algorithm  8.24  to  this  subtree,  with  6 =1  and  two  registers. 
The  result  looks  very  much  like  the  code  we  generated  in  Fig.  8.24,  but  with 
registers Rl  and R2  in  place  of R2  and R3.  This  code  is 

LD  R2,  d 
LD  Rl,  c 
ADD R2,  Rl,  R2 
LD  Rl,  e 
MUL R2,  Rl,  R2 

572 

CHAPTER  8. 

CODE  GENERATION 

Now,  since  we  need  both  registers  for  the  left  child  of  the  root,  we  need  to 
generate  the  instruction 

ST  t3,  R2 

Next,  the  left  child  of  the  root  is  handled.  Again,  the  number  of  registers  is 
sufficient  for  this  child,  and  the  code  is 

LD  R2,  b 

LD  Rl,  a 

SUB R2,  Rl,  R2 

Finally,  we  reload  the  temporary  t h at  holds  the  right  child  of  the  root  with  the 
instruction 

LD  Rl,  t3 

and  execute  the  operation  at  the  root  of  the  tree  with  t he  instruction 

ADD R2,  R2,  Rl 

The  complete  sequence  of  instructions  is  shown  in  Fig. 8.25.  • 

LD  R2 
LD  Rl 
ADD  R2 
LD  Rl 
MUL  R2 
ST  t3 
LD  R2 
LD  Rl 
SUB  R2 
LD  Rl 
ADD  R2 

d 
c 

Rl,  R2 
e 

Rl,  R2 
R2 
b 
a 

Rl,  R2 
t3 

R2, Rl 

Figure 8.25:  Optimal  three-register  code  for  the  tree  of  Fig. 8.23,  using  only 
two  registers 

8.10.4  Exercises  for  Section  8.10 

Exercise  8 . 1 0 . 1:  Compute  Ershov  numbers  for  t he  following  expressions: 

a)  a/(b  +  c)  -  d*  (e  +  / ). 

b)  a +  b *  (c *  (d + e ) ). 

8.11. 

DYNAMIC  PROGRAMMING 

CODE-GENERATION 

573 

c) 

(—a  + 

*p)*((b-*q)/(—c+*r)). 

Exercise 8. 1 0 . 2:  Generate  optimal  code  using  two  registers  for  each  of  t he 
expressions  of Exercise 8.10.1. 

Exercise 8. 1 0 . 3:  Generate  optimal  code  using  three  registers  for  each  of  the 
expressions  of Exercise 8.10.1. 

! Exercise 8. 1 0. 4:  Generalize the computation of Ershov numbers to expression 

trees  with  interior  nodes  with  three  or  more  children. 

! Exercise 8.10.5:  An  assignment  to  an  array  element,  such  as  a [ i]  = x,  ap 
pears  to  be  an  operator  with  three  operands:  a,  i,  and  x.  How  would  you  modify 
t he  tree-labeling  scheme  to  generate  optimal  code  for  this  machine  model? 

! Exercise 8. 1 0 . 6:  The  original  Ershov  numbers  were  used  for  a  machine  t h at 
allowed  the  right  operand  of  an  expression  to  be  in  memory,  rather  t h an  a 
register.  How  would  you  modify  the  tree-labeling  scheme  to  generate  optimal 
code  for  this  machine  model? 

! Exercise 8. 1 0 . 7:  Some  machines  require  two  registers  for  certain  single-pre 
cision  values.  Suppose  t h at  the  result  of a  multiplication  of single-register  quan 
tities  requires  two  consecutive  registers,  and  when  we  divide  a/6,  t he  value  of 
a  must  be  held  in  two  consecutive  registers.  How  would  you  modify  the  tree-
labeling  scheme  to  generate  optimal  code  for  this  machine  model? 

8.11  Dynamic  Programming  Code-Generation 

Algorithm  8.26  in  Section  8.10  produces  optimal  code  from  an  expression  tree 
using  an  amount  of  time  t h at  is  a  linear  function  of  t he  size  of  t he  tree.  This 
procedure  works  for  machines  in  which  all  computation  is  done  in  registers  and 
in  which  instructions  consist  of  an  operator  applied  to  two  registers  or  to  a 
register  and  a  memory  location. 

An  algorithm  based  on  the  principle  of  dynamic  programming  can  be  used 
to  extend  the  class  of  machines  for  which  optimal  code  can  be  generated  from 
expression  trees  in  linear  time.  The  dynamic  programming  algorithm  applies 
to  a  broad  class  of  register  machines  with  complex  instruction  sets. 

The  dynamic  programming  algorithm  can  be  used  to  generate  code  for  any 
machine  with  r  interchangeable  registers  R 0 , R 1 , . ..  , Rr—1  and  load,  store,  and 
add  instructions.  For  simplicity,  we  assume  every  instruction  costs  one  unit, 
although  t he  dynamic  programming  algorithm  can  easily  be  modified  to  work 
even  if  each  instruction  has  its  own  cost. 

574 

CHAPTER  8. 

CODE  GENERATION 

8.11.1  Contiguous  Evaluation 

T he  dynamic  programming  algorithm  partitions  the  problem  of  generating  op 
timal  code  for  an  expression  into  the  subproblems  of  generating  optimal  code 
for  the  subexpressions  of  the  given  expression.  As  a  simple  example,  consider 
an  expression  E  of  the  form  E\  +  E2.  An  optimal  program  for  E  is  formed  by 
combining  optimal  programs  for  E\  and  E2,  in  one  or  the  other  order,  followed 
by  code  to  evaluate  the  operator  +.  The  subproblems  of  generating  optimal 
code  for  E\  and  E2  are  solved  similarly. 

An  optimal  program  produced  by  the  dynamic  programming  algorithm  has 
an  important  property. 
It  evaluates  an  expression  E  =  E\  op  E2  "contigu 
ously."  We  can  appreciate  what  this  means  by  looking  at  the  syntax  tree  T  for 
E: 

Here  Ti  and  T2  are  trees  for  E\  and  E2,  respectively. 

We  say  a  program  P  evaluates  a  tree  T  contiguously  if it  first  evaluates  those 
subtrees  of  T  t h at  need  to  be  computed  into  memory.  Then,  it  evaluates  t he 
remainder  of  T  either  in  the  order  Ti,  T2,  and  then  the  root,  or  in  t he  order 
T2,  Ti,  and  then  t he  root,  in  either  case  using  t he  previously  computed  values 
from  memory  whenever  necessary.  As  an  example  of  noncontiguous  evaluation, 
P  might  first  evaluate  part  of  Ti  leaving  the  value  in  a  register  (instead  of 
memory),  next  evaluate  T2,  and  then  return  to  evaluate  t he  rest  of  T i. 

For  the  register  machine  in  this  section,  we  can  prove  t h at  given  any  mach 
ine-language  program  P  to  evaluate  an  expression  tree  T,  we  can  find  an  equiv 
alent  program  P'  such  t h at 

1.  P'  is  of  no  higher  cost  t h an  P, 

2.  P'  uses  no  more  registers  t h an  P,  and 

3.  P'  evaluates  the  tree  contiguously. 

This  result  implies  t h at  every  expression  tree  can  be  evaluated  optimally  by 

a  contiguous  program. 

By  way  of contrast,  machines  with  even-odd register pairs  do  not  always  have 
optimal  contiguous  evaluations;  the  x86  architecture  uses  register  pairs  for  mul 
tiplication  and  division.  For  such  machines,  we  can  give  examples  of  expression 
trees  in  which  an  optimal  machine  language  program  must  first  evaluate  into 
a  register  a  portion  of  the  left  subtree  of  the  root,  then  a  portion  of  the  right 
subtree,  then  another  part  of  the  left  subtree,  then  another  part  of  the  right, 
and  so  on.  This  type  of  oscillation  is  unnecessary  for  an  optimal  evaluation  of 
any  expression  tree  using  the  machine  in  this  section. 

8.11. 

DYNAMIC  PROGRAMMING 

CODE-GENERATION 

575 

T he  contiguous  evaluation  property  defined  above  ensures  t h at  for  any  ex 
pression  tree  T  there  always  exists  an  optimal  program  t h at  consists  of  optimal 
programs  for  subtrees  of  the  root,  followed  by  an  instruction  to  evaluate  the 
root.  This  property  allows  us  to  use  a  dynamic  programming  algorithm  to 
generate  an  optimal  program  for  T. 

8.11.2  The  Dynamic  Programming  Algorithm 

The  dynamic  programming  algorithm  proceeds  in  three  phases  (suppose  the 
target  machine  has  r  registers): 

1.  Compute  bottom-up  for  each  node  n  of  the  expression  tree  T  an  array  C 
of costs,  in  which  the  zth  component  C[i]  is  the  optimal  cost  of computing 
the  subtree  S  rooted  at  n  into  a  register,  assuming  i  registers  are  available 
for  the  computation,  for  1  <  i  <  r. 

2.  Traverse  T,  using  the  cost  vectors  to  determine  which  subtrees  of  T  must 

be  computed  into  memory. 

3.  Traverse  each  tree  using  the  cost  vectors  and  associated  instructions  to 
generate  the  final  target  code.  The  code  for  the  subtrees  computed  into 
memory  locations  is  generated  first. 

Each  of  these  phases  can  be  implemented  to  run  in  time  linearly  proportional 
to  the  size  of  the  expression  tree. 

The  cost  of  computing  a  node  n  includes  whatever  loads  and  stores  are 
necessary  to  evaluate  S  in  the  given  number  of  registers.  It  also  includes  the 
cost  of  computing  the  operator  at  the  root  of  S.  The  zeroth  component  of 
the  cost  vector  is  the  optimal  cost  of  computing  the  subtree  S  into  memory. 
T he  contiguous  evaluation  property  ensures  t h at  an  optimal  program  for  S  can 
be  generated  by  considering  combinations  of  optimal  programs  only  for  the 
subtrees  of  the  root  of  S.  This  restriction  reduces  the  number  of  cases  t h at 
need  to  be  considered. 

In  order  to  compute  the  costs  C[i]  at  node  n,  we  view  the  instructions  as 
tree-rewriting  rules,  as  in  Section  8.9.  Consider  each  template  E  t h at  matches 
the  input  tree  at  node  n.  By  examining  the  cost  vectors  at  the  corresponding 
descendants  of  n,  determine  the  costs  of  evaluating  the  operands  at  the  leaves 
of  E.  For  those  operands  of  E  t h at  are  registers,  consider  all  possible  orders  in 
which  the  corresponding  subtrees  of  T  can  be  evaluated  into  registers.  In  each 
ordering,  the  first  subtree  corresponding  to  a  register  operand  can  be  evaluated 
using  i  available  registers,  the  second  using  i -1  registers,  and  so  on.  To  account 
for  node  n,  add  in  the  cost  of  the  instruction  associated  with  the  template  E. 
T he  value  C[i]  is  then  the  minimum  cost  over  all  possible  orders. 

The  cost  vectors  for  the  entire  tree  T  can  be  computed  b o t t om  up  in  time 
linearly  proportional  to  the  number  of  nodes  in  T.  It  is  convenient  to  store  at 
each  node  the  instruction  used  to  achieve  the  best  cost  for  C[i]  for  each  value 

576 

CHAPTER  8. 

CODE  GENERATION 

of  i.  The  smallest  cost  in  the  vector  for  the  root  of  T  gives  the  minimum  cost 
of  evaluating  T. 

E x a m p le 8.28:  Consider  a  machine  having  two  registers RO  and Rl,  and  the 
following  instructions,  each  of  unit  cost: 

LD  Ri,  Kj 
op  Ri,  Ri,  Ri 
op  Ri,  Ri,  Mi 
LD  Ri,  Ri 
ST  Hi,  Ri 

// Ri =  Mj 
// Ri = Ri op  Rj 
// Ri = Ri  op  Kj 
// Ri =  Ri 
// Mi =  Rj 

In  these  instructions, Ri  is  either RO  or Rl,  and Mi  is  a  memory  location.  T he 
operator  op  corresponds  to  an  arithmetic  operators. 

Let  us  apply  the  dynamic  programming  algorithm  to  generate  optimal  code 
for  t he  syntax  tree  in  Fig  8.26.  In  the  first  phase,  we  compute  the  cost  vectors 
shown  at  each  node.  To  illustrate  this  cost  computation,  consider  t he  cost 
vector  at  the  leaf a.  C[0],  the  cost  of  computing a  into  memory,  is  0  since  it  is 
already  there.  C[l],  t he  cost  of  computing a  into  a  register,  is  1  since  we  can 
load  it  into  a  register  with  the  instruction LD RO, a.  C[2],  the  cost  of loading a 
into  a  register  with  two  registers  available,  is  the  same  as  t h at  with  one  register 
available.  T he  cost  vector  at  leaf a  is  therefore  ( 0 , 1 , 1 ). 

Figure  8.26:  Syntax  tree  for  ( a - b ) + c * ( d / e)  with  cost  vector  at  each  node 

Consider  the  cost  vector  at  the  root.  We  first  determine  t he  minimum 
cost  of  computing  the  root  with  one  and  two  registers  available.  T he  machine 
instruction ADD RO, RO, M  matches  t he  root,  because  t he  root  is  labeled  with 
the  operator  +.  Using  this  instruction,  the  minimum  cost  of  evaluating  the 
root  with  one  register  available  is  t he  minimum  cost  of  computing  its  right 
subtree  into  memory,  plus  t he  minimum  cost  of  computing  its  left  subtree  into 
the  register,  plus  1  for  the  instruction.  No  other  way  exists.  T he  cost  vectors  at 
t he  right  and  left  children  of t he  root  show  t h at  t he  minimum  cost  of  computing 
the  root  with  one  register  available  is  5  +  2  +  1  =  8. 

Now  consider  the  minimum  cost  of  evaluating  t he  root  with  two  registers 
available.  Three  cases  arise  depending  on  which  instruction  is  used  to  compute 
the  root  and  in  what  order  t he  left  and  right  subtrees  of the  root  are  evaluated. 

8.21.  DYNAMIC 

PROGRAMMING 

CODE-GENERATION 

577 

1.  Compute  the  left  subtree  with  two  registers  available  into  register RO, 
compute  t he  right  subtree  with  one  register  available  into  register Rl,  and 
use  the  instruction ADD RO, RO, Rl  to  compute  the  root.  This  sequence 
has  cost  2  +  5  +  1  =  8. 

2.  Compute  the  right  subtree  with  two  registers  available  into Rl,  compute 
the  left  subtree  with  one  register  available  into RO,  and  use  the  instruction 
ADD RO, RO, Rl.  This  sequence  has  cost  4 + 2 +1  =  7. 

3.  Compute  the  right  subtree  into  memory  location M,  compute  t he  left  sub 

tree  with  two  registers  available  into  register RO,  and  use  the  instruction 
ADD RO, RO, M.  This  sequence has  cost  5 + 2 + 1  =  8. 

T he  second  choice  gives  the  minimum  cost  7. 
T he  minimum  cost  of  computing  the  root  into  memory  is  determined  by 
adding  one  to  the  minimum  cost  of  computing  the  root  with  all  registers  avail 
able;  t h at  is,  we  compute  the  root  into  a  register  and  then  store  the  result.  T he 
cost  vector  at  t he  root  is  therefore  (8,8,7). 

From  the  cost  vectors  we  can  easily  construct  the  code  sequence  by  making 
a  traversal  of  the  tree.  From  the  tree  in  Fig.  8.26,  assuming  two  registers  are 
available,  an  optimal  code  sequence  is 

LD  RO,  c 
LD  Rl,  d 
DIV  Rl,  Rl,  e 
MUL  RO,  RO,  Rl 
LD  Rl,  a 
SUB  Rl,  Rl,  b 
ADD  Rl,  Rl,  RO 

// RO  =  c 
// Rl  =  d 
// Rl  =  Rl  / e 
// RO  =  RO  *  Rl 
// Rl  =  a 
// Rl  =  Rl  - b 
// Rl  =  Rl  +  RO 

• 

Dynamic  programming  techniques  have  been  used  in  a  number  of compilers, 
including  t he  second  version  of  the  portable  C  compiler,  P C C 2.  T he  technique 
facilitates  retargeting  because  of  the  applicability  of the  dynamic  programming 
technique  to  a  broad  class  of  machines. 

8.11.3  Exercises  for  Section  8.11 

E x e r c i se  8 . 1 1 . 1:  Augment  the  tree-rewriting  scheme  in  Fig.  8.20  with  costs, 
and  use  dynamic  programming  and  tree  matching  to  generate  code  for  t he 
statements  in  Exercise  8.9.1. 

!!  E x e r c i se  8.11.2  :  How  would  you  extend  dynamic  programming  to  do  optimal 

code  generation  on  dags? 

578 

CHAPTER  8. 

CODE  GENERATION 

8.12  Summary  of  Chapter  8 

4-  Code  generation  is  the  final  phase  of a  compiler.  T he  code  generator  maps 
the  intermediate  representation  produced  by  the  front  end,  or  if there  is  a 
code  optimization  phase  by  the  code  optimizer,  into  the  target  program. 

• 

Instruction  selection  is  t he  process  of  choosing  target-language  instruc 
tions  for  each  IR  statement. 

•  Register  allocation  is  the  process  of  deciding  which  IR  values  to  keep 
in  registers.  Graph  coloring  is  an  effective  technique  for  doing  register 
allocation  in  compilers. 

•  Register  assignment  is  the  process  of  deciding  which  register  should  hold 

a  given  IR  value. 

•  A  retargetable  compiler  is  one  t h at  can  generate  code  for  multiple  instruc 

tion  sets. 

•  A  virtual  machine  is  an  interpreter  for  a  bytecode  intermediate  language 

produced  by  languages  such  as  Java  and  C #. 

4-  A  CISC  machine  is  typically  a  two-address  machine  with  relatively  few 
registers,  several  register  classes,  and  variable-length  instructions  with 
complex  addressing  modes. 

•  A  RISC  machine  is  typically  a  three-address  machine  with  many  registers 

in  which  operations  are  done  in  registers. 

•  A  basic  block  is  a  maximal  sequence  of  consecutive  three-address  state 
ments  in  which  flow  of  control  can  only  enter  at  the  first  statement  of  the 
block  and  leave  at  the  last  statement  without  halting  or  branching  except 
possibly  at  the  last  statement  in  the  basic  block. 

•  A  flow  graph  is  a  graphical  representation  of a  program  in  which  the  nodes 
of the  graph  are  basic  blocks  and  the  edges  of the  graph  show  how  control 
can  flow  among  the  blocks. 

4-  A  loop  in  a  flow  graph  is  a  strongly  connected  region  with  a  single  entry 

point  called  the  loop  header. 

•  A  DAG representation  of a  basic  block  is  a  directed  acyclic  graph  in  which 
the  nodes  of t he  DAG  represent  t he  statements  within  the  block  and  each 
child  of  a  node  corresponds  to  the  statement  t h at  is  the  last  definition  of 
an  operand  used  in  t he  statement. 

•  Peephole  optimizations  are  local  code-improving  transformations  t h at  can 

be  applied  to  a  program,  usually  through  a  sliding  window. 

8.13. 

REFERENCES  FOR  CHAPTER  8 

579 

* 

Instruction  selection  can  be  done  by  a  tree-rewriting  process  in  which 
tree  patterns  corresponding  to  machine  instructions  are  used  to  tile  a 
syntax  tree.  We  can  associate  costs  with  the  tree-rewriting  rules  and 
apply  dynamic  programming  to  obtain  an  optimal  tiling  for  useful  classes 
of  machines  and  expressions. 

4-  An  Ershov  number  tells  how  many  registers  are  needed  to  evaluate  an 

expression  without  storing  any  temporaries. 

•  Spill  code  is  an  instruction  sequence  t h at  stores  a  value  in  a  register  into 
memory  in  order  to  make  room  to  hold  another  value  in  t h at  register. 

8.13  References  for  Chapter  8 

Many  of the  techniques  covered  in  this  chapter  have  their  origins  in  the  earliest 
compilers.  Ershov's  labeling  algorithm  appeared  in  1958  [7].  Sethi  and  Ullman 
[16]  used  this  labeling  in  an  algorithm  t h at  they  prove  generated  optimal  code 
for  arithmetic  expressions.  Aho  and  Johnson  [1]  used  dynamic  programming 
to  generate  optimal  code  for  expression  trees  on  CISC  machines.  Hennessy 
and  Patterson  [12]  has  a  good  discussion  on  the  evolution  of  CISC  and  RISC 
machine  architectures  and  the  tradeoffs  involved  in  designing  a  good  instruction 
set. 

RISC  architectures  became  popular  after  1990,  although  their  origins  go 
back  to  computers  like  the  CDC  6600,  first  delivered  in  1964.  Many  of  the 
computers  designed  before  1990  were  CISC  machines,  but  most  of  the  general-
purpose  computers  installed  after  1990  are  still  CISC  machines  because  they  are 
based  on  the  Intel  80x86  architecture  and  its  descendants,  such  as  t he  Pentium. 
The  Burroughs  B5000  delivered  in  1963  was  an  early  stack-based  machine. 

Many  of the  heuristics  for  code  generation  proposed  in  this  chapter  have  been 
used  in  various  compilers.  Our  strategy  of  allocating  a  fixed  number  of registers 
to  hold  variables  for  the  duration  of  a  loop  was  used  in  the  implementation  of 
Fortran  H  by  Lowry  and  Medlock  [13]. 

Efficient  register  allocation  techniques  have  also  been  studied  from  t he  time 
of  the  earliest  compilers.  Graph  coloring  as  a  register-allocation  technique  was 
proposed  by  Cocke,  Ershov  [8],  and  Schwartz  [15].  Many  variants  of  graph-
coloring  algorithms  have  been  proposed  for  register  allocation.  Our  treatment 
of  graph  coloring  follows  Chaitin  [3]  [4].  Chow  and  Hennessy  describe  their 
priority-based  coloring  algorithm  for  register  allocation  in  [5].  See  [6]  for  a 
discussion  of  more  recent  graph-splitting  and  rewriting  techniques  for  register 
allocation. 

Lexical  analyzer  and  parser  generators  spurred  the  development  of  pattern-
directed  instruction  selection.  Glanville  and  G r a h am  [11]  used  LR-parser  gen 
eration  techniques  for  automated  instruction  selection.  Table-driven  code  gen 
erators  evolved  into  a  variety  of  tree-pattern  matching  code-generation  tools 
[14].  Aho,  Ganapathi,  and  Tjiang  [2]  combined  efficient  tree-pattern  matching 

580 

CHAPTER  8. 

CODE  GENERATION 

techniques  with  dynamic  programming  in  the  code  generation  tool  twig.  Fraser, 
Hanson,  and  Proebsting  [10]  further  refined  these  ideas  in  their  simple  efficient 
code-generator  generator. 

1.  Aho,  A.  V.  and  S.  C.  Johnson,  "Optimal  code  generation  for  expression 

trees,"  J.  ACM  23:3,  pp.  488-501. 

2.  Aho,  A.  V.,  M.  Ganapathi,  and  S.  W.  K.  Tjiang,  "Code  generation  using 

tree  matching  and  dynamic  programming,"  ACM  Trans.  Programming 
Languages  and  Systems  11:4  (1989),  pp.  491-516. 

3.  Chaitin,  G.  J.,  M.  A.  Auslander,  A.  K.  Chandra,  J.  Cocke,  M.  E.  Hop 

kins,  and  P.  W.  Markstein,  "Register  allocation  via  coloring,"  Computer 
Languages  6:1  (1981),  pp.  47-57. 

4.  Chaitin,  G.  J.,  "Register  allocation  and  spilling  via  graph  coloring,"  ACM 

SIGPLAN  Notices  17:6  (1982),  pp.  201-207. 

5.  Chow,  F.  and  J.  L.  Hennessy,  "The  priority-based  coloring  approach  to 

register  allocation,"  ACM  Trans.  Programming  Languages  and  Systems 
12:4  (1990),  pp.  501-536. 

6.  Cooper,  K.  D.  and  L.  Torczon,  Engineering  a  Compiler,  Morgan  Kauf-

mann,  San  Francisco  CA,  2004. 

7.  Ershov,  A.  P.,  "On  programming  of  arithmetic  operations,"  Comm.  ACM 

1:8  (1958),  pp.  3-6.  Also,  Comm.  ACM  1:9  (1958),  p.  16. 

8.  Ershov,  A.  P.,  The  Alpha  Automatic  Programming  System,  Academic 

Press,  New  York,  1971. 

9.  Fischer,  C.  N.  and  R.  J.  LeBlanc,  Crafting  a  Compiler  with  C,  Benjamin-

Cummings,  Redwood  City,  CA,  1991. 

10.  Fraser,  C.  W.,  D.  R.  Hanson,  and  T.  A.  Proebsting,  "Engineering  a  sim 

ple,  efficient  code  generator  generator,"  ACM  Letters  on  Programming 
Languages  and  Systems  1:3  (1992),  pp.  213-226. 

11.  Glanville,  R.  S.  and  S.  L.  Graham,  "A  new  method  for  compiler  code  gen 

eration,"  Conf.  Rec.  Fifth  ACM  Symposium  on  Principles  of  Programming 
Languages  (1978),  pp.  231-240. 

12.  Hennessy,  J.  L.  and  D.  A.  Patterson,  Computer  Architecture:  A  Quanti 
tative  Approach,  Third  Edition,  Morgan  Kaufman,  San  Francisco,  2003. 

13.  Lowry,  E.  S.  and  C.  W.  Medlock,  "Object  code  optimization,"  Comm. 

ACM  12:1  (1969),  pp.  13-22. 

8.13. 

REFERENCES  FOR  CHAPTER  8 

581 

14.  Pelegri-Llopart,  E.  and  S.  L.  Graham,  "Optimal  code  generation  for  ex 
pressions  trees:  an  application  of  BURS  theory,"  Conf.  Rec.  Fifteenth  An 
nual  ACM  Symposium  on  Principles  of  Programming  Languages 
p p.  294-308. 

(1988), 

15.  Schwartz, 

the  SETL 
J.  T.,  On  Programming:  An  Interim  Report  on 
Project,  Technical  Report,  Courant  Institute  of  Mathematical  Sciences, 
New  York,  1973. 

16.  Sethi,  R.  and  J.  D.  Ullman,  "The  generation  of optimal  code  for  arithmetic 

expressions,"  J.  ACM  17:4  (1970),  pp.  715-728. 

Chapter  9 

Machine-Independent 
Optimizations 

High-level  language  constructs  can  introduce  substantial  run-time  overhead  if 
we  naively  translate  each  construct  independently  into  machine  code.  This 
chapter  discusses  how  to  eliminate  many  of  these  inefficiencies.  Elimination  of 
unnecessary  instructions  in  object  code,  or  the  replacement  of  one  sequence  of 
instructions  by  a  faster  sequence  of  instructions  t h at  does  t he  same  thing  is 
usually  called  "code  improvement"  or  "code  optimization." 

Local  code  optimization  (code  improvement  within  a  basic  block)  was  intro 
duced  in  Section  8.5.  This  chapter  deals  with  global  code  optimization,  where 
improvements  take  into  account  what  happens  across  basic  blocks.  We  begin 
in  Section  9.1  with  a  discussion  of the  principal  opportunities  for  code  improve 
ment. 

Most  global  optimizations  are  based  on  data-flow  analyses,  which  are  algo 
rithms  to  gather  information  about  a  program.  T he  results  of data-flow  analyses 
all  have  the  same  form:  for  each  instruction  in  the  program,  they  specify  some 
property  t h at  must  hold  every  time  t h at  instruction  is  executed.  T he  analyses 
differ  in  the  properties  they  compute.  For  example,  a  constant-propagation 
analysis  computes,  for  each  point  in  the  program,  and  for  each  variable  used  by 
t he  program,  whether  t h at  variable  has  a  unique  constant  value  at  t h at  point. 
This  information  may  be  used  to  replace  variable  references  by  constant  values, 
for  instance.  As  another  example,  a  liveness  analysis  determines,  for  each  point 
in  the  program,  whether  the  value  held  by  a  particular  variable  at  t h at  point  is 
sure  to  be  overwritten  before  it  is  read.  If  so,  we  do  not  need  to  preserve  t h at 
value,  either  in  a  register  or  in  a  memory  location. 

We  introduce  data-flow  analysis  in  Section  9.2,  including  several  important 
examples  of t he  kind  of  information  we  gather  globally  and  then  use  to  improve 
the  code.  Section  9.3  introduces  t he  general  idea  of  a  data-flow  framework, 
of  which  the  data-flow  analyses  in  Section  9.2  are  special  cases.  We  can  use 
essentially  the  same  algorithms  for  all  these  instances  of  data-flow  analysis,  and 

583 

584 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

we  can  measure  the  performance  of these  algorithms  and  show  their  correctness 
on  all  instances,  as  well.  Section  9.4  is  an  example  of the  general  framework  t h at 
does  more  powerful  analysis  t h an  the  earlier  examples.  Then,  in  Section  9.5 
we  consider  a  powerful  technique,  called  "partial  redundancy  elimination,"  for 
optimizing  the  placement  of  each  expression  evaluation  in  the  program.  T he 
solution  to  this  problem  requires  the  solution  of  a  variety  of  different  data-flow 
problems. 

In  Section  9.6  we  take  up  the  discovery  and  analysis  of  loops  in  programs. 
The  identification  of  loops  leads  to  another  family  of  algorithms  for  solving 
data-flow  problems  t h at  is  based  on  the  hierarchical  structure  of  the  loops  of 
a  well-formed  ("reducible")  program.  This  approach  to  data-flow  analysis  is 
covered in  Section  9.7.  Finally,  Section  9.8  uses  hierarchical analysis to  eliminate 
induction  variables  (essentially,  variables  t h at  count  t he  number  of  iterations 
around  a  loop).  This  code  improvement  is  one  of  t he  most  important  we  can 
make  for  programs  written  in  commonly  used  programming  languages. 

9.1  The  Principal  Sources  of  Optimization 

A  compiler  optimization  must  preserve  the  semantics  of  the  original  program. 
Except  in  very  special  circumstances,  once  a  programmer  chooses  and  imple 
ments  a  particular  algorithm,  the  compiler  cannot  understand  enough  about 
the  program  to  replace  it  with  a  substantially  different  and  more  efficient  al 
gorithm.  A  compiler  knows  only  how  to  apply  relatively  low-level  semantic 
transformations,  using  general  facts  such  as  algebraic  identities  like  i  + 0  =  i  or 
program  semantics  such  as  the  fact  t h at  performing  t he  same  operation  on  t he 
same  values  yields  the  same  result. 

9.1.1  Causes  of  Redundancy 

There  are  many  redundant  operations  in  a  typical  program.  Sometimes  the 
redundancy  is  available  at  the  source  level.  For  instance,  a  programmer  may 
find  it  more  direct  and  convenient  to  recalculate  some  result,  leaving  it  to 
the  compiler  to  recognize  t h at  only  one  such  calculation  is  necessary.  But 
more  often,  the  redundancy  is  a  side  effect  of  having  written  the  program  in  a 
high-level  language.  In  most  languages  (other  t h an  C  or  C + +,  where  pointer 
arithmetic  is  allowed),  programmers  have  no  choice  but  to  refer  to  elements  of 
an  array  or  fields  in  a  structure  through  accesses  like  A[i][j]  or  X  -+  fl. 

As  a  program  is  compiled,  each  of  these  high-level  data-structure  accesses 

expands  into  a  number  of low-level  arithmetic  operations,  such  as  the  computa 
tion  of  t he  location  of  the  (i, j ) th  element  of  a  matrix  A.  Accesses  to  the  same 
d a ta  structure  often  share  many  common  low-level  operations.  Programmers 
are  not  aware  of  these  low-level  operations  and  cannot  eliminate  the  redundan 
cies  themselves.  It  is,  in  fact,  preferable  from  a  software-engineering  perspec 
tive  t h at  programmers  only  access  d a ta  elements  by  their  high-level  names;  t he 

9.1. 

THE  PRINCIPAL  SOURCES  OF  OPTIMIZATION 

585 

programs  are  easier  to  write  and,  more  importantly,  easier  to  understand  and 
evolve.  By  having  a  compiler  eliminate  the  redundancies,  we  get  the  best  of 
b o th  worlds:  the  programs  are  b o th  efficient  and  easy  to  maintain. 

9.1.2  A  Running  Example:  Quicksort 

In  t he  following,  we  shall  use  a  fragment  of  a  sorting  program  called  quicksort 
to  illustrate  several  important  code-improving  transformations.  The  C  program 
in  Fig.  9.1  is  derived  from  Sedgewick,1  who  discussed  the  hand-optimization  of 
such  a  program.  We  shall  not  discuss  all  the  subtle  algorithmic  aspects  of  this 
program  here,  for  example,  t he  fact  t h at  a[0)  must  contain  the  smallest  of  t he 
sorted  elements,  and  a[max]  the  largest. 

v o id  q u i c k s o r t ( i nt  m, 

i nt  n) 

/*  r e c u r s i v e ly  s o r ts  a[m] 

t h r o u gh  a [ n]  */ 

{ 

} 

j; 

(n  <=  m)  r e t u r n; 

i, 
i nt 
i nt  v,  x; 
if 
/*  f r a g m e nt  b e g i ns  h e re  */ 
i = m - l; 
w h i le 

j  = n;  v = a [ n ]; 

(1) 

i 

do  i  =  i + 1;  w h i le  ( a [ i]  <  v ); 
do  j  =  j - 1;  w h i le  ( a [ j]  >  v ); 
if 
j)  b r e a k; 
x  =  a [ i]  ;  a [ i]  =  a [ j]  ;  a [ j]  =  x; 

(i  >= 

/*  swap  a [ i]  ,  a [ j]  */ 

} 
x  =  a [ i ];  a [ i]  =  a [ n]  ;  a [ n]  =  x; 
/*  f r a g m e nt  ends  h e re  */ 
q u i c k s o r t ( m , j );  q u i c k s o r t ( i + 1 , n ); 

/*  swap  a [ i]  ,  a [ n]  */ 

Figure  9.1:  C  code  for  quicksort 

Before  we  can  optimize  away  the  redundancies  in  address  calculations,  the 
address  operations  in  a  program  first  must  be  broken  down  into  low-level  arith 
metic  operations  to  expose  t he  redundancies.  In  the  rest  of  this  chapter,  we  as 
sume  t h at  the  intermediate  representation  consists  of three-address  statements, 
where  t e m p o r a ry  variables  are  used  to  hold  all  the  results  of  intermediate  ex 
pressions.  Intermediate  code  for  the  marked  fragment  of t he  program  in  Fig.  9.1 
is  shown  in  Fig.  9.2. 

In  this  example  we  assume  t h at  integers  occupy  four  bytes.  T he  assignment 
x  =  a [ i]  is  translated  as  in  Section  6.4.4  into  the  two  three-address  statements 

1R.  Sedgewick,  "Implementing  Quicksort  Programs,"  Comm.  ACM, 21,1978,  pp.  847-857. 

586 

(1) 
(2) 
(3) 
(4) 
(5) 
(6) 
(7) 
(8) 
(9) 
(10) 
(11) 
(12) 
(13) 
(14) 
(15) 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

i  =  m-1 
j  =  n 
tl  =  4*n 
v  =  a C t l] 
i  =  i+1 
t2  =  4 *i 
t3  =  a [ t 2] 
if 

t 3 <v  g o to 

j  =  j -l 
t4  =  4 *j 
t5  =  a [ t 4] 
if 
if 
t6  =  4 *i 
x  =  a [ t 6] 

t 5 >v  g o to 
i > =j  g o to 

(5) 

(9) 
(23) 

(16) 
(17) 
(18) 
(19) 
(20) 
(21) 
(22) 
(23) 
(24) 
(25) 
(26) 
(27) 
(28) 
(29) 
(30) 

t7  =  4 *i 
t8  =  4 *j 
t9  =  a [ t 8] 
a [ t 7]  =  t9 
t lO  =  4 *j 
a [ t l 0]  =  x 
(5) 
g o to 
t il  =  4 *i 
x 
t l2  =  4 *i 
t l3  =  4*n 
t l4  =  a [ t l 3] 
a [ t l 2]  =  t l4 
t l5  =  4*n 
a [ t l 5]  =  x 

=  a [ t i l] 

Figure  9.2:  Three-address  code  for  fragment  in  Fig.  9.1 

t6  =  4 *i 
x  =  a [ t 6] 

as  shown  in  steps  (14)  and  (15)  of  Fig.  9.2.  Similarly,  a [ j]  =  x  becomes 

t lO  =  4 *j 
a [ t l 0]  =  x 

in  steps  (20)  and  (21).  Notice  t h at  every  array  access  in  t he  original  program 
translates  into  a  pair  of  steps,  consisting  of  a  multiplication  and  an  array-
subscripting  operation.  As  a  result,  this  short  program  fragment  translates 
into  a  rather  long  sequence  of  three-address  operations. 

Figure  9.3  is  the  flow  graph  for  t he  program  in  Fig.  9.2.  Block  B\  is  t he 
entry  node.  All  conditional  and  unconditional  jumps  to  statements  in  Fig.  9.2 
have  been  replaced  in  Fig.  9.3  by  jumps  to  t he  block  of  which  the  statements 
are  leaders,  as  in  Section  8.4.  In  Fig.  9.3,  there  are  three  loops.  Blocks  B2  and 
JE?3  are  loops  by  themselves.  Blocks  B2,  B3,  B±,  and  B$  together  form  a  loop, 
with  B2  t he  only  entry  point. 

9.1.3 

Semantics-Preserving  Transformations 

There  are  a  number  of ways  in  which  a  compiler  can  improve  a  program  without 
changing  the  function  it  computes.  Common-subexpression  elimination,  copy 
propagation,  dead-code  elimination,  and  constant  folding  are  common  examples 
transformations;  we  shall 
of  such  function-preserving  (or  semantics-preserving) 
consider  each  in  t u r n. 

9.1. 

THE  PRINCIPAL  SOURCES  OF  OPTIMIZATION 

587 

i  = m-1 
j = n 
tl  =  4*n 
V  =  a[tl] 

~ 

,  , 

i  =  i+l 
t2  =  4*i 
t3  =  a[t2] 
if  t3<v  goto B 2 

j  =  j-1 
t4  = 4 * -
t5  =  a[t4] 
if  t5>v  goto 5 

if  i>=j  goto B 6 

t6  =  4*i 
x  =  a[t6] 
tl  =  4*i 
t8  =  4*j 
t9  =  a[t8] 
a[t7]  = t9 
tlO  =  4*j 
a[tlO]  = x 
goto  B0 

til  =  4*i 
x  =  a[tll] 
tl2  =  4*i 
tl3  =  4*n 
tl4  =  a[tl3] 
a[tl2]  = tl4 
tl5  =  4*n 
a[tl5]  = x 

Figure  9.3:  Flow  graph  for  the  quicksort  fragment 

588 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

Frequently,  a  program  will  include  several  calculations  of  the  same  value, 
such  as  an  offset  in  an  array.  As  mentioned  in  Section  9.1.2,  some  of  these 
duplicate  calculations  cannot  be  avoided  by  t he  programmer  because  they  lie 
below  the  level  of  detail  accessible  within  the  source  language.  For  example, 
block  £5  shown  in  Fig.  9.4(a)  recalculates  4 * i  and  4* j,  although  none  of these 
calculations  were  requested  explicitly  by  the  programmer. 

t6  =  4*i 
x  =  a[t6] 
t7  =  4*i 
t8  =  4*j 
t9  =  a[t8] 
a[t7]  = t9 
tlO  =  4*j 
a[tlO]  = x 
goto  5 

t6  =  4*i 
x  =  a[t6] 
t8  =  4*j 
t9  =  a[t8] 
a[t6]  = t9 
a[t8]  = x 
goto  B2 

(a)  Before. 

(b)  After. 

Figure  9.4:  Local  common-subexpression  elimination 

9.1.4  Global  Common  Subexpressions 

An  occurrence  of  an  expression  E  is  called  a  common  subexpression  if  E  was 
previously  computed  and  t he  values  of the  variables  in  E  have  not  changed  since 
the  previous  computation.  We  avoid  recomputing  E  if we  can  use  its  previously 
computed  value;  t h at  is,  the  variable  x  to  which  t he  previous  computation  of 
E  was  assigned  has  not  changed  in  the  interim.2 

E x a m p le  9 . 1:  The  assignments  to  t7  and  t lO  in  Fig.  9.4(a)  compute  t he 
common  subexpressions  4  *  i  and  4  *  j,  respectively.  These  steps  have  been 
eliminated  in  Fig.  9.4(b),  which  uses  t6  instead  of  t7  and  t8  instead  of  t l O. 
• 

E x a m p le  9.2  :  Figure  9.5  shows  t he  result  of eliminating  both  global  and  local 
common  subexpressions  from  blocks  f?5  and  BQ  in  the  flow  graph  of  Fig.  9.3. 
We  first  discuss  the  transformation  of  B5  and  then  mention  some  subtleties 
involving  arrays. 

After  local  common  subexpressions  are  eliminated,  B§  still  evaluates  4*i  and 
4* j,  as  shown  in  Fig.  9.4(b).  Both  are  common  subexpressions;  in  particular, 
the  three  statements 

2If  x  has  changed,  it  may  still  be  possible  to  reuse  the  computation  of  E  if  we  assign  its 
value  to  a  new  variable  y,  as  well  as  to  x,  and  use  the  value  of  y  in  place  of  a  recomputation 
of  E. 

9.1. 

THE  PRINCIPAL  SOURCES  OF  OPTIMIZATION 

589 

i  = m-1 
j  = n 
tl  =  4*n 
v  =  a[tl] 

i  =  i+1 
t2  =  4*i 
t3  =  a[t2] 
if  t3<v  goto 52 

j  =  j-l 
t4  =  4*j 
t5  =  a[t4] 
if  t5>v  goto 53 

if  i>=j  goto  B6 

x  =  t3 
a[t2]  = t5 
a[t4]  = x 
goto  B2 

x  =  t3 
tl4  =  a[tl] 
a[t2]  = tl4 
a[tl]  = x 

Figure  9.5: 

and  B6  after  common-subexpression  elimination 

t8  =  4*j 
t9  =  a[ t 8] 
a[ t 8]  =  x 

in  B<$  can  be  replaced  by 

t9  =  a[ t 4] 
a[ t 4]  =  x 

using  £4  computed  in  block  B3.  In  Fig.  9.5,  observe  t h at  as  control  passes  from 
the  evaluation  of  4  * j  in  B3  to  B5,  there  is  no  change  to  j  and  no  change  to  £4, 
so  t4  can  be  used  if  4  * j  is  needed. 

Another  common  subexpression  comes  to  light  in  B5  after  £4  replaces  t8. 
T he  new  expression  a[£4]  corresponds  to  the  value  of  a[j]  at  t he  source  level. 
Not  only  does  j  retain  its  value  as  control  leaves  B3  and  then  enters  f?5,  but 

590 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

a[j],  a  value  computed  into  a  temporary  £5,  does  too,  because  there  are  no 
assignments  to  elements  of  the  array  a  in  the  interim.  The  statements 

t9  =  a [ t 4] 
a [ t 6]  =  t9 

in  j?5  therefore  can  be  replaced  by 

a [ t 6]  =  t5 

Analogously,  the  value  assigned  to  x  in  block  B5  of  Fig.  9.4(b)  is  seen  to  be 
the  same  as  the  value  assigned  to  t3  in  block  B2.  Block  B5  in  Fig.  9.5  is  the 
result  of eliminating  common  subexpressions  corresponding  to  t he  values  of the 
source  level  expressions  a[i]  and  a[j]  from  B5  in  Fig.  9.4(b).  A  similar  series  of 
transformations  has  been  done  to  BQ  in  Fig.  9.5. 

The  expression  a[tl]  in  blocks  B\  and  BQ  of  Fig.  9.5  is  not  considered  a 
common  subexpression,  although  tl  can  be  used  in  b o th  places.  After  control 
leaves  B\  and  before  it  reaches  BQ,  it  can  go  through  B5,  where  there  are 
assignments  to  a.  Hence,  a[tl]  may  not  have  the  same  value  on  reaching  BQ  as 
it  did  on  leaving  B\,  and  it  is  not  safe  to  treat  a[tl]  as  a  common  subexpression. 
• 

9.1.5  Copy  Propagation 

Block  B$  in  Fig.  9.5  can  be  further  improved  by  eliminating  x,  using  two  new 
transformations.  One  concerns  assignments  of the  form  u  =  v  called  copy  state 
ments,  or  copies  for  short.  Had  we  gone  into  more  detail  in  Example  9.2,  copies 
would  have  arisen  much  sooner,  because  the  normal  algorithm  for  eliminating 
common  subexpressions  introduces  them,  as  do  several  other  algorithms. 

a  =  d+e 

b  =  d+e 

t  =  d+e 
a  =  t 

t  =  d+e 
b  =  t 

c  =  d+e 

Ca) 

c  =  t 

Cb) 

Figure  9.6:  Copies  introduced  during  common  subexpression  elimination 

E x a m p le  9 . 3:  In  order  to  eliminate  the  common  subexpression  from  t he  state 
ment  c  =  d+e  in  Fig.  9.6(a),  we  must  use  a  new  variable  t  to  hold  t he  value  of 
d + e.  T he  value  of variable  t,  instead  of t h at  of t he  expression  d + e,  is  assigned 
to  c  in  Fig.  9.6(b).  Since  control  may  reach  c  =  d+e  either  after  t he  assignment 
to  a  or  after  the  assignment  to  b,  it  would  be  incorrect  to  replace  c  =  d+e  by 
either  c  =  a  or  by  c  =  b. 

• 

9.1. 

THE  PRINCIPAL  SOURCES  OF  OPTIMIZATION 

591 

T he  idea  behind  t he  copy-propagation  transformation  is  to  use  v  for  ii, 
wherever  possible  after  the  copy  statement  u  =  v.  For  example,  the  assignment 
x  =  t3  in  block  B5  of  Fig.  9.5  is  a  copy.  Copy  propagation  applied  to  B$  yields 
the  code  in  Fig.  9.7.  This  change  may  not  appear  to  be  an  improvement,  but, 
as  we  shall  see  in  Section  9.1.6,  it  gives  us  the  opportunity  to  eliminate  the 
assignment  to  x. 

x  =  t3 
a [ t 2]  =  t5 
a [ t 4]  =  t3 
g o to  B2 

Figure  9.7:  Basic  block  B5  after  copy  propagation 

9.1.6  Dead-Code  Elimination 

A  variable  is  live  at  a  point  in  a  program  if  its  value  can  be  used  subsequently; 
otherwise,  it  is  dead  at  t h at  point.  A  related  idea  is  dead  (or  useless)  code  — 
statements  t h at  compute  values  t h at  never  get  used.  While  the  programmer  is 
unlikely  to  introduce  any  dead  code  intentionally,  it  may  appear  as  the  result 
of  previous  transformations. 

E x a m p le  9 . 4:  Suppose  debug  is  set  to  TRUE  or  FALSE  at  various  points  in  the 
program,  and  used  in  statements  like 

if 

(debug)  p r i nt 

. .. 

It  may  be  possible  for  the  compiler  to  deduce  t h at  each  time  the  program 
reaches  this  statement,  the  value  of debug  is  FALSE.  Usually,  it  is  because  there 
is  one  particular  statement 

debug  =  FALSE 

t h at  must  be  the  last  assignment  to  debug  prior  to  any  tests  of  the  value  of 
debug,  no  m a t t er  what  sequence  of  branches  the  program  actually  takes. 
If 
copy  propagation  replaces  debug  by  FALSE,  then  the  print  statement  is  dead 
because  it  cannot  be  reached.  We  can  eliminate  b o th  t he  test  and  t he  print 
operation  from  the  object  code.  More  generally,  deducing  at  compile  time  t h at 
the  value  of an  expression  is  a  constant  and  using  t he  constant  instead  is  known 
as  constant  folding. 

• 

One  advantage  of  copy  propagation  is  t h at  it  often  turns  the  copy  state 

ment  into  dead  code.  For  example,  copy  propagation  followed  by  dead-code 
elimination  removes  the  assignment  to  x  and  transforms  the  code  in  Fig  9.7 
into 

592 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

a[t2]  = t5 

a[t4]  = t3 

goto  B2 

This  code  is  a  further  improvement  of  block  B5  in  Fig.  9.5. 

9.1.7  Code  Motion 

Loops  are  a  very  important  place  for  optimizations,  especially  t he  inner  loops 
where  programs  tend  to  spend  t he  bulk  of  their  time.  T he  running  time  of  a 
program  may  be  improved  if  we  decrease  the  number  of instructions  in  an  inner 
loop,  even  if  we  increase  the  amount  of  code  outside  t h at  loop. 

An  important  modification  t h at  decreases  t he  amount  of  code  in  a  loop  is 
code  motion.  This  transformation  takes  an  expression  t h at  yields  the  same 
result  independent  of  the  number  of  times  a  loop  is  executed  (a  loop-invariant 
computation)  and  evaluates  the  expression  before  t he  loop.  Note  t h at  the  notion 
"before  the  loop"  assumes  the  existence  of  an  entry  for  the  loop,  t h at  is,  one 
basic  block  to  which  all  j u m ps  from  outside  the  loop  go  (see  Section  8.4.5). 

E x a m p le  9 . 5:  Evaluation  of  limit — 2  is  a  loop-invariant  computation  in  the 
following  while-statement: 

while  (i  <=  limit-2)  /*  statement  does  not  change  limit  */ 

Code  motion  will  result  in  the  equivalent  code 

t  =  limit-2 
while  (i  <=  t)  /*  statement  does  not  change  limit  or  t  */ 

Now,  t he  computation  of  limit — 2  is  performed  once,  before  we  enter  t he  loop. 
Previously,  there  would  be  n +1  calculations  of  limit— 2  if  we  iterated  t he  body 
of t he  loop  n  times. 

• 

9.1.8 

Induction  Variables  and  Reduction  in  Strength 

Another  important  optimization  is  to  find  induction  variables  in  loops  and 
optimize  their  computation.  A  variable  x  is  said  to  be  an.  "induction  variable" 
if there  is  a  positive  or  negative  constant  c  such  t h at  each  time  x  is  assigned,  its 
value  increases  by  c.  For  instance,  i  and  tl  are  induction  variables  in  t he  loop 
containing  B2  of  Fig.  9.5. 
Induction  variables  can  be  computed  with  a  single 
increment  (addition  or  subtraction)  per  loop  iteration.  T he  transformation  of 
replacing  an  expensive  operation,  such  as  multiplication,  by  a  cheaper  one, 
such  as  addition,  is  known  as  strength  reduction.  But  induction  variables  not 
only  allow  us  sometimes  to  perform  a  strength  reduction;  often  it  is  possible  to 
eliminate  all  but  one  of  a  group  of  induction  variables  whose  values  remain  in 
lock  step  as  we  go  around  t he  loop. 

9.1. 

THE  PRINCIPAL  SOURCES  OF  OPTIMIZATION 

593 

j = :  j-l 
t4  = t4- 4 
t5  =  a[t4] 
if  t5>v  goto  B  3 

if  i>=j  goto  B  6 

x  =  t3 
a[t2]  = t5 
a[t4]  = x 
goto  B  2 

x  =  t3 
tl4  =  a[tl] 
a[t2]  = tl4 
a[tl]  = x 

Figure  9.8:  Strength  reduction  applied  to  4  *  j  in  block  S3 

W h en  processing  loops,  it  is  useful  to  work  "inside-out";  t h at  is,  we  shall 
start  with  t he  inner  loops  and  proceed  to  progressively  larger,  surrounding 
loops.  Thus,  we  shall  see  how this  optimization  applies  to  our  quicksort  example 
by  beginning  with  one  of t he  innermost  loops:  B3  by  itself.  Note  t h at  t he  values 
of  j  and  £4  remain  in  lock  step;  every  time  the  value  of  j  decreases  by  1,  the 
value  of  t4  decreases  by  4,  because  4  *  j  is  assigned  to  t4.  These  variables,  j 
and  t4,  thus  form  a  good  example  of  a  pair  of  induction  variables. 

W h en  there  are  two  or  more  induction  variables  in  a  loop,  it  may  be  possible 
to  get  rid  of all  but  one.  For  t he  inner  loop  of B3  in  Fig.  9.5,  we  cannot  get  rid  of 
either  j  or  t4  completely;  t4  is  used  in  B3  and  j  is  used  in  B±.  However,  we  can 
illustrate  reduction  in  strength  and  a  part  of  t he  process  of  induction-variable 
elimination.  Eventually,  j  will  be  eliminated  when  the  outer  loop  consisting  of 
blocks  B?,,B3,B±  and  B5 

is  considered. 

594 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

E x a m p le  9 . 6:  As  the  relationship  £4  =  4  *  j  surely  holds  after  assignment  to 
£4  in  Fig.  9.5,  and  £4  is  not  changed  elsewhere  in  the  inner  loop  around  B3,  it 
follows  t h at  just  after  the  statement  j  =  j -1  the  relationship  £4  =  4  *  j  +  4 
must  hold.  We  may  therefore  replace  t he  assignment  t4  =  4*  j  by  t4  =  t 4 - 4. 
T he  only  problem  is  t h at  £4  does  not  have  a  value  when  we  enter  block  B3  for 
the  first  time. 

Since  we  must  maintain  the  relationship  £4  =  4 * j  on  entry  to  t he  block  B3, 
we  place  an  initialization  of £4  at  the  end  of t he  block  where  j  itself is  initialized, 
shown  by  t he  dashed  addition  to  block  B\  in  Fig.  9.8.  Although  we  have  added 
one  more  instruction,  which  is  executed  once  in  block  Bi,  t he  replacement  of  a 
multiplication  by  a  subtraction  will  speed  up  the  object  code  if  multiplication 
takes  more  time  t h an  addition  or  subtraction,  as  is  t he  case  on  many  machines. 
• 

i = m-1 
j  = n 
tl  =  4*n 
v  =  a [ t l] 
t2  =  4*i 
t4  =  4*j 

t2  = t2+4 
t3  =  a[t2] 
if  t3<v  g o t oB2 

t4  = t4--4 
t5  =  a[t4] 
if  t5>v  goto  B  3 

B2 

B3 

B4 

tl4 =  a[tl] 
a[t2]  = tl4 
a[tl]  = t3 

Figure  9.9:  Flow  graph  after  induction-variable  elimination 

We  conclude  this  section  with  one  more  instance  of  induction-variable  elim-

9.1. 

THE  PRINCIPAL  SOURCES  OF  OPTIMIZATION 

595 

ination.  This  example  treats  i  and  j  in  the  context  of the  outer  loop  containing 
B2,  B3,  B4,  and  B5. 

E x a m p le  9 . 7:  After  reduction  in  strength  is  applied  to  the  inner  loops  around 
B2  and  B3,  the  only  use  of  i  and  j  is  to  determine  the  outcome  of  the  test  in 
block  B4.  We  know  t h at  t he  values  of i  and  t2  satisfy  t he  relationship  t2  =  4 * i, 
while  those  of j  and  £4  satisfy  t he  relationship  ti  =  4* j.  Thus,  the  test  t2  >  ti 
can  substitute  for  i  >  j.  Once  this  replacement  is  made,  i  in  block  B2  and  j  in 
block  B3  become  dead  variables,  and  the  assignments  to  them  in  these  blocks 
become  dead  code  t h at  can  be  eliminated.  T he  resulting  flow  graph  is  shown 
in  Fig.  9.9. 

• 

E N T RY 

B 

(1) a  =  1 

(2) b  =  2 

(3) c  =  a +b 

(4) d  =  c-a 

(5) d  =  b +d 

(8) b  =  a +b 

(9) e  =  c-a 

(6) d  =  a +b 

(7) e  -  e +1 

(10) a  =  b*d 

(11) b  =  a-d 

EXIT 

Figure  9.10:  Flow  graph  for  Exercise  9.1.1 

T he  code-improving  transformations  we  have  discussed  have  been  effective. 
In  Fig.  9.9,  the  numbers  of  instructions  in  blocks  B2  and  B3  have  been  reduced 
from  4  to  3,  compared  with  the  original flow graph  in  Fig.  9.3.  In  B5,  the  number 

596 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

has  been  reduced  from  9  to  3,  and  in  B6  from  8  to  3.  True,  Bi  has  grown  from 
four  instructions  to  six,  but  Bi  is  executed  only  once  in  t he  fragment,  so  the 
total  running  time  is  barely  affected  by  the  size  of  B\. 

9 . 1 .9  Exercises for Section 9 .1 

E x e r c i se  9 . 1 . 1:  For  the  flow  graph  in  Fig.  9.10: 

a)  Identify  the  loops  of  the  flow  graph. 

b)  Statements  (1)  and  (2)  in  B\  are  b o th  copy  statements,  in  which  a  and  b 
are  given  constant  values.  For  which  uses  of a  and  b  can  we  perform  copy 
propagation  and  replace  these  uses  of  variables  by  uses  of  a  constant?  Do 
so,  wherever  possible. 

c)  Identify  any  global  common  subexpressions  for  each  loop. 

d)  Identify  any  induction  variables  for  each  loop.  Be  sure  to  take  into  account 

any  constants  introduced  in  (b). 

e)  Identify  any  loop-invariant  computations  for  each  loop. 

E x e r c i se  9 . 1 . 2:  Apply  the  transformations  of  this  section  to  the  flow  graph 
of  Fig.  8.9. 

E x e r c i se  9 . 1 . 3:  Apply  the  transformations  of  this  section  to  your flow graphs 
from  (a)  Exercise  8.4.1;  (b)  Exercise  8.4.2. 

E x e r c i se  9 . 1 . 4:  In  Fig.  9.11  is  intermediate  code  to  compute  the  dot  product 
of two  vectors  A  and  B.  Optimize  this  code  by  eliminating  common  subexpres 
sions,  performing  reduction  in  strength  on  induction  variables,  and  eliminating 
all  the  induction  variables  you  can. 

dp  =  0. 
i 
L:  tl  = 

=  0 

i*8 

i*8 

t2  =  A[tl] 
t3  = 
t4  =  B[t3] 
t5  =  t2*t4 
dp  =  dp+t5 
=  i+1 
i 
if 
i <n  goto  L 

Figure  9.11:  Intermediate  code  to  compute  t he  dot  product 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

597 

9.2 

Introduction  to  Data-Flow  Analysis 

All  t he  optimizations  introduced  in  Section  9.1  depend  on  data-flow  analysis. 
"Data-flow  analysis"  refers  to  a  body  of  techniques  t h at  derive  information 
about  t he flow of d a ta  along  program  execution  paths.  For  example,  one  way  to 
implement  global  common  subexpression  elimination  requires  us  to  determine 
whether  two  textually  identical  expressions  evaluate  to  the  same  value  along 
any  possible  execution  p a th  of  the  program.  As  another  example,  if  the  result 
of  an  assignment  is  not  used  along  any  subsequent  execution  p a t h,  then  we 
can  eliminate  t he  assignment  as  dead  code.  These  and  many  other  important 
questions  can  be  answered  by  data-flow  analysis. 

9.2.1  The  Data-Flow  Abstraction 

Following  Section  1.6.2,  t he  execution  of  a  program  can  be  viewed  as  a  series 
of  transformations  of  the  program  state,  which  consists  of  the  values  of  all  the 
variables  in  t he  program,  including  those  associated  with  stack  frames  below  the 
top  of  the  run-time  stack.  Each  execution  of  an  intermediate-code  statement 
transforms  an  input  state  to  a  new  output  state.  The  input  state  is  associated 
with  t he  program  point  before  the  statement  and  the  output  state  is  associated 
with  the  program  point  after  the  statement. 

When  we  analyze  the  behavior  of  a  program,  we  must  consider  all  the  pos 
sible  sequences  of  program  points  ("paths")  through  a  flow  graph  t h at  the  pro 
gram  execution  can  take.  We  then  extract,  from  the  possible  program  states 
at  each  point,  t he  information  we  need  for  the  particular  data-flow  analysis 
problem  we  want  to  solve.  In  more  complex  analyses,  we  must  consider  paths 
t h at  j u mp  among  t he  flow  graphs  for  various  procedures,  as  calls  and  returns 
are  executed.  However,  to  begin  our  study,  we  shall  concentrate  on  the  paths 
through  a  single  flow  graph  for  a  single  procedure. 

Let  us  see  what  the  flow  graph  tells  us  about  t he  possible  execution  p a t h s. 

•  Within  one  basic  block,  the  program  point  after  a  statement  is  the  same 

as  the  program  point  before  the  next  statement. 

•  If there  is  an  edge  from  block  B\  to  block  E>2 ,  then  the  program  point  after 
the  last  statement  of  By  may  be  followed  immediately  by  the  program 
point  before  the  first  statement  of  B2. 

Thus,  we  may  define  an  execution  path  (or  just  path)  from  point  pi  to  point  pn 
to  be  a  sequence  of  points  pi,p2,... 
,n  -  1, 
either 

,pn  such  t h at  for  each  i  =  1 , 2 , . .. 

1.  Pi  is  t he  point  immediately  preceding  a  statement  and  pi+i  is  the  point 

immediately  following  t h at  same  statement,  or 

2.  pi  is  t he  end  of  some  block  and  pi+1  is  the  beginning  of  a  successor  block. 

598 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

In  general,  there  is  an  infinite  number  of possible  execution  paths  through  a 
program,  and  there  is  no  finite  upper  bound  on  t he  length  of an  execution  p a t h. 
Program  analyses  summarize  all  the  possible  program  states  t h at  can  occur  at 
a  point  in  the  program  with  a  finite  set  of  facts.  Different  analyses  may  choose 
to  abstract  out  different  information,  and  in  general,  no  analysis  is  necessarily 
a  perfect  representation  of  t he  state. 

E x a m p le  9 . 8:  Even  the  simple  program  in  Fig.  9.12  describes  an  unbounded 
number  of  execution  p a t h s.  Not  entering  t he  loop  at  all,  the  shortest  com 
plete  execution  p a th  consists  of  the  program  points  ( 1 , 2 , 3 , 4 , 9 ).  T he  next 
shortest  p a th  executes  one  iteration  of  the  loop  and  consists  of  the  points 
( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 3 , 4 , 9 ).  We  know  t h a t,  for  example,  the  first  time  program 
point  (5)  is  executed,  t he  value  of  a  is  1  due  to  definition  d\.  We  say  t h at 
di  reaches  point  (5)  in  t he  f i r st  iteration.  In  subsequent  iterations,  ^3  reaches 
point  (5)  and  the  value  of  a  is  243. 

Figure  9.12:  Example  program  illustrating  the  data-flow  abstraction 

In  general,  it  is  not  possible  to  keep  track  of  all  t he  program  states  for  all 
possible  paths.  In  data-flow  analysis,  we  do  not  distinguish  among  the  paths 
taken  to  reach  a program  point.  Moreover,  we  do  not  keep  track  of entire  states; 
rather,  we  abstract  out  certain  details,  keeping  only  t he  d a ta  we  need  for  t he 
purpose  of  t he  analysis.  Two  examples  will  illustrate  how  t he  same  program 
states  may  lead  to  different  information  abstracted  at  a  point. 

1.  To  help  users  debug  their  programs,  we  m ay  wish  to  find  out  what  are 
all  t he  values  a  variable  may  have  at  a  program  point,  and  where  these 
values  may  be  defined.  For  instance,  we  may  summarize  all  the  program 
states  at  point  (5)  by  saying  t h at  the  value  of  a  is  one  of  {1,243},  and 
t h at  it  may  be  defined  by  one  of  { ^ 1 , ^ 3 }.  The  definitions  t h at  may  reach 
a  program  point  along  some  p a th  are  known  as  reaching  definitions. 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

599 

2.  Suppose,  instead,  we  are  interested  in  implementing  constant  folding.  If a 
use  of  the  variable  x  is  reached  by  only  one  definition,  and  t h at  definition 
assigns  a  constant  to  x,  then  we  can  simply  replace  x  by  the  constant. 
If,  on  the  other  hand,  several  definitions  of  x  may  reach  a  single  program 
point,  then  we  cannot  perform  constant  folding  on  x.  Thus,  for  constant 
folding  we  wish  to  find  those  definitions  t h at  are  t he  unique  definition  of 
their  variable  to  reach  a  given  program  point,  no  m a t t er  which  execution 
p a th  is  taken.  For  point  (5)  of  Fig.  9.12,  there  is  no  definition  t h at  must 
be  the  definition  of  a  at  t h at  point,  so  this  set  is  empty  for  a  at  point  (5). 
Even  if  a  variable  has  a  unique  definition  at  a  point,  t h at  definition  must 
assign  a  constant  to  the  variable.  Thus,  we  may  simply  describe  certain 
variables  as  "not  a  constant,"  instead  of  collecting  all  their  possible  values 
or  all  their  possible  definitions. 

Thus,  we  see  t h at  the  same  information  may  be  summarized  differently,  de 
pending  on  t he  purpose  of  the  analysis. 

• 

9.2.2  The  Data-Flow  Analysis  Schema 

In  each  application  of  data-flow  analysis,  we  associate  with  every  program  point 
a  data-flow  value  t h at  represents  an  abstraction  of the  set  of all  possible  program 
states  t h at  can  be  observed  for  t h at  point.  The  set  of  possible  data-flow  values 
is  t he  domain  for  this  application.  For  example,  the  domain  of  data-flow  values 
for  reaching  definitions  is  the  set  of  all  subsets  of  definitions  in  the  program. 
A  particular  data-flow  value  is  a  set  of  definitions,  and  we  want  to  associate 
with  each  point  in  the  program  the  exact  set  of  definitions  t h at  can  reach  t h at 
point.  As  discussed  above,  the  choice  of  abstraction  depends  on  the  goal  of  the 
analysis;  to  be  efficient,  we  only  keep  track  of  information  t h at  is  relevant. 

We  denote  the  data-flow  values  before  and  after  each  statement  s  by  I N [ S] 
and  OUT[s],  respectively.  The  data-flow  problem  is  to  find  a  solution  to  a  set 
of  constraints  on  the  I N [ S ] 'S  and  OUT[s]'s,  for  all  statements  s.  There  are  two 
sets  of  constraints:  those  based  on  the  semantics  of  the  statements  ("transfer 
functions")  and  those  based  on  the  flow  of  control. 

Transfer  F u n c t i o ns 

The  data-flow  values  before  and  after  a  statement  are  constrained  by  the  se 
mantics  of  t he  statement.  For  example,  suppose  our  data-flow  analysis  involves 
determining  the  constant  value  of  variables  at  points.  If  variable  a  has  value  v 
before  executing  statement b  =  a,  then  both  a  and  b  will  have  the  value  v  after 
the  statement.  This  relationship  between  the  data-flow  values  before  and  after 
t he  assignment  statement  is  known  as  a  transfer  function. 

Transfer  functions  come  in  two  flavors:  information  may  propagate  forward 
along  execution  p a t h s,  or  it  may  flow  backwards  up  the  execution  p a t h s. 
In 
a  forward-flow  problem,  the  transfer  function  of  a  statement  s,  which  we  shall 

600 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

usually  denote  fa,  takes  the  data-flow  value  before  the  statement  and  produces 
a  new  data-flow  value  after  the  statement.  T h at  is, 

OUT[a]  =  / , ( l N [ a ] ). 

Conversely,  in  a  backward-flow  problem,  the  transfer  function  fa  for  statement 
8  converts  a  data-flow  value  after  the  statement  to  a  new  data-flow  value  before 
the  statement.  T h at  is, 

IN[s]  =  /s( O U T [ s ] ). 

C o n t r o l - F l ow  C o n s t r a i n ts 

T he  second  set  of  constraints  on  data-flow  values  is  derived  from  the  flow  of 
control.  Within  a  basic  block,  control  flow  is  simple.  If  a  block  B  consists  of 
statements  s i, s2,  •  •  •  ,sn  in  t h at  order,  then  t he  control-flow  value  out  of  Si  is 
the  same  as  the  control-flow  value  into  Si+i.  T h at  is, 

l N [ si +i]  =  O U T f o ],  for  all  i  =  1 , 2 , . ..  , n  -  1. 

However,  control-flow  edges  between  basic  blocks  create  more  complex  con 
straints  between  the  last  statement  of  one  basic  block  and  the  first  statement 
of  the  following  block.  For  example,  if  we  are  interested  in  collecting  all  the 
definitions  t h at  may  reach  a  program  point,  then  the  set  of  definitions  reaching 
the  leader  statement  of  a  basic  block  is  t he  union  of  the  definitions  after  t he 
last  statements  of  each  of  the  predecessor  blocks.  T he  next  section  gives  t he 
details  of  how  d a ta  flows  among  the  blocks. 

9.2,3  Data-Flow  Schemas  on  Basic  Blocks 

While  a  data-flow  schema  technically  involves  data-flow  values  at  each  point  in 
the  program,  we  can  save  time  and  space  by  recognizing t h at  what  goes  on  inside 
a  block  is  usually  quite  simple.  Control  flows  from  the  beginning  to  the  end  of 
the  block,  without  interruption  or  branching.  Thus,  we  can  restate  t he  schema 
in  terms  of  data-flow  values  entering  and  leaving  the  blocks.  We  denote  the 
data-flow  values  immediately  before  and  immediately  after  each  basic  block  B 
by  m[B]  and  0 U T p S ],  respectively.  The  constraints  involving  m[B]  and  0UT[i?] 
can  be  derived  from  those  involving  w[s]  and  OUT[s]  for  t he  various  statements 
s  in  B  as  follows. 

Suppose  block  B  consists  of  statements  s i , . ..  ,  sn,  in  t h at  order.  If  si  is  t he 
first  statement  of  basic  block  B,  then  m[B]  =  I N [ S I],  Similarly,  if  sn  is  the  last 
statement  of  basic  block  B,  then  OUT[S]  =  O U T [ s „ ].  T he  transfer  function  of 
a  basic  block  B,  which  we  denote  fB,  can  be  derived  by  composing  the  transfer 
functions  of the  statements  in  the  block.  T h at  is,  let  fa.  be  the  transfer  function 
of  statement  st.  Then  fB  =  fSn  o  ... o  f8i  o  fSl.  T he  relationship  between  t he 
beginning  and  end  of  the  block  is 

O U T [ B]  = 

/B( I N [ B ] ). 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

601 

T he  constraints  due  to  control flow between  basic  blocks  can  easily  be  rewrit 

ten  by  substituting  IN[B]  and  OVT[B]  for  I N [ S I]  and  O U T [ s „ ],  respectively.  For 
instance,  if  data-flow  values  are  information  about  the  sets  of  constants  t h at 
may  be  assigned  to  a  variable,  then  we  have  a  forward-flow  problem  in  which 

P  a  predecessor  of  B 

O U T [ P ]. 

W h en  the  data-flow  is  backwards  as  we  shall  soon  see  in  live-variable  analy 
sis,  t he  equations  are  similar,  b ut  with  the  roles  of t he  IN's  and  OUT's  reversed. 
T h at  is, 

I N [ B]  = 

/B( O U T [ B ]) 

Unlike  linear  arithmetic  equations,  the  data-flow  equations  usually  do  not 
have  a  unique  solution.  Our  goal  is  to  find  the  most  "precise"  solution  t h at 
satisfies  the  two  sets  of  constraints:  control-flow  and  transfer  constraints.  T h at 
is,  we  need  a  solution  t h at  encourages  valid  code  improvements,  but  does  not 
justify  unsafe  transformations  —  those  t h at  change  what  the  program  com 
putes.  This  issue  is  discussed  briefly  in  the  box  on  "Conservatism"  and  more 
extensively  in  Section  9.3.4.  In  the  following  subsections,  we  discuss  some  of the 
most  i m p o r t a nt  examples  of  problems  t h at  can  be  solved  by  data-flow  analysis. 

9.2.4  Reaching  Definitions 

"Reaching  definitions"  is  one  of the  most  common  and  useful  data-flow  schemas. 
By  knowing  where  in  a  program  each  variable  x  may  have  been  defined  when 
control  reaches  each  point  p,  we  can  determine  many  things  about  x.  For  just 
two  examples,  a  compiler  then  knows  whether  x  is  a  constant  at  point  p,  and 
a  debugger  can  tell  whether  it  is  possible  for  x  to  be  an  undefined  variable, 
should  x  be  used  at  p. 

We  say  a  definition  d  reaches  a  point  p  if  there  is  a  p a th  from  the  point 
immediately  following  d  to  p,  such  t h at  d  is  not  "killed"  along  t h at  p a t h.  We 
kill  a  definition  of  a  variable  x  if  there  is  any  other  definition  of  x  anywhere 
along  the  p a t h .3  Intuitively,  if  a  definition  d  of  some  variable  x  reaches  point 
p,  then  d  might  be  the  place  at  which  the  value  of  x  used  at  p  was  last  defined. 
A  definition  of  a  variable  x  is  a  statement  t h at  assigns,  or  may  assign,  a 
value  to  x.  Procedure  parameters,  array  accesses,  and  indirect  references  all 
may  have  aliases,  and  it  is  not  easy  to  tell  if  a  statement  is  referring  to  a 
particular  variable  x.  P r o g r am  analysis  must  be  conservative;  if  we  do  not 

3N o te  that  the  path  may  have  loops,  so  we  could  come  to  another  occurrence  of  d  along 

the  path,  which  does  not  "kill"  d. 

602 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

Detecting  Possible  Uses  Before  Definition 

Here  is  how  we  use  a  solution  to  t he  reaching-definitions  problem  to  detect 
uses  before  definition.  The  trick  is  to  introduce  a  d u m my  definition  for 
each  variable  x  in  the  entry  to  t he  flow  graph. 
If  the  d u m my  definition 
of  x  reaches  a  point  p  where  x  might  be  used,  then  there  might  be  an 
opportunity  to  use  x  before  definition.  Note  t h at  we  can  never  be  abso 
lutely  certain  t h at  the  program  has  a  bug,  since  there  may  be  some  reason, 
possibly  involving  a  complex  logical  argument,  why  t he  p a th  along  which 
p  is  reached  without  a  real  definition  of  x  can  never  be  taken. 

know  whether  a  statement  s  is  assigning  a  value  to  x,  we  must  assume  t h at 
it  may  assign  to  it;  t h at  is,  variable  x  after  statement  s  may  have  either  its 
original  value  before  s  or  the  new  value  created  by  s.  For  t he  sake  of simplicity, 
the  rest  of  the  chapter  assumes  t h at  we  are  dealing  only  with  variables  t h at 
have  no  aliases.  This  class  of variables  includes  all  local  scalar  variables  in  most 
languages;  in  the  case  of  C  and  C++,  local  variables  whose  addresses  have  been 
computed  at  some  point  are  excluded. 

E x a m p le  9 . 9:  Shown  in  Fig.  9.13  is  a flow graph  with  seven  definitions.  Let  us 
focus  on  t he  definitions  reaching  block  B2 •  All  the  definitions  in  block  B\  reach 
t he  beginning  of block  B2.  The  definition  d§:  j  =  j -1  in  block  B2  also  reaches 
the  beginning  of  block  B2,  because  no  other  definitions  of  j  can  be  found  in  t he 
loop  leading  back  to  B2.  This  definition,  however,  kills  the  definition  d2:  j  =  n, 
preventing  it  from  reaching  B%  or  J34.  T he  statement  d4:  i  = 
i +1  in  B2  does 
not  reach  the  beginning  of  B2  though,  because  t he  variable  i  is  always  redefined 
by  d^:  i  =  u 3.  Finally,  the  definition  d6: a  =  u2  also  reaches  the  beginning  of 
block  B2. 

• 

By  defining  reaching definitions  as  we  have,  we  sometimes  allow  inaccuracies. 
However,  they  are  all  in  the  "safe,"  or  "conservative,"  direction.  For  example, 
notice  our  assumption  t h at  all  edges  of  a  flow  graph  can  be  traversed.  This 
assumption  may  not  be  true  in  practice.  For  example,  for  no  values  of  a  and 
b  can  the  flow  of  control  actually  reach  statement  2  in  t he  following  program 
fragment: 

if  (a  ==  b)  statement  1; else 

if  (a  ==  b)  statement  2; 

To  decide  in  general  whether  each  p a th  in  a  flow  graph  can  be  taken  is 
an  undecidable  problem.  Thus,  we  simply  assume  t h at  every  p a th  in  the  flow 
graph  can  be  followed  in  some  execution  of  t he  program.  In  most  applications 
of reaching  definitions,  it  is  conservative  to  assume  t h at  a  definition  can  reach  a 
point  even  if it  might  not.  Thus,  we  may  allow  paths  t h at  are  never  be  traversed 
in  any  execution  of t he  program,  and  we  may  allow  definitions  to  pass  through 
ambiguous  definitions  of  t he  same  variable  safely. 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

603 

Conservatism  in  Data-Flow  Analysis 

Since  all  data-flow  schemas  compute  approximations  to  the  ground  t r u th 
(as  defined  by  all  possible  execution  paths  of the  program),  we  are  obliged 
to  assure  t h at  any  errors  are  in  the  "safe"  direction.  A  policy  decision  is 
safe  (or  conservative)  if  it  never  allows  us  to  change  what  the  program 
computes.  Safe  policies  may,  unfortunately,  cause  us  to  miss  some  code 
improvements  t h at  would  retain  the  meaning  of the  program,  but  in  essen 
tially  all  code  optimizations  there  is  no  safe  policy  t h at  misses  nothing.  It 
would  generally  be  unacceptable  to  use  an  unsafe  policy  —  one  t h at  sped 
up  the  code  at  the  expense  of  changing  what  the  program  computes. 

Thus,  when  designing  a  data-flow  schema,  we  must  be  conscious  of 
how  the  information  will  be  used,  and  make  sure  t h at  any  approximations 
we  make  are  in  the  "conservative"  or  "safe"  direction.  Each  schema  and 
application  must  be  considered  independently.  For  instance,  if  we  use 
reaching  definitions  for  constant  folding,  it  is  safe  to  think  a  definition 
reaches  when  it  doesn't  (we  might  think  x  is  not  a  constant,  when  in  fact 
it  is  and  could  have  been  folded),  but  not  safe  to  think  a  definition  doesn't 
reach  when  it  does  (we  might  replace  x  by  a  constant,  when  the  program 
would  at  times  have  a  value  for  x  other  t h an  t h at  constant). 

Transfer  E q u a t i o ns  for  R e a c h i ng  D e f i n i t i o ns 

We  shall  now  set  up  the  constraints  for  the  reaching  definitions  problem.  We 
start  by  examining  t he  details  of  a  single  statement.  Consider  a  definition 

ri:  u  =  v+w 

Here,  and  frequently  in  what  follows,  +  is  used  as  a  generic  binary  operator. 

This  statement  "generates"  a  definition  d  of  variable  u  and  "kills"  all  the 

other  definitions  in  the  program  t h at  define  variable  u,  while  leaving  the  re 
maining  incoming  definitions  unaffected.  The  transfer  function  of  definition  d 
thus  can  be  expressed  as 

fd(x)  =  gend  U  (x  -  killd) 

(9.1) 

where  gend  =  {d},  the  set  of  definitions  generated  by  the  statement,  and  killd 
is  the  set  of  all  other  definitions  of  u  in  the  program. 

As  discussed  in  Section  9.2.2,  t he  transfer  function  of  a  basic  block  can  be 
found  by  composing  the  transfer  functions  of  the  statements  contained  therein. 
T he  composition  of  functions  of  the  form  (9.1),  which  we  shall  refer  to  as  "gen-
kill  form,"  is  also  of  t h at  form,  as  we  can  see  as  follows.  Suppose  there  are  two 
functions  fi(x)  =  gen\  U  (x  -  kill\)  and  f2(x)  =  gen2  U  (x  —  kill2).  T h en 

604 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

ENTRY 

i =  m-1 
j =  n 
.  a  =  ul 

dl 

d3 

d4:  i =  i+1 
d5  :  j =  j-l 

dj  : i =  u3 

EXIT 

gen ^  =  {  dv 

} 

kill^ 

=  {  d4,  dy  d&  dj 

genh 

={d4,  d5 

} 

kill^ 

=  {  dv  dj,  dj  } 

gen  R_  = { 4 ;} 

kilL 

gen 

dj  } 

killB 

=  {  dy  d4  } 

Figure  9.13:  Flow  graph  for  illustrating  reaching  definitions 

M/iO))  =  gen2  U  (geni  U  (x  -  kilh)  -  kilh) 

= 

(gen2  U  (geni  —  kill2))  U  (x  —  (kilh  U  kill2)) 

This  rule  extends  to  a  block  consisting of any number of statements.  Suppose 
block  B  has  n  statements,  with  transfer  functions  fi(x)  =  geni  U  (x  —  kilh)  for 
i  =  1 , 2 , . ..  , n.  Then  t he  transfer  function  for  block  B  may  be  written  as: 

!B{X)  =  genB  U  (x  -  kills), 

kills  =  kilh  U  kill2  U  •  •  •  U  killn 

where 

and 

gens  —  genn  U  ( g e nn_i  —  killn)  U  (genn-2  —  killn-\  —  killn)  U 

•  •  •  U  (#eni  —  kill2  —  kilh  —  •  •  —  killn) 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

605 

Thus,  like  a  statement,  a  basic  block  also  generates  a  set  of  definitions  and 
kills  a  set  of  definitions.  T he  gen  set  contains  all  the  definitions  inside  the  block 
t h at  are  "visible"  immediately  after  the  block  —  we  refer  to  t h em  as  downwards 
exposed.  A  definition  is  downwards  exposed  in  a  basic  block  only  if  it  is  not 
"killed"  by  a  subsequent  definition  to  the  same  variable  inside  t he  same  basic 
block.  A  basic  block's  kill  set  is  simply  the  union  of all  the  definitions  killed  by 
t he  individual  statements.  Notice  t h at  a  definition  may  appear  in  b o th  the  gen 
and  kill  set  of  a  basic  block.  If  so,  the  fact  t h at  it  is  in  gen  takes  precedence, 
because  in  gen-kill  form,  the  kill  set  is  applied  before  t he  gen  set. 

E x a m p le  9 . 1 0:  T he  gen  set  for  the  basic  block 

d\\ 
d2: 

a  =  3 
a  =  4 

is  {d2}  since  d\  is  not  downwards  exposed.  The  kill  set  contains  b o th  d\  and 
d2,  since  d\  kills  d2  and  vice  versa.  Nonetheless,  since  the  subtraction  of  the 
kill  set  precedes  the  union  operation  with  the  gen  set,  the  result  of  the  transfer 
function  for  this  block  always  includes  definition  d2. 

• 

C o n t r o l - F l ow  E q u a t i o ns 

Next,  we  consider  the  set  of  constraints  derived  from  the  control  flow  between 
basic  blocks.  Since  a  definition  reaches  a  program  point  as  long  as  there  exists 
at  least  one  p a th  along  which  the  definition  reaches,  O U T[ P]  C  m[B]  whenever 
there  is  a  control-flow  edge  from  P  to  B.  However,  since  a  definition  cannot 
reach  a  point  unless  there  is  a  p a th  along  which  it  reaches,  w[B]  needs  to  be  no 
larger  t h an  the  union  of  the  reaching  definitions  of  all  the  predecessor  blocks. 
T h at  is,  it  is  safe  to  assume 

We  refer  to  union  as  the  meet  operator  for  reaching  definitions.  In  any  data 
flow  schema,  the  meet  operator  is  the  one  we  use  to  create  a  summary  of  the 
contributions  from  different  paths  at  the  confluence  of  those  paths. 

I t e r a t i ve  A l g o r i t hm  for  R e a c h i ng  D e f i n i t i o ns 

We  assume  t h at  every  control-flow  graph  has  two  empty  basic  blocks,  an  E N T RY 
node,  which  represents  the  starting  point  of  t he  graph,  and  an  E X IT  node  to 
which  all  exits  out  of  the  graph  go.  Since  no  definitions  reach  the  beginning 
of  t he  graph,  t he  transfer  function  for  the  E N T RY  block  is  a  simple  constant 
function  t h at  returns 0  as  an  answer.  T h at  is,  O U T [ E N T R Y]  = 0. 

T he  reaching  definitions  problem  is  defined  by  the  following  equations: 

O U T [ E N T R Y]  =  0 

606 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

and  for  all  basic  blocks  B  other  t h an  E N T R Y, 

0\]T[B] 

=genBU 

(w[B] 

kills) 

m[B]=  (J P  a  predecessor  of  B 

OUTpP]. 

These  equations  can  be  solved  using  the  following  algorithm.  T he  result  of 
the  algorithm  is  the  least  fixedpoint  of  t he  equations,  i.e.,  t he  solution  whose 
assigned  values  to  the  I N's  and  OUT's  is  contained  in  t he  corresponding  values 
for  any  other  solution  to  the  equations.  T he  result  of  the  algorithm  below  is 
acceptable,  since  any  definition  in  one  of the  sets  IN  or  OUT  surely  must  reach 
It  is  a  desirable  solution,  since  it  does  not  include  any 
the  point  described. 
definitions  t h at  we  can  be  sure  do  not  reach. 

A l g o r i t hm  9 . 1 1:  Reaching  definitions. 

INPUT:  A  flow  graph  for  which  kills  and  genB  have  been  computed  for  each 
block  B. 

OUTPUT:  I N [ B]  and  O U T[ B ],  the  set  of  definitions  reaching  the  entry  and  exit 
of  each  block  B  of  the  flow  graph. 

METHOD:  We  use  an  iterative  approach,  in  which  we  start  with  t he  "estimate" 
OUT[JB]  = 0  for  all  B  and  converge  to  t he  desired  values  of  IN  and  OUT.  As 
we  must  iterate  until  the  I N's  (and  hence  the  OUT's)  converge,  we  could  use  a 
boolean  variable  change  to  record,  on  each  pass  through  the  blocks,  whether 
any  OUT  has  changed.  However,  in  this  and  in  similar  algorithms  described 
later,  we  assume  t h at  the  exact  mechanism  for  keeping  track  of  changes  is 
understood,  and  we  elide  those  details. 

T he  algorithm  is  sketched  in  Fig.  9.14.  T he  first  two  lines  initialize  certain 
data-flow values.4  Line  (3)  starts  the  loop  in  which  we  iterate until  convergence, 
and  the  inner  loop  of  lines  (4)  through  (6)  applies  t he  data-flow  equations  to 
every  block  other  t h an  the  entry. 

• 

Intuitively,  Algorithm  9.11  propagates  definitions  as  far  as  they  will  go  with 
out  being  killed,  thus  simulating  all  possible  executions  of  t he  program.  Algo 
rithm  9.11  will  eventually  halt,  because  for  every  B,  OUT[B]  never  shrinks;  once 
a  definition  is  added,  it  stays  there  forever.  (See  Exercise  9.2.6.)  Since  the  set  of 
all  definitions  is  finite,  eventually  there  must  be  a  pass  of t he  while-loop  during 
which  nothing  is  added  to  any  OUT,  and  the  algorithm  then  terminates.  We 
are  safe  terminating  then  because  if  the  OUT's  have  not  changed,  the  I N's  will 

4T he  observant  reader will  notice  that  we  could  easily  combine  lines  (1)  and  (2).  However, 
in  similar  data-flow  algorithms,  it  may  be  necessary  to  initialize  the  entry  or  exit  node  dif 
ferently  from  the  way  we  initialize  the  other  nodes.  Thus,  we  follow  a  pattern  in  all  iterative 
algorithms  of applying  a  "boundary  condition"  like  line  (1)  separately  from  the  initialization 
of line  (2). 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

607 

O U T [ E N T R Y]  =  0; 
for  (each  basic  block  B  other  t h an  E N T R Y)  0UT[B]  = 0; 

1) 
2) 
3)  w h i le  (changes  to  any  OUT  occur) 
4) 

for  (each  basic  block  B  other  t h an  E N T R Y)  { 

5) 

6) 

I N [ £]  =  UP  a  predecessor  of  B 0\JT[P]] 

OUT[S]  =  genB  U 

( I N [ S] 

-  killB)\ 

} 

Figure  9.14:  Iterative  algorithm  to  compute  reaching  definitions 

not  change  on  the  next  pass.  And,  if the  I N 'S  do  not  change,  the  OUT's  cannot, 
so  on  all  subsequent  passes  there  can  be  no  changes. 

T he  number  of nodes  in  the  flow  graph  is  an  upper  bound  on  the  number  of 
times  around  the  while-loop.  T he  reason  is  t h at  if  a  definition  reaches  a  point, 
it  can  do  so  along  a  cycle-free  path,  and  the  number  of  nodes  in  a  flow  graph  is 
an  upper  bound  on  the  number  of  nodes  in  a  cycle-free  p a t h.  Each  time  around 
the  while-loop,  each  definition  progresses  by  at  least  one  node  along  the  p a th 
in  question,  and  it  often  progresses  by  more  t h an  one  node,  depending  on  t he 
order  in  which  the  nodes  are  visited. 

In  fact,  if  we  properly  order  the  blocks  in  the  for-loop  of  line  (5),  there 
is  empirical  evidence  t h at  the  average  number  of  iterations  of  t he  while-loop 
is  under  5  (see  Section  9.6.7).  Since  sets  of  definitions  can  be  represented 
by  bit  vectors,  and  t he  operations  on  these  sets  can  be  implemented  by  logical 
operations  on  the  bit  vectors,  Algorithm  9.11  is  surprisingly  efficient  in  practice. 

E x a m p le  9 . 1 2:  We  shall  represent  the  seven  definitions  d\, d2,  •  •  •  ,d>j  in  t he 
flow  graph  of  Fig.  9.13  by  bit  vectors,  where  bit  i  from  t he  left  represents 
definition  d{.  T he  union  of  sets  is  computed  by  taking  the  logical  OR  of  t he 
corresponding  bit  vectors.  T he  difference  of  two  sets  S  —  T  is  computed  by 
complementing  the  bit  vector  of  T,  and  then  taking  t he  logical  AND  of  t h at 
complement,  with  the  bit  vector  for  S. 

Shown  in  t he  table  of  Fig.  9.15  are  the  values  taken  on  by  the  IN  and  OUT 
sets  in  Algorithm  9.11.  T he  initial  values,  indicated  by  a  superscript  0,  as 
in  OUTfS]0,  are  assigned,  by  t he  loop  of  line  (2)  of  Fig.  9.14.  They  are  each 
t he  empty  set,  represented  by  bit  vector  000  0000.  T he  values  of  subsequent 
passes  of  the  algorithm  are  also  indicated  by  superscripts,  and  labeled  IN  [I?]1 
and  OUTfS]1  for  the  first  pass  and  m[Bf  and  OUT[S]2  for  the  second. 

Suppose  the  for-loop  of  lines  (4)  through  (6)  is  executed  with  B  taking  on 

the  values 

B \,  B<i,  B3,  S 4,  E X IT 

in  t h at  order.  W i th  B  =  B1}  since  O U T [ E N T R Y]  = 0,  iNpBi]1  is  the  empty  set, 
and  OUTfPi]1  is  genBl.  This  value  differs  from  t he  previous  value  OUTpSi]0,  so 

608 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

Block  B  OUT[B]° 

INfi?]1 

O U T f B ]1 

W[B]2 

OVT[B]2 

B\ 

B2 
B3 
B4 
EXIT 

000  0000 
000  0000 
000  0000 
000  0000 
000  0000 

000  0000 
111  0000 
001  1100 
001  1110 
001  0111 

111  0000 
o oi  l i oo 
000  1110 
001  0111 
001  0111 

000  0000 
111  0111 
001  1110 
001  1110 
001  0111 

111  0000 
001  1110 
000  1110 
001  0111 
001  0111 

Figure  9.15:  Computation  of  IN  and  OUT 

we  now  know  there  is  a  change  on  the  first  round  (and  will  proceed  to  a  second 
round). 

Then  we  consider  B  =  B2  and  compute 

I N ^ ]1  =  O U T ^ i ]1  U  O U T [ 54]° 

=  111  0000  +  000  0000  =  111  0000 

O U T f f l a ]1  =  gen[B2]  U  ( i N ^ ]1  -  kill[B2]) 

=  000  1100  +  (111  0000  -  110  0001)  =  001  1100 

This  computation  is  summarized  in  Fig.  9.15.  For  instance,  at  t he  end  of t he 
first  pass,  O U T[ 5 2j1  =  001  1100,  reflecting  t he  fact  t h at  d4  and  d5  are  generated 
in  B2,  while  d3  reaches  the  beginning  of  B2  and  is  not  killed  in  B2. 

Notice  t h at  after  the  second  round,  O U T[ 52]  has  changed  to  reflect  the  fact 
t h at  d&  also  reaches  the  beginning  of  B2  and  is  not  killed  by  B2.  We  did  not 
learn  t h at  fact  on  the  first  pass,  because  the  p a th  from  d6  to  t he  end  of  B2, 
which  is  B3  -»  B4  ->  B2,  is  not  traversed  in  t h at  order  by  a  single  pass.  T h at  is, 
by  t he  time  we  learn  t h at  d$  reaches  t he  end  of  B4,  we  have  already  computed 
IN[Z?2]  and  O U T[ 52]  on  the  first  pass. 

There  are  no  changes  in  any  of  t he  OUT  sets  after  t he  second  pass.  T h u s, 
after  a  third  pass,  t he  algorithm  terminates,  with  the  IN's  and  OUT's  as  in  t he 
final  two  columns  of  Fig.  9.15. 

• 

9.2.5  Live-Variable  Analysis 

Some  code-improving  transformations  depend  on  information  computed  in  t he 
direction  opposite  to  t he  flow  of  control  in  a  program;  we  shall  examine  one 
such  example  now.  In  live-variable  analysis  we  wish  to  know  for  variable  x  and 
point  p  whether  the  value  of  x  at  p  could  be  used  along  some  p a th  in  t he  flow 
graph  starting  at  p.  If  so,  we  say  x  is  live  at  p;  otherwise,  x  is  dead  at  p. 

An  important  use  for  live-variable  information  is  register  allocation  for  basic 
blocks.  Aspects  of  this  issue  were  introduced  in  Sections  8.6  and  8.8.  After  a 
value  is  computed  in  a  register,  and  presumably  used  within  a  block,  it  is  not 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

609 

necessary  to  store  t h at  value  if  it  is  dead  at  the  end  of  the  block.  Also,  if  all 
registers  are  full  and  we  need  another  register,  we  should  favor  using  a  register 
with  a  dead  value,  since  t h at  value  does  not  have  to  be  stored. 

Here,  we  define  the  data-flow  equations  directly  in  terms  of  I N[ 5]  and 
OUTpB],  which  represent  the  set  of  variables  live  at  the  points  immediately 
before  and  after  block  B,  respectively.  These  equations  can  also  be  derived 
by  first  defining  t he  transfer  functions  of  individual  statements  and  composing 
t h em  to  create  the  transfer  function  of  a  basic  block.  Define 

1.  defB  as  the  set  of  variables  defined  (i.e.,  definitely  assigned  values)  in  B 

prior  to  any  use  of  t h at  variable  in  B,  and 

2.  useB  as  the  set  of  variables  whose  values  may  be  used  in  B  prior  to  any 

definition  of  the  variable. 

E x a m p le  9 . 1 3:  For  instance,  block  B2  in  Fig.  9.13  definitely  uses  i.  It  also 
uses  j  before  any  redefinition  of  j,  unless  it  is  possible  t h at  i  and  j  are  aliases 
of one  another.  Assuming  there  are  no  aliases  among  t he  variables  in  Fig.  9.13, 
then  uses2  =  {i,j}-  Also,  B2  clearly  defines  i  and  j.  Assuming  there  are  no 
aliases,  defB2  = 

as  well. 

• 

As  a  consequence  of t he  definitions,  any  variable  in  useB  must  be  considered 
live  on  entrance  to  block  B,  while  definitions  of  variables  in  defB  definitely 
are  dead  at  the  beginning  of  B. 
In  effect,  membership  in  defB  "kills"  any 
opportunity  for  a  variable  to  be  live  because  of  paths  t h at  begin  at  B. 

Thus,  the  equations  relating  def  and  use  to  the  unknowns  IN  and  OUT  are 

defined  as  follows: 

and  for  all  basic  blocks  B  other  t h an  E X IT 

IN [ E X I T]  =  0 

m[B]  =useBU 

(OTJTpB] 

-  defB) 

T he  first  equation  specifies  t he  boundary  condition,  which  is  t h at  no  variables 
are  live  on  exit  from  the  program.  The  second  equation  says  t h at  a  variable  is 
live  coming  into  a  block  if  either  it  is  used  before  redefinition  in  the  block  or 
it  is  live  coming  out  of  the  block  and  is  not  redefined  in  the  block.  The  third 
equation  says  t h at  a  variable  is  live  coming  out  of  a  block  if  and  only  if  it  is 
live  coming  into  one  of  its  successors. 

T he  relationship  between  the  equations  for  liveness  and  the  reaching-defin-

itions  equations  should  be  noticed: 

610 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

•  Both  sets  of  equations  have  union  as  t he  meet  operator.  T he  reason  is 
t h at  in  each  data-flow  schema  we  propagate  information  along  paths,  and 
we  care  only  about  whether  any  p a th  with  desired  properties  exist,  rather 
t h an  whether  something  is  true  along  all  paths. 

•  However,  information flow for  liveness  travels  "backward,"  opposite  to  the 
direction  of  control  flow,  because  in  this  problem  we  want  to  make  sure 
t h at  the  use  of  a  variable  x  at  a  point  p  is  transmitted  to  all  points  prior 
to  p  in  an  execution  p a t h,  so  t h at  we  may  know  at  the  prior  point  t h at  x 
will  have  its  value  used. 

To  solve  a  backward  problem,  instead  of  initializing  O U T [ E N T R Y],  we  ini 
tialize  IN  [EXIT].  Sets  IN  and  O UT  have  their  roles  interchanged,  and  use  and 
def  substitute  for  gen  and  kill,  respectively.  As  for  reaching  definitions,  the 
solution  to  the  liveness  equations  is  not  necessarily  unique,  and  we  want  the  so 
lution  with  the  smallest  sets  of  live  variables.  T he  algorithm  used  is  essentially 
a  backwards  version  of  Algorithm  9.11. 

A l g o r i t hm  9 . 1 4:  Live-variable  analysis. 

INPUT:  A  flow  graph  with  def and  use  computed  for  each  block. 

OUTPUT:  m[B]  and  O U T [ £ ],  the  set  of  variables  live  on  entry  and  exit  of  each 
block  B  of  the  flow  graph. 

METHOD:  Execute  t he  program  in  Fig.  9.16. 

• 

IN [ E X I T]  =  0; 
for  (each  basic  block  B  other  t h an  E X I T)  IN  [B]  = 0; 
w h i le  (changes  to  any  IN  occur) 

for  (each  basic  block  B  other  t h an  E X I T)  { 

O U T [ £] 
m[B]  =  useBU 

= 

Us  a  successor  of  B 

(bUTpB] 

-  defB); 

} 

Figure  9.16:  Iterative  algorithm  to  compute  live  variables 

9.2.6  Available  Expressions 

An  expression  x  +  y  is  available  at  a  point  p  if  every  p a th  from  the  entry  node 
to  p  evaluates  x  +  y,  and  after  t he  last  such  evaluation  prior  to  reaching  p, 
there  are  no  subsequent  assignments  to  x  or  y.5  For  t he  available-expressions 
data-flow  schema  we  say  t h at  a  block  kills  expression  x + y  if it  assigns  (or  m ay 

5N o te  that,  as  usual  in  this  chapter,  we  use  the  operator  +  as  a  generic  operator,  not 

necessarily  standing  for  addition. 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

611 

assign)  x  or  y  and  does  not  subsequently  recompute  x  +  y.  A  block  generates 
expression  x + y  if  it  definitely  evaluates  x + y  and  does  not  subsequently  define 
x  or  y. 

Note  t h at  t he  notion  of  "killing"  or  "generating"  an  available  expression  is 
not  exactly  t he  same  as  t h at  for  reaching  definitions.  Nevertheless,  these  notions 
of  "kill"  and  "generate"  behave  essentially  as  they  do  for  reaching  definitions. 
The  primary  use  of  available-expression  information  is  for  detecting  global 
common  subexpressions.  For  example,  in  Fig.  9.17(a),  the  expression  4  *  i  in 
block  Bs  will  be  a  common  subexpression  if  4 * i  is  available  at  t he  entry  point 
of  block  B3.  It  will  be  available  if  i  is  not  assigned  a  new  value  in  block  B2,  or 
if,  as  in  Fig.  9.17(b),  4  *  i  is  recomputed  after  i  is  assigned  in  B2. 

(a) 

(b) 

Figure  9.17:  Potential  common  subexpressions  across  blocks 

We  can  compute  t he  set  of  generated  expressions  for  each  point  in  a  block, 
working  from  beginning  to  end  of the  block.  At  the  point  prior  to  the  block,  no 
expressions  are  generated.  If  at  point  p  set  S  of  expressions  is  available,  and  q 
is  t he  point  after  p,  with  statement  x  =  y+z  between  t h e m,  t h en  we  form  t he 
set  of  expressions  available  at  q  by  the  following  two  steps. 

1.  Add  to  S  t he  expression  y  +  z. 

2.  Delete  from  S  any  expression  involving  variable  x. 

Note  the  steps  must  be  done  in  the  correct  order,  as  x  could  be  the  same  as 
y  or  z.  After  we  reach  the  end  of the  block,  S  is  the  set  of generated  expressions 
for  t he  block.  T he  set  of  killed  expressions  is  all  expressions,  say  y  +  z,  such 
t h at  either  y  or  z  is  defined  in  the  block,  and  y  +  z  is  not  generated  by  the 
block. 

E x a m p le  9 . 15  :  Consider  the  four  statements  of Fig.  9.18.  After  the  first,  b + c 
is  available.  After  the  second  statement,  a  —  d  becomes  available,  b ut  b  +  c  is 
no  longer  available,  because  b  has  been  redefined.  The  third  statement  does 
not  make  b  +  c  available  again,  because  the  value  of  c  is  immediately  changed. 

612 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

After  the  last  statement,  a  —  d  is  no  longer  available,  because  d  has  changed. 
Thus  no  expressions  are  generated,  and  all  expressions  involving  a,  b,  c,  or  d 
are  killed. 

• 

Statement 

Available  Expressions 
0 

a  =  b  +  c 

b  =  a  - d 

c  =  b  +  c 

d  =  a  - d 

{b  +  c} 

{a-d} 

{a-d} 

0 

Figure  9.18:  Computation  of  available  expressions 

We  can  find  available  expressions  in  a  manner  reminiscent  of t he  way  reach 
ing  definitions  are  computed.  Suppose  U  is  t he  "universal"  set  of all  expressions 
appearing  on  the  right  of one  or  more  statements  of the  program.  For  each  block 
B,  let IN[B]  be  t he  set  of  expressions  in  U  t h at  are  available  at  t he  point  just 
before  t he  beginning  of  B.  Let  OUT[B]  be  the  same  for  t he  point  following  t he 
end  of  B.  Define e.genB  to  be  the  expressions  generated  by  B  and  eJnills  to  be 
the  set  of expressions  in  U  killed  in  B.  Note  t h at  I N,  O U T,  e_#en,  and  eJkill  can 
all  be  represented  by  bit  vectors.  The  following  equations  relate  t he  unknowns 
IN  and  O UT  to  each  other  and  the  known  quantities  e_#en  and  eJkilh 

and  for  all  basic  blocks  B  other  t h an  E N T R Y, 

O U T [ E N T R Y]  =  0 

O U T[ E]  =  e-geriB  U 

( I N [ . B] 

-  eJeills) 

I N [ B ]= 

Pi 

, 

c 

O U T [ P ]. 

I 

' Pa  p r e d e c e s s or  of  B 

T he  above  equations  look  almost  identical  to  t he  equations  for  reaching 
definitions.  Like  reaching  definitions,  the  boundary  condition  is  O U T [ E N T R Y]  = 
0,  because  at  t he  exit  of  t he  E N T RY  node,  there  are  no  available  expressions. 
T he  most  important  difference  is  t h at  t he  meet  operator  is  intersection  rather 
t h an  union.  This  operator  is  t he  proper  one  because  an  expression  is  available 
at  t he  beginning  of a block  only  if it  is  available  at  t he  end  of  all its  predecessors. 
In  contrast,  a  definition  reaches  the  beginning  of  a  block  whenever  it  reaches 
the  end  of  any  one  or  more  of  its  predecessors. 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

613 

The  use  of  D  rather  t h an  U  makes  the  available-expression  equations  behave 
differently  from  those  of  reaching  definitions.  While  neither  set  has  a  unique 
solution,  for  reaching  definitions,  it  is  the  solution  with  the  smallest  sets  t h at 
corresponds  to  the  definition  of  "reaching,"  and  we  obtained  t h at  solution  by 
starting  with  t he  assumption  t h at  nothing  reached  anywhere,  and  building  up 
to  t he  solution.  In  t h at  way,  we  never  assumed  t h at  a  definition  d  could  reach 
a  point  p  unless  an  actual  p a th  propagating  d  to  p  could  be  found.  In  contrast, 
for  available  expression  equations  we  want  t he  solution  with  t he  largest  sets  of 
available  expressions,  so  we  start  with  an  approximation  t h at  is  too  large  and 
work  down. 

It  may  not  be  obvious  t h at  by  starting  with  the  assumption  "everything 
(i.e.,  the  set  U)  is  available  everywhere  except  at  the  end  of  the  entry  block" 
and  eliminating  only  those  expressions  for  which  we  can  discover  a  p a th  along 
which  it  is  not  available,  we  do  reach  a  set  of  truly  available  expressions.  In 
t he  case  of  available  expressions,  it  is  conservative  to  produce  a  subset  of  the 
exact  set  of  available  expressions.  The  argument  for  subsets  being  conservative 
is  t h at  our  intended  use  of  the  information  is  to  replace  the  computation  of  an 
available  expression  by  a  previously  computed  value.  Not  knowing  an  expres 
sion  is  available  only  inhibits  us  from  improving  the  code,  while  believing  an 
expression  is  available  when  it  is  not  could  cause  us  to  change  what  the  program 
computes. 

Figure  9.19:  Initializing  the  O UT  sets  to 0  is  too  restrictive. 

E x a m p le  9 . 1 6:  We  shall  concentrate  on  a  single  block,  B2  in  Fig.  9.19,  to 
illustrate  the  effect  of  the  initial  approximation  of  OUT[B2]  on  IN 
[ - 6 2 ]-  Let  G 
and  K  abbreviate e.genB2  and e-killB2,  respectively.  The  data-flow  equations 
for  block  B2  are 

m[B2] 

=  O U T [ £ I]  n  O U T [ B2] 

O U T [ £2]  =  G  U  (iNp32]  -  K) 

These  equations  may  be  rewritten  as  recurrences,  with  P  and  Oj  being  t he  jth 

614 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

approximations  of  I N [ S2]  and  O U T[ I ?2],  respectively: 

P+1  =  O U T [ S I] 

n  Oj 

Oj+1  =  GU  (P+1  -  K) 

Starting  with  0°  =  0,  we  get  I1  =  oUTpSi]  n  0°  =  0.  However,  if  we  start 

with  0°  =  U,  then  we  get  I1  =  O U T[ S i]  D  0°  =  OUTpBi],  as  we  should.  Intu 
itively,  the  solution  obtained  starting  with  0°  =  U  is  more  desirable,  because 
it  correctly  reflects  t he  fact  t h at  expressions  in  O U T [ JBI]  t h at  are  not  killed  by 
P>2  are  available  at  the  end  of J92. 

• 

A l g o r i t hm  9 . 1 7:  Available  expressions. 

INPUT:  A  flow  graph  with  e-kills  and  e.gens  computed  for  each  block  B.  T he 
initial  block  is  B\. 

OUTPUT:  I N[ 5]  and  O U T[ 5 ],  the  set  of  expressions  available  at  the  entry  and 
exit  of  each  block  B  of  the  flow  graph. 

METHOD:  Execute  the  algorithm  of  Fig.  9.20.  The  explanation  of the  steps  is 
similar  to  t h at  for  Fig.  9.14. 

• 

O U T [ E N T R Y]  =  0; 
for  (each  basic  block  B  other  t h an  E N T R Y)  O U T[ P]  =  U; 
w h i le  (changes  to  any  O UT  occur) 

for  (each  basic  block  B  other  t h an  E N T R Y)  { 

m[B)  = f]p 
O U T[ P]  =  e-gens  U  (iNpB]  -  e-killB); 

a  predecessor  of  B  O U T[ P ]; 

} 

Figure  9.20:  Iterative  algorithm  to  compute  available  expressions 

9.2.7 

Summary 

In  this  section,  we  have  discussed  three  instances  of  data-flow  problems:  reach 
ing  definitions,  live  variables,  and  available  expressions.  As  summarized  in 
Fig.  9.21,  t he  definition  of  each  problem  is  given  by  t he  domain  of  t he  data 
flow  values,  t he  direction  of  the  d a ta  flow,  t he  family  of  transfer  functions, 
the  boundary  condition,  and  t he  meet  operator.  We  denote  the  meet  operator 
generically  as  A. 

T he  last  row  shows  t he  initial  values  used  in  the  iterative  algorithm.  These 
values  are  chosen  so  t h at  t he  iterative  algorithm  will  find  t he  most  precise 
solution  to  the  equations.  This  choice  is  not  strictly  a  part  of  t he  definition  of 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

615 

the  data-flow  problem,  since  it  is  an  artifact  needed  for  the  iterative  algorithm. 
There  are  other  ways  of  solving  the  problem.  For  example,  we  saw  how  the 
transfer  function  of  a  basic  block  can  be  derived  by  composing  t he  transfer 
functions  of  t he  individual  statements  in  t he  block;  a  similar  compositional 
approach  may  be  used  to  compute  a  transfer  function  for  the  entire  procedure, 
or  transfer  functions  from  t he  entry  of t he  procedure  to  any  program  point.  We 
shall  discuss  such  an  approach  in  Section  9.7. 

Reaching  Definitions 

Live  Variables 

Available  Expressions 

Domain 

Sets  of  definitions 

Sets  of  variables 

Sets  of  expressions 

Direction 
Transfer 
function 

Boundary 

Forwards 

Backwards 

Forwards 

geriB  U  (x  —  kills) 

useB  U 

(x  —  defB) 

e-geriB  U  (x  —  eJciZ/s) 

O U T J E N T R Y]  =  0 

IN [EXIT]  =  0 

O U T J E N T R Y]  =  0 

Meet  (A) 

U 

u 

n 

Equations 

O U T [ B]  =  / B ( I N [ B ]) 

IN[B]  =  /F L( O U T [ B ]) 

O U T [ Bl  =  /B( I N [ B ]) 

IN[J3]  = 

O U T [ J B] 

= 

I N [ £]  = 

A p,P,E D (B)  O U T [ P] 

Initialize 

O U T [ £]  =  0 

IN[B]  = 0 

O U T [ B]  =  U 

Figure  9.21:  Summary  of  three  data-flow  problems 

9.2.8  Exercises  for  Section  9.2 

E x e r c i se  9 . 2 . 1:  For  t he  flow  graph  of  Fig.  9.10  (see  the  exercises  for  Sec 
tion  9.1),  compute 

a)  The  gen  and  kill  sets  for  each  block. 

b)  T he  IN  and  O UT  sets  for  each  block. 

E x e r c i se  9 . 2 . 2:  For  the flow graph  of Fig.  9.10,  compute  the  e_#en,  eJkill,  I N, 
a nd  O UT  sets  for  available  expressions. 

E x e r c i se  9 . 2 . 3:  For  t he flow graph  of Fig.  9.10,  compute  the  def,  use,  INJ  and 
O UT  sets  for live  variable  analysis. 

!  E x e r c i se  9 . 2 . 4:  Suppose  V  is  the  set  of  complex  numbers.  Which  of  the 
following  operations  can  serve  as  the  meet  operation  for  a  semilattice  on  V? 

a)  Addition:  (a  +  ib)  A  (c  +  id)  =  (a  +  b)  +  i(c  +  d). 

b)  Multiplication:  (a  +  ib)  A  (c  +  id)  =  (ac  —  bd)  +  i(ad  +  be). 

616 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

Why  the  Available-Expressions  Algorithm  Works 

We  need  to  explain  why  starting  all  O U T's  except  t h at  for  the  entry  block 
with  U,  the  set  of  all  expressions,  leads  to  a  conservative  solution  to  the 
data-flow  equations;  t h at  is,  all  expressions  found  to  be  available  really 
are  available.  First,  because  intersection  is  the  meet  operation  in  this 
data-flow  schema,  any  reason  t h at  an  expression  x  +  y  is  found  not  to  be 
available  at  a  point  will  propagate  forward  in  the  flow  graph,  along  all 
possible  paths,  until  x  +  y  is  recomputed  and  becomes  available  again. 
Second,  there  are  only  two  reasons  x  +  y  could  be  unavailable: 

1.  x  +  y  is  killed  in  block  B  because  x  or  y  is  defined  without  a  subse 
quent  computation  of  x + y.  In  this  case,  the  first  time  we  apply  t he 
transfer  function  fs,  x  +  y  will  be  removed  from  OVT[B}. 

2.  x  +  y  is  never  computed  along  some  p a t h.  Since  x  +  y  is  never  in 
O U T [ E N T R Y],  and  it  is  never  generated  along  the  p a th  in  question, 
we  can  show  by  induction  on  the  length  of  the  p a th  t h at  x  +  y  is 
eventually  removed  from  I N's  and  O U T's  along  t h at  path. 

Thus,  after  changes  subside,  t he  solution  provided  by  the  iterative  algo 
rithm  of  Fig.  9.20  will  include  only  truly  available  expressions. 

c)  Componentwise  minimum:  (a  +  ib)  A  (c  +  id)  =  min(«,  c)  +  i mm(b,  d). 

d)  Componentwise  maximum:  (a  +  ib)  A  (c  +  id)  —  max(a,  c)  +  imax(6,  of). 

!  E x e r c i se  9 . 2. 5:  We  claimed  t h at  if  a  block  B  consists  of  n  statements,  and 
the  ith.  statement  has  gen  and  kill  sets  gerii  and  kilk,  then  t he  transfer  function 
for  block  B  has  gen  and  kill  sets  gens  and  kills  given  by 

kills  —  kill\  U  killi  U  •  •  •  U  killn 

gens  =  genn  U  (genn-i  —  killn)  U  (genn-2  —  killn-i  —  killn)  U 

•  •  •  U  (geni  —  kilh  —  kills  —  •  •  •  —  killn). 

Prove  this  claim  by  induction  on  n. 

!  E x e r c i se  9 . 2 . 6:  Prove  by  induction  on  t he  number  of iterations  of t he  for-loop 
of  lines  (4)  through  (6)  of  Algorithm  9.11  t h at  none  of  the  I N's  or  O U T's  ever 
shrinks.  T h at  is,  once  a  definition  is  placed  in  one  of these  sets  on  some  round, 
it  never  disappears  on  a  subsequent  round. 

9.2. 

INTRODUCTION  TO  DATA-FLOW  ANALYSIS 

617 

!  E x e r c i se  9 . 2. 7:  Show  the  correctness  of  Algorithm  9.11.  T h at  is,  show  t h at 

a)  If  definition  d  is  put  in  IN  [B]  or  OUT[2?],  then  there  is  a  p a th  from  d  to 
t he  beginning  or  end  of  block  B,  respectively,  along  which  the  variable 
defined  by  d  might  not  be  redefined. 

b)  If  definition  d  is  not  put  in  w[B]  or  O U T [ . B],  then  there  is  no  p a th  from  d 
to  t he  beginning  or  end  of  block  B,  respectively,  along  which  t he  variable 
defined  by  d  might  not  be  redefined. 

!  E x e r c i se  9 . 2 . 8:  Prove  t he  following  about  Algorithm  9.14: 

a)  T he  I N's  and  OUT's  never  shrink. 

b)  If  variable  x  is  put  in  m[B]  or  0UTp9],  then  there  is  a  p a th  from  the 
beginning  or  end  of  block  B,  respectively,  along  which  x  might  be  used. 

c)  If  variable  x  is  not  put  in  IN[JB]  or  OUTp9],  then  there  is  no  p a th  from  the 
beginning  or  end  of  block  B,  respectively,  along  which  x  might  be  used. 

!  E x e r c i se  9 . 2 . 9:  Prove  the  following  about  Algorithm  9.17: 

a)  T he  I N's  and  OUT's  never  grow;  t h at  is,  successive  values  of these  sets  are 

subsets  (not  necessarily  proper)  of  their  previous  values. 

b)  If expression  e  is  removed  from  IN[B]  or  OUTpH],  then  there  is  a p a th  from 
t he  entry  of t he  flow  graph to  t he  beginning  or  end  of block  B,  respectively, 
along  which  e  is  either  never  computed,  or  after  its  last  computation,  one 
of  its  arguments  might  be  redefined. 

c)  If expression  e  remains  in  IN[B]  or  OUTpB],  then  along  every  p a th  from  the 
entry  of  the  flow  graph  to  the  beginning  or  end  of  block  B,  respectively, 
e  is  computed,  and  after  the  last  computation,  no  argument  of  e  could  be 
redefined. 

!  E x e r c i se  9 . 2 . 1 0:  T he  astute  reader will  notice  t h at  in  Algorithm  9.11  we  could 
have  saved  some  time  by  initializing  OUTpB]  to gens  for  all  blocks  B.  Likewise, 
in  Algorithm  9.14  we  could  have  initialized  m[B]  to gens-  We  did  not  do  so  for 
uniformity  in  the  treatment  of  the  subject,  as  we  shall  see  in  Algorithm  9.25. 
However,  is  it  possible  to  initialize  OUTpB]  to e^gens  in  Algorithm  9.17?  Why 
or  why  not? 

!  E x e r c i se  9 . 2 . 1 1:  Our  data-flow  analyses  so  far  do  not  take  advantage  of  the 
semantics  of  conditionals.  Suppose  we  find  at  t he  end  of  a  basic  block  a  test 
such  as 

if 

(x  <  10)  g o to 

. .. 

How  could  we  use  our  understanding  of  what  the  test  x  <  10  means  to  improve 
our  knowledge  of  reaching  definitions?  Remember,  "improve"  here  means  t h at 
we  eliminate  certain  reaching  definitions  t h at  really  cannot  ever  reach  a  certain 
program  point. 

618 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

9.3  Foundations  of  Data-Flow  Analysis 

Having  shown  several  useful  examples  of  the  data-flow  abstraction,  we  now 
study  the  family  of  data-flow  schemas  as  a  whole,  abstractly.  We  shall  answer 
several  basic  questions  about  data-flow  algorithms  formally: 

1.  Under  what  circumstances  is  the  iterative  algorithm  used  in  data-flow 

analysis  correct? 

2.  How  precise  is  t he  solution  obtained  by  the  iterative  algorithm? 

3.  Will  the  iterative  algorithm  converge? 

4.  W h at  is  the  meaning  of  the  solution  to  the  equations? 

In  Section  9.2,  we  addressed  each  of  the  questions  above  informally  when 
describing  t he  reaching-definitions  problem. 
Instead  of  answering  the  same 
questions  for  each  subsequent  problem  from  scratch,  we  relied  on  analogies 
with  the  problems  we  had  already  discussed  to  explain  t he  new  problems.  Here 
we  present  a  general  approach  t h at  answers  all  these  questions,  once  and  for 
all,  rigorously,  and  for  a  large  family  of  data-flow  problems.  We  first  iden 
tify  the  properties  desired  of  data-flow  schemas  and  prove  the  implications  of 
these  properties  on  the  correctness,  precision,  and  convergence  of the  data-flow 
algorithm,  as  well  as  the  meaning  of  t he  solution.  Thus,  to  understand  old 
algorithms  or  formulate  new  ones,  we  simply  show  t h at  t he  proposed  data-flow 
problem  definitions  have  certain  properties,  and  the  answers  to  all  the  above 
difficult  questions  are  available  immediately. 

The  concept  of  having  a  common  theoretical  framework  for  a  class  of  sche 
mas  also  has  practical  implications.  The  framework  helps  us  identify  the 
reusable  components  of  the  algorithm  in  our  software  design.  Not  only  is  cod 
ing  effort  reduced,  but  programming  errors  are  reduced  by  not  having  to  recode 
similar  details  several  times. 
A  data-flow  analysis 

consists  of 

framework 

(D,V,A:F) 

1.  A  direction  of the  d a ta  flow  D,  which  is  either  F O R W A R DS  or  B A C K W A R D S. 

2.  A  semilattice  (see  Section  9.3.1  for  t he  definition),  which  includes  a  do 

main  of  values  V  and  a  meet  operator  A. 

3.  A  family  F  of  transfer  functions  from  V  to  V.  This  family  must  include 
functions  suitable  for  t he  boundary  conditions,  which  are  constant  transfer 
functions  for  the  special  nodes  E N T RY  and  E X IT  in  any  flow  graph. 

9.3.1 

Semilattices 

A  semilattice  is  a  set  V  and  a  binary  meet  operator  A  such  t h at  for  all  x,  y, 
and  z  in  V: 

9.3. 

FOUNDATIONS  OF  DATA-FLOW  ANALYSIS 

619 

1  x  A  x  —  x  (meet  is  idempotent). 

2. 

3 

x  Ay  =  y  A  x  (meet  is  commutative). 

x  A  (y  A  z)  =  (x  A  y)  A  z  (meet  is  associative). 

A  semilattice  has  a  top  element,  denoted  T,  such  t h at 

for  all  x  in  V,  T  A x  —  x. 

Optionally,  a  semilattice  may  have  a  bottom  element,  denoted  ±,  such  t h at 

for  all  x  in  V,  _L A x  =  ±. 

P a r t i al  O r d e rs 

As  we  shall  see,  the  meet  operator  of  a  semilattice  defines  a  partial  order  on 
the  values  of the  domain.  A  relation  <  is  a  partial  order on  a  set  V  if for  all  x, 
y,  and  z  in  V: 

1.  x  <  x  (the  partial  order  is  reflexive). 

2.  If  x  <  y  and  y  <  x,  then  x  =  y  (the  partial  order  is  antisymmetric). 

3.  If  x  <  y  and  y  <  z,  then  x  <  z  (the  partial  order  is  transitive). 

T he  pair  (V,  <)  is  called  a  poset,  or  partially  ordered  set.  It  is  also  convenient 
to  have  a  <  relation  for  a  poset,  defined  as 

x  <  y  if  and  only  if  (x  <  y)  and  (x  /  y). 

T he  P a r t i al  O r d er  for  a  S e m i l a t t i ce 

It  is  useful  to  define  a  partial  order  <  for  a  semilattice  (V,  A).  For  all  x  and  y 
in  V,  we  define 

x  <  y  if  and  only  if  x  A  y  =  x. 

Because  the  meet  operator  A  is  idempotent,  commutative,  and  associative,  the 
<  order  as  defined  is  reflexive,  antisymmetric,  and  transitive.  To  see  why, 
observe  t h a t: 

•  Reflexivity:  for  all  x,  x  <  x.  The  proof  is  t h at  x  A  x  =  x  since  meet  is 

idempotent. 

•  Antisymmetry: 

In  proof,  x  <  y 
if  x  <  y  and  y  <  x,  then  x  —  y. 
means  x  Ay  =  x  and  y  <  x  means  y  A  x  =  y.  By  commutativity  of  A, 
x  =  (x  Ay)  =  (y  Ax)  =  y. 

620 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

•  Transitivity:  if  x  <  y  and  y  <  z,  then  x  <  z.  In  proof,  x  <  y  and  y  <  z 
means  t h at  x  A  y  =  x  and  y  A  z  -  y.  Then  (x  A  z)  =  ((x  A  y)  A  z)  = 
(x  A  (y  A  z))  =  (x  A  y)  =  x,  using  associativity  of  meet.  Since  x  A  z  =  x 
has  been  shown,  we  have  x  <  z,  proving  transitivity. 

E x a m p le  9 . 1 8:  The  meet  operators  used  in  the  examples  in  Section  9.2  are 
set  union  and  set  intersection.  They  are  both  idempotent,  commutative,  and 
associative.  For  set  union,  the  top  element  is 0  and  t he  b o t t om  element  is  U, 
the  universal  set,  since  for  any  subset  xo£U,$Ux  =  x  and  U  U  x  =  U.  For 
set  intersection,  T  is  U  and  ±  is 0.  V,  the  domain  of  values  of  the  semilattice, 
is  the  set  of  all  subsets  of  U,  which  is  sometimes  called  t he  power  set  of  U  and 
denoted  2U. 

For  all  x  and  yinV,xUy  =  x  implies  x  D  y; 

therefore,  the  partial  order 
imposed  by  set  union  is  D,  set  inclusion.  Correspondingly,  the  partial  order 
imposed  by  set  intersection  is  C,  set  containment.  T h at  is,  for  set  intersection, 
sets  with  fewer  elements  are  considered  to  be  smaller  in  the  partial  order.  How 
ever,  for  set  union,  sets  with  more  elements  are  considered  to  be  smaller  in  t he 
partial  order.  To  say  t h at  sets  larger  in  size  are  smaller  in  the  partial  order  is 
counterintuitive;  however,  this  situation  is  an  unavoidable  consequence  of  the 
definitions.6 

As  discussed  in  Section  9.2,  there  are  usually  many  solutions  to  a  set  of data 
flow  equations,  with  the  greatest  solution  (in  the  sense  of  t he  partial  order  <) 
being  the  most  precise.  For  example,  in  reaching  definitions,  t he  most  precise 
among  all  the  solutions  to  the  data-flow  equations  is  the  one  with  the  smallest 
number  of  definitions,  which  corresponds  to  t he  greatest  element  in  the  partial 
order  defined  by  the  meet  operation,  union.  In  available  expressions,  the  most 
precise  solution  is  t he  one  with  the  largest  number  of  expressions.  Again,  it 
is  the  greatest  solution  in  the  partial  order  defined  by  intersection  as  t he  meet 
operation. 

• 

G r e a t e st  L o w er  B o u n ds 

There  is  another  useful  relationship  between  the  meet  operation  and  the  partial 
ordering  it  imposes.  Suppose  (V,  A)  is  a  semilattice.  A  greatest  lower  bound  (or 
gib)  of  domain  elements  x  and  y  is  an  element  g  such  t h at 

1. 

g<x, 

2.  g  <  y,  and 

3.  If  z  is  any  element  such  t h at  z  <  x  and  z  <  y,  then  z  <  g. 

It  turns  out  t h at  the  meet  of x  and  y  is  their  only  greatest  lower  bound.  To  see 
why,  let  g  =  x  A  y.  Observe  t h a t: 

6  And  if  we  defined  the  partial  order  to  be  >  instead  of  <,  then  the  problem  would  surface 

when  the  meet  was  intersection,  although  not  for  union. 

9.3. 

FOUNDATIONS  OF  DATA-FLOW  ANALYSIS 

621 

Joins,  Lub's,  and  Lattices 

In  symmetry  to  t he  gib  operation  on  elements  of  a  poset,  we  may  define 
t he  least  upper  bound  (or  lub)  of  elements  x  and  y  to  be  t h at  element  b 
such  t h at  x  <b,  y  <b,  and  if  z  is  any  element  such  t h at  x  <  z  and  y  <  z, 
then  b  <  z.  One  can  show  t h at  there  is  at  most  one  such  element  b  if  it 
exists. 

In  a  true  lattice,  there  are  two  operations  on  domain  elements,  the 
meet  A,  which  we  have  seen,  and  the  operator  join,  denoted  V,  which 
gives  the  lub  of  two  elements  (which  therefore  must  always  exist  in  the 
lattice).  We  have  been  discussing  only  "semi"  lattices,  where  only  one 
of  t he  meet  and  join  operators  exist.  T h at  is,  our  semilattices  are  meet 
semilattices.  One  could  also  speak  of join  semilattices,  where  only  the join 
operator  exists,  and  in  fact  some  literature  on  program  analysis  does  use 
the  notation  of join  semilattices.  Since  the  traditional  data-flow  literature 
speaks  of  meet  semilattices,  we  shall  also  do  so  in  this  book. 

•  g  <  x  because  (x  A  y)  A  x  =  x  A  y.  The  proof  involves  simple  uses  of 

associativity,  commutativity,  and  idempotence.  T h at  is, 

g Ax  =  ((x A y) A x)  —  (x A (y A x))  = 

(x A (x A y))  =  ((x Ax) Ay)  = 

(x Ay)  = g 

•  9  <  y  by  a  similar  argument. 

•  Suppose  z  is  any  element  such  t h at  z  <  x  and  z  <  y.  We  claim  z  <  g, 
and  therefore,  z  cannot  be  a  gib  of  x  and  y  unless  it  is  also  g.  In  proof: 
(zAg)  =  (zA  (xAy))  —  ((zAx)  Ay).  Since  z  <  x,  we  know  (zAx)  =  z,  so 
(z Ag)  =  (z  Ay).  Since  z  <  y,  we  know  z Ay  =  z,  and  therefore  z Ag  —  z. 
We  have  proven  z  <  g  and  conclude  g  =  x  A  y  is  the  only  gib  of  x  and  y. 

L a t t i ce  D i a g r a ms 

It  often  helps  to  draw  the  domain  V  as  a  lattice  diagram,  which  is  a  graph  whose 
nodes  are  t he  elements  of  V,  and  whose  edges  are  directed  downward,  from  x 
to  y  if  y  <  x.  For  example,  Fig.  9.22  shows  t he  set  V  for  a  reaching-definitions 
data-flow  schema  where  there  are  three  definitions:  d±,  d2,  and  d%.  Since  <  is 
an  edge  is  directed  downward  from  any  subset  of these  three  definitions  to  each 
of  its  supersets.  Since  <  is  transitive,  we  conventionally  omit  t he  edge  from  x 

622 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

to  y  as  long  as  there  is  another  p a th  from  x  to  y  left  in  t he  diagram.  Thus, 
although  {di,d2,dz}  <  { d i },  we  do  not  draw  this  edge  since  it  is  represented 
by  the  p a th  through  {di,d2},  for  example. 

{} 

( T) 

Figure  9.22:  Lattice  of  subsets  of  definitions 

It  is  also  useful  to  note  t h at  we  can  read  t he  meet  off such  diagrams.  Since 
x  A  y  is  t he  gib,  it  is  always  the  highest  z  for  which  there  are  paths  downward 
to  z  from  both  x  and  y.  For  example,  if  x  is  {di}  and  y  is  { ^ 2 },  then  z  in 
Fig.  9.22  is  {G?I,G?2}5  which  makes  sense,  because  t he  meet  operator  is  union. 
The  top  element  will  appear  at  the  top  of  the  lattice  diagram;  t h at  is,  there  is 
a  p a th  downward  from  T  to  each  element.  Likewise,  the  b o t t om  element  will 
appear  at  the  bottom,  with  a  p a th  downward  from  every  element  to  _L. 

P r o d u ct  L a t t i c es 

While  Fig.  9.22  involves  only  three  definitions,  the  lattice  diagram  of  a  typical 
program  can  be  quite  large.  T he  set  of  data-flow  values  is  t he  power  set  of t he 
definitions,  which  therefore  contains  2n  elements  if  there  are  n  definitions  in 
the  program.  However,  whether  a  definition  reaches  a  program  is  independent 
of the  reachability  of the  other  definitions.  We  may  thus  express  the  l a t t i c e7  of 
definitions  in  terms  of a  "product  lattice,"  built  from  one  simple  lattice  for  each 
definition.  T h at  is,  if  there  were  only  one  definition  d  in  the  program,  then  t he 
lattice  would  have  two  elements:  {},  the  empty  set,  which  is  the  top  element, 
and  {d},  which  is  t he  b o t t om  element. 

Formally,  we  may  build  product  lattices  as  follows.  Suppose  (A, A A)  and 
(B,AB)  are  (semi)lattices.  The  product  lattice  for  these  two  lattices  is  defined 
as  follows: 

1.  The  domain  of  the  product  lattice  is  Ax  B. 

7In  this  discussion  and  subsequently,  we  shall  often  drop  the  "semi,"  since  lattices  like  the 

one  under  discussion  do  have  a join  or  lub  operator,  even  if we  do  not  make  use  of it. 

9.3.  FOUNDATIONS  OF  DATA-FLOW  ANALYSIS 

623 

2.  T he  meet  A  for  the  product  lattice  is  defined  as  follows. 
(a1,  b')  are  domain  elements  of  the  product  lattice,  then 

If  (a, b)  and 

(a,6)  A(a',b')  =  (aAa',bAb'). 

(9.19) 

It  is  simple  to  express  the  <  partial  order  for  the  product  lattice  in  terms 

of  the  partial  orders  <A  and  <B  for  A  and  B 

(a,  b)  <  (a\V)  if  and  only  if  a  <A  a1  and  b  <B  b'. 

(9.20) 

To  see  why  (9.20)  follows  from  (9.19),  observe  t h at 

(a, b) A (a', b') = (a A A a' ,b AB b'). 

So  we  might  ask  under  what  circumstances  does  (a AA a', bAB b')  =  (a, &)?  T h at 
happens  exactly  when  a  A  A  a'  —  a  and  b  AB  b'  —  b.  But  these  two  conditions 
are  t he  same  as  a  <A  OJ  and  b  <B  b'. 

T he  product  of  lattices  is  an  associative  operation,  so  one  can  show  t h at 
the  rules  (9.19)  and  (9.20)  extend  to  any  number  of  lattices.  T h at  is,  if  we  are 
given  lattices  (Ai,  Ai)  for  i  =  1,  2 , . ..  ,  k,  then  the  product  of  all  k  lattices,  in 
this  order,  has  domain  A\  x  A2  x  •  •  •  x  Ak,  a  meet  operator  defined  by 

( a i , a2 )-  •  • 

,ak)  A  (h,b2,... 

,bk)  =  (ax  Ai  h,a2  A2  b2,... 

,ak  Ak  h) 

and  a  partial  order  defined  by 

( o i, a2,...  , ak)  <  (bi, b2,...  , bk)  if  and  only  if  a«  <  bi  for  all  i. 

H e i g ht  of  a  S e m i l a t t i ce 

We  may  learn  something  about  t he  rate  of  convergence  of  a  data-flow  analysis 
algorithm  by  studying  the  "height"  of  the  associated  semilattice.  An  ascending 
chain  in  a  poset  (V,  <)  is  a  sequence  where  x\  <  x2  <  ...  <  xn.  T he  height 
of  a  semilattice  is  t he  largest  number  of  <  relations  in  any  ascending  chain; 
t h at  is,  the  height  is  one  less  t h an  the  number  of  elements  in  t he  chain.  For 
example,  the  height  of  the  reaching  definitions  semilattice  for  a  program  with 
n  definitions  is  n. 

Showing  convergence  of  an  iterative  data-flow  algorithm  is  much  easier  if the 
semilattice  has  finite  height.  Clearly,  a  lattice  consisting  of  a  finite  set  of values 
will  have  a  finite  height;  it  is  also  possible  for  a  lattice  with  an  infinite  number 
of  values  to  have  a  finite  height.  The  lattice  used  in  the  constant  propagation 
algorithm  is  one  such  example  t h at  we  shall  examine  closely  in  Section  9.4. 

9.3.2  Transfer  Functions 

The  family  of  transfer  functions  F  :  V  -»  V  in  a  data-flow  framework  has  t he 
following  properties: 

624 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

1.  F  has  an  identity  function  i",  such  t h at  I(x)  =  x  for  all  x  in  V. 

2.  F  is  closed  under  composition;  t h at  is,  for  any  two  functions  /  and  g  in 

F,  the  function  h  defined  by  h(x)  =  g(f(x)) 

is  in  F. 

E x a m p le  9 . 2 1:  In  reaching  definitions,  F  has  t he  identity,  the  function  where 
gen  and  kill  are  b o th  the  empty  set.  Closure  under  composition  was  actually 
shown  in  Section  9.2.4;  we  repeat  t he  argument  succinctly  here.  Suppose  we 
have  two  functions 

fi(x) 

=GiU(x-  K±) 

and 

f2(x) 

=  G2U{x~  K2). 

Then 

h(hix))  =  G2  U 

( ( Gi  U(x-  Ki)) 

-  K2). 

T he  right  side  of t he  above  is  algebraically  equivalent  to 

(G2  U 

(G1 

-  K2))  U(x- 

( #!  U  K2)). 

If  we  let  K  =  K\  U  K2  and  G  =  G2  U  (Gi  -  #2)5  then  we  have  shown  t h at 
the  composition  of  /i  and  f2,  which  is  f(x)  =  G  U  (x  —  K),  is  of  the  form 
t h at  makes  it  a  member  of  F. 
If  we  consider  available  expressions,  the  same 
arguments  used  for  reaching  definitions  also  show  t h at  F  has  an  identity  and  is 
closed  under  composition. 

• 

M o n o t o ne  F r a m e w o r ks 

To  make  an  iterative  algorithm  for  data-flow  analysis  work,  we  need  for  the 
data-flow  framework  to  satisfy  one  more  condition.  We  say  t h at  a  framework 
is  monotone  if  when  we  apply  any  transfer  function  /  in  F  to  two  members  of 
V,  the  first  being  no  greater  t h an  t he  second,  then  the  first  result  is  no  greater 
t h an  the  second  result. 

Formally,  a  data-flow  framework  (D,F,  V,  A)  is  monotone  if 

For  all  x  and  y  in  V  and  /  in  F,  x  <  y  implies  f(x)  <  f(y). 

(9.22) 

Equivalently,  monotonicity  can  be  defined  as 

For  all  x  and  y  in  V  and  /  in  F,  f{x  Ay)  <  f(x)  A  f(y). 

(9.23) 

Equation  (9.23)  says  t h at  if  we  take  t he  meet  of  two  values  and  then  apply  /, 
t he  result  is  never  greater  t h an  what  is  obtained  by  applying  /  to  t he  values 
individually  first  and  then  "meeting"  the  results.  Because  t he  two  definitions 
of  monotonicity  seem  so  different,  they  are  b o th  useful.  We  shall  find  one  or 
the  other  more  useful  under  different  circumstances.  Later,  we  sketch  a  proof 
to  show  t h at  they  are  indeed  equivalent. 

9.3. 

FOUNDATIONS  OF  DATA-FLOW  ANALYSIS 

625 

We  shall  first  assume  (9.22)  and  show  t h at  (9.23)  holds.  Since  x  A  y  is  the 

greatest  lower  bound  of  x  and  y,  we  know  t h at 

x  Ay  <  x  and  x  f\y  <y. 

Thus,  by  (9.22), 

f(x  A  y)  <  f(x)  and  f{x  Ay)  <  f{y). 

Since  f(x)  A  / ( y)  is  the  greatest  lower  bound  of  f(x)  and  f(y),  we  have  (9.23). 
Conversely,  let  us  assume  (9.23)  and  prove  (9.22).  We  suppose  x  <  y  and 
( 9 . 2 3)  tells 

use  (9.23)  to  conclude  f(x)  <  f(y),  thus  proving  (9.22).  Equation 
us 

f(xAy)<f(x)Af(y). 

But  since  x  <  y  is  assumed,  x  A  y  —  x,  by  definition.  Thus  (9.23)  says 

f(x) 

<f(x)Af(y). 

Since  f{x)Af(y)  is  the  gib  of  f(x)  and  f(y),  we  know  f(x)  A  f(y)  <  f(y).  Thus 

f(x)<f(x)Af(y)<f(y) 

and  (9.23)  implies  (9.22). 

D i s t r i b u t i ve  F r a m e w o r ks 

Often,  a  framework  obeys  a  condition  stronger  t h an  (9.23),  which  we  call  the 
distributivity 

condition, 

f(xAy) 

= 

f(x)Af(y) 

for  all  x  and  y  in  V  and  /  in  F.  Certainly,  if  a  =  b,  then  a A  b  =  a  by  idempot-
ence,  so  a  <  b.  Thus,  distributivity  implies  monotonicity,  although  the  converse 
is  not  true. 

E x a m p le  9 . 2 4:  Let  y  and  z  be  sets  of  definitions  in  the  reaching-definitions 
framework.  Let  /  be  a  function  defined  by  f(x)  =  G  U  (x  —  K)  for  some  sets 
of  definitions  G  and  K.  We  can  verify  t h at  the  reaching-definitions  framework 
satisfies  the  distributivity  condition,  by  checking  t h at 

G  U  ((y  U  z)  -  K)  =  (G  U  (y  -  K))  U  (G  U  (z  -  K)). 

While  the  equation  above  may  appear  formidable,  consider  first  those  definitions 
in  G.  These  definitions  are  surely  in  the  sets  defined  by  b o th  the  left  and  right 
sides.  Thus,  we  have  only  to  consider  definitions  t h at  are  not  in  G. 
In  t h at 
case,  we  can  eliminate  G  everywhere,  and  verify  the  equality 

(yUz)-K 

= 

(y-K)U(z-K). 

T he  latter  equality  is  easily  checked  using  a  Venn  diagram. 

• 

626 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

9.3.3  The  Iterative  Algorithm  for  General  Frameworks 

We  can  generalize  Algorithm  9.11  to  make  it  work  for  a  large  variety  of data-flow 
problems. 

A l g o r i t hm  9 . 2 5:  Iterative  solution  to  general  data-flow  frameworks. 

INPUT:  A  data-flow  framework  with  t he  following  components: 

1.  A  data-flow  graph,  with  specially  labeled  E N T RY  and  E X IT  nodes, 

2.  A  direction  of  the  data-flow  D, 

3.  A  set  of  values  V, 

4.  A  meet  operator  A, 

5.  A  set  of  functions  F,  where  fs  in  F  is  t he  transfer  function  for  block  B, 

and 

6.  A  constant  value  GENTRY  or  f  EXIT  in  V,  representing  t he  boundary  condition 

for  forward  and  backward  frameworks,  respectively. 

OUTPUT:  Values  in  V  for  IN[B]  and  O U T[ B]  for  each  block  B  in  the  data-flow 
graph. 

METHOD:  T he  algorithms  for  solving  forward  and  backward  data-flow  prob 
lems  are  shown  in  Fig.  9.23(a)  and  9.23(b),  respectively.  As  with  the  familiar 
iterative  data-flow  algorithms  from  Section  9.2,  we  compute  IN  and  O UT  for 
each  block  by  successive  approximation. 

• 

It  is  possible  to  write  t he  forward  and  backward  versions  of  Algorithm  9.25 
so  t h at  a  function  implementing  t he  meet  operation  is  a  parameter,  as  is  a 
function  t h at  implements  the  transfer  function  for  each  block.  T he  flow  graph 
itself  and  the  boundary  value  are  also  parameters. 
In  this  way,  the  compiler 
implementor  can  avoid  recoding  the  basic  iterative  algorithm  for  each  data-flow 
framework  used  by  the  optimization  phase  of  the  compiler. 

We  can  use  the  abstract  framework  discussed  so  far  to  prove  a  number  of 

useful  properties  of  t he  iterative  algorithm: 

1.  If  Algorithm  9.25  converges,  the  result  is  a  solution  to  t he  data-flow  equa 

tions. 

2.  If  t he  framework  is  monotone,  then  the  solution  found  is  the  maximum 

fixedpoint  (MFP)  of  the  data-flow  equations.  A  maximum  fixedpoint  is  a 
solution  with  t he  property  t h at  in  any  other  solution,  the  values  of  IN[B] 
and  O UT  [B]  are  <  the  corresponding  values  of  the  M F P. 

3.  If t he  semilattice  of t he  framework  is  monotone  and  of  finite  height,  then 

the  algorithm  is  guaranteed  to  converge. 

9.3. 

FOUNDATIONS  OF  DATA-FLOW  ANALYSIS 

627 

O U T [ E N T R Y]  =  GENTRY", 

1) 
2)  for  (each  basic  block  B  other  t h an  E N T R Y)  OUT[J5]  =  T; 
3)  w h i le  (changes  to  any  O UT  occur) 
4) 

for  (each  basic  block  B  other  t h an  E N T R Y)  { 

5) 

6) 

I N [ B]  =  AP  a  predecessor  of  B  OUT[P]\ 

O U T [ £]  = 

/B( I N [ B ] ); 

} 

(a)  Iterative  algorithm  for  a  forward  data-flow  problem. 

IN  [ E X I T]  =  VEX1T] 

1) 
2)  for  (each  basic  block  B  other  t h an  E X I T)  I N [ B]  =  T; 
3)  w h i le  (changes  to  any  IN  occur) 
4) 

for  (each  basic  block  B  other  t h an  E X I T)  { 

5) 
6) 

OVT[B]  =  As  a  successor  of  B  ™[S\m> 
I N [ B]  =  /B( O U T [ B ] ); 

} 

(b)  Iterative  algorithm  for  a  backward  data-flow  problem. 

Figure  9.23:  Forward  and  backward  versions  of  the  iterative  algorithm 

We  shall  argue  these  points  assuming  t h at  the  framework  is  forward.  T he 
case  of backwards  frameworks  is  essentially  the  same.  T he  first  property  is  easy 
to  show.  If the  equations  are  not  satisfied  by  the  time  t he  while-loop  ends,  then 
there  will  be  at  least  one  change  to  an  OUT  (in  the  forward  case)  or  IN  (in  the 
backward  case),  and  we  must  go  around  the  loop  again. 

To  prove  the  second  property,  we  first  show  t h at  the  values  taken  on  by  I N[ 5] 
and  OUT[P]  for  any  B  can  only  decrease  (in  the  sense  of  the  <  relationship  for 
lattices)  as  t he  algorithm  iterates.  This  claim  can  be  proven  by  induction. 

BASIS:  T he  base  case  is  to  show  t h at  the  value  of  IN[B]  and  OUT[B]  after  the 
first  iteration  is  not  greater  t h an  t he  initialized  value.  This  statement  is  trivial 
because  m[B]  and  OUT[P]  for  all  blocks  B  ^  E N T RY  are  initialized  with  T. 

INDUCTION:  Assume  t h at  after  t he  fcth  iteration,  t he  values  are  all  no  greater 
t h an  those  after  the  (k  —  l ) st  iteration,  and  show  the  same  for  iteration  k  +  1 
compared  with  iteration  k.  Line  (5)  of  Fig.  9.23(a)  has 

IN[J5]  = 

/\ 

O U T [ P ]. 

P  a  predecessor  of  B 

Let  us  use  t he  notation  I N [ S]*  and  OUT[P]*  to  denote  the  values  of  m[B]  and 
OUT[P]  after  iteration  i.  Assuming  OVT[P]k  <  O U T f P ] *- 1,  we  know  t h at 
w[B]k+1  <  w[B]k  because  of  the  properties  of  the  meet  operator.  Next,  line  (6) 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

628 

says 

O U T [ £]  =  /B( l N [ £ ] ). 

Since  m[B]k+1  <  m[B]k,  we  have  OUT[B]k+1  <  OVT[B]k  by  monotonicity. 

Note  t h at  every  change  observed  for  values  of IN[J3]  and  OUTpS]  is  necessary 
to  satisfy  the  equation.  T he  meet  operators  return  t he  greatest  lower  bound  of 
their  inputs,  and  the  transfer  functions  return  t he  only  solution  t h at  is  consis 
tent  with  the  block  itself  and  its  given  input.  Thus,  if  the  iterative  algorithm 
terminates,  the  result  must  have  values  t h at  are  at  least  as  great  as  the  corre 
sponding  values  in  any  other  solution;  t h at  is,  the  result  of  Algorithm  9.25  is 
the  M FP  of  the  equations. 

Finally,  consider  the  third  point,  where  t he  data-flow  framework  has  finite 
height.  Since  the  values  of every IN[B]  and  O U T [ £]  decrease  with  each  change, 
and  the  algorithm  stops  if  at  some  round  nothing  changes,  the  algorithm  is 
guaranteed  to  converge  after  a  number  of  rounds  no  greater  t h an  t he  product 
of  the  height  of  the  framework  and  the  number  of  nodes  of  the  flow  graph. 

9.3.4  Meaning  of a  Data-Flow  Solution 

We  now  know  t h at  t he  solution  found  using  the  iterative  algorithm  is  the  max 
imum  fixedpoint,  but  what  does  the  result  represent  from  a  program-semantics 
point  of view?  To  understand  the  solution  of a  data-flow  framework  (D,  F,  V,  A), 
let  us  first  describe  what  an  ideal  solution  to  t he  framework  would  be.  We  show 
t h at  the  ideal  cannot  be  obtained  in  general,  but  t h at  Algorithm  9.25  approxi 
mates  the  ideal  conservatively. 

T he  I d e al  S o l u t i on 

Without  loss  of generality,  we  shall  assume  for  now  t h at  the  data-flow  framework 
of  interest  is  a  forward-flowing  problem.  Consider  t he  entry  point  of  a  basic 
block  B.  The  ideal  solution  begins  by  finding  all  t he  possible  execution  p a t hs 
leading  from  the  program  entry  to  the  beginning  of  B.  A  p a th  is  "possible" 
only  if there  is  some  computation  of the  program  t h at  follows  exactly  t h at  p a t h. 
The  ideal  solution  would  then  compute  the  data-flow  value  at  t he  end  of  each 
possible  p a th  and  apply  t he  meet  operator  to  these  values  to  find  their  greatest 
lower  bound.  Then  no  execution  of  the  program  can  produce  a  smaller  value 
In  addition,  the  bound  is  tight;  there  is  no  greater 
for  t h at  program  point. 
data-flow  value  t h at  is  a  gib  for  the  value  computed  along  every  possible  p a th 
to  B  in  the  flow  graph. 

We  now  try  to  define  the  ideal  solution  more  formally.  For  each  block  B  in 

a  flow  graph,  let  fB  be  the  transfer  function  for  B.  Consider  any  p a th 

P  —  E N T RY  ->•  B\ 

->•  B2 

-»•  •  •  •  ->  Bk-l 

->•  Bk 

from  the  initial  node  E N T RY  to  some  block  Bk.  The  program  p a th  may  have 
cycles,  so  one  basic  block  may  appear  several  times  on  the  p a th  P.  Define  the 

9.3. 

FOUNDATIONS  OF  DATA-FLOW  ANALYSIS 

629 

/ p, 

to  be  the  composition  of  fBl  ,fB2--- 

transfer  function  for  P, 
t h at  / BH  is  not  p a rt  of  the  composition,  reflecting  the  fact  t h at  this  p a th  is 
taken  to  reach  the  beginning  of  block  Bk,  not  its  end.  T he  data-flow  value 
created  by  executing  this  p a th  is  thus  /P ( VEN T R Y),  where  GENTRY  is  the  result  of 
t he  constant  transfer  function  representing  the  initial  node  ENTRY.  T he  ideal 
result  for  block  B  is  thus 

>  / B « , _I  •  Note 

IDEAL 

[J5] 

= 

f\ 

fp(vENTKY). 

P,  a  possible  path  from  ENTRY  to  B 

We  claim  t h a t,  in  terms  of the  lattice-theoretic  partial  order  <  for  the  framework 
in  question, 

•  Any  answer  t h at  is  greater  t h an  IDEAL  is  incorrect. 

•  Any  value  smaller  t h an  or  equal  to  the  ideal  is  conservative,  i.e.,  safe. 

Intuitively,  t he  closer  t he  value  to  the  ideal  t he  more  precise  it  i s .8  To  see 
why  solutions  must  be  <  the  ideal  solution,  note  t h at  any  solution  greater  t h an 
IDEAL  for  any  block  could  be  obtained  by  ignoring  some  execution  p a th  t h at 
t he  program  could  take,  and  we  cannot  be  sure  t h at  there  is  not  some  effect 
along  t h at  p a th  to  invalidate  any  program  improvement  we  might  make  based 
on  t he  greater  solution.  Conversely,  any  solution  less  t h an  IDEAL  can  be  viewed 
as  including  certain  p a t hs  t h at  either  do  not  exist  in  the  flow  graph,  or  t h at 
exist  but  t h at  the  program  can  never  follow.  This  lesser  solution  will  allow  only 
transformations  t h at  are  correct  for  all  possible  executions  of  the  program,  b ut 
may  forbid  some  transformations  t h at  IDEAL  would  permit. 

T he  M e e t - O v e r - P a t hs  S o l u t i on 

However,  as  discussed  in  Section  9.1,  finding  all  possible  execution  paths  is 
undecidable.  We  must  therefore  approximate.  In  the  data-flow  abstraction,  we 
assume  t h at  every  p a th  in  the  flow  graph  can  be  taken.  Thus,  we  can  define 
t he  meet-over-paths  solution  for  B  to  be 

M O P[ E]  = 

f\ 

J P K N T R Y )-

P,  a  path  from  ENTRY  to  B 

Note  t h a t,  as  for  IDEAL,  the  solution  MOP[B]  gives  values  for  IN[B]  in  forward-
If  we  were  to  consider  backward-flow  frameworks,  then  we 
flow  frameworks. 
would  think  of  MOP [B]  as  a  value  for  OUT[B]. 

T he  p a t hs  considered  in  the  MOP  solution  are  a  superset  of  all  the  paths 
t h at  are  possibly  executed.  Thus,  the  MOP  solution  meets  together  not  only  the 
data-flow  values  of all  t he  executable  p a t h s,  but  also  additional  values  associated 

8N o te  that  in  forward  problems,  the  value  IDEAL[B]  is  what  we  would  like  m[B]  to  be.  In 
backward  problems,  which  we  do  not  discuss  here,  we  would  define  IDEAL[J5]  to  be  the  ideal 
value  of  OUT[B]. 

630 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

with  the  paths  t h at  cannot  possibly  be  executed.  Taking  t he  meet  of  the  ideal 
solution  plus  additional  terms  cannot  create  a  solution  larger  t h an  the  ideal. 
Thus,  for  all  B  we  have  MOP[B]  <  IDEAL[B],  and  we  will  simply  say  t h at 

M OP  <  I D E A L. 

T he  M a x i m um  F i x e d p o i nt  V e r s us  t he  M OP  S o l u t i on 

Notice  t h at  in  the  M OP  solution,  the  number  of  paths  considered  is  still  un 
bounded  if  t he  flow  graph  contains  cycles.  Thus,  t he  M OP  definition  does  not 
lend  itself  to  a  direct  algorithm.  T he  iterative  algorithm  certainly  does  not  first 
find  all  the  paths  leading  to  a  basic  block  before  applying  t he  meet  operator. 
Rather, 

1.  T he  iterative  algorithm  visits  basic  blocks,  not  necessarily  in  t he  order  of 

execution. 

2.  At  each  confluence  point, 

the  algorithm  applies  the  meet  operator  to 
the  data-flow  values  obtained  so  far.  Some  of  these  values  used  were 
introduced  artificially  in  the  initialization  process,  not  representing  t he 
result  of  any  execution  from  the  beginning  of  t he  program. 

So  what  is  the  relationship  between  the  M OP  solution  and  the  solution  M FP 
produced  by  Algorithm  9.25? 

We  first  discuss  t he  order  in  which  the  nodes  are  visited.  In  an  iteration,  we 
may  visit  a  basic  block  before  having  visited  its  predecessors.  If t he  predecessor 
is  t he  E N T RY  node,  O U T [ E N T R Y]  would  have  already  been  initialized  with  t he 
proper,  constant  value.  Otherwise,  it  has  been  initialized  to  T,  a  value  no 
smaller  t h an  the  final  answer.  By  monotonicity,  the  result  obtained  by  using  T 
as  input  is  no  smaller  t h an  t he  desired  solution.  In  a  sense,  we  can  think  of  T 
as  representing  no  information. 

ENTRY 

Figure  9.24:  Flow  graph  illustrating  the  effect  of  early  meet  over  paths 

W h at  is  t he  effect  of  applying  t he  meet  operator  early?  Consider  t he  simple 
example  of  Fig.  9.24,  and  suppose  we  are  interested  in  t he  value  of  lNp94].  By 

9.3. 

FOUNDATIONS  OF  DATA-FLOW  ANALYSIS 

631 

the definition of M OP 

M O P [ £4]  = 

(UB3

0 

/ BJ  A  UB3 

° 

/ B2) ) ( V E N T R Y) 

In  the  iterative  algorithm,  if  we  visit  the  nodes  in  the  order  Bi,B2,B3,B4,  then 

'ENTRY 

While  the  meet  operator  is  applied  at  the  end  in  the  definition  of  M O P,  the 
iterative  algorithm  applies  it  early.  T he  answer  is  the  same  only  if  the  data 
flow  framework  is  distributive. 
If  the  data-flow  framework  is  monotone  but 
not  distributive,  we  still  have  I N[ E4]  <  M O P ^ ].  Recall  t h at  in  general  a 
solution  IN[B]  is  safe  (conservative)  if  IN[J5]  <  I D E A L[ B]  for  all  blocks  B.  Surely, 

M O P [ £] 

< 

I D E AL  [B]. 

We  now  provide  a  quick  sketch  of why  in  general  the  M FP  solution  provided 
by  the  iterative  algorithm  is  always  safe.  An  easy  induction  on  i  shows  t h at 
t he  values  obtained  after  i  iterations  are  smaller  t h an  or  equal  to  the  meet  over 
all  paths  of  length  i  or  less.  But  the  iterative  algorithm  terminates  only  if  it 
arrives  at  the  same  answer  as  would  be  obtained  by  iterating  an  unbounded 
number  of  times.  Thus,  the  result  is  no  greater  t h an  the  M OP  solution.  Since 
M OP  <  I D E AL  and  M FP  <  M O P,  we  know  t h at  M FP  <  I D E A L,  and  therefore  the 
solution  M FP  provided  by  the  iterative  algorithm  is  safe. 

9.3.5  Exercises  for  Section  9.3 

E x e r c i se  9 . 3 . 1:  Construct  a  lattice  diagram  for  the  product  of  three  lattices, 
each  based  on  a  single  definition  di,  for  i  =  1,2,3.  How  is  your  lattice  diagram 
related  to  t h at  in  Fig.  9.22? 

E x e r c i se  9 . 3 . 2:  In  Section  9.3.3  we  argued  t h at  if  the  framework  has  finite 
height,  then  the  iterative  algorithm  converges.  Here  is  an  example  where  the 
framework  does  not  have  finite  height,  and  the  iterative  algorithm  does  not 
converge.  Let  the  set  of  values  V  be  the  nonnegative  real  numbers,  and  let  the 
meet  operator  be  the  minimum.  There  are  three  transfer  functions: 

i.  T he  identity,  fi(x)  =  x. 

ii. 

"half," 

t h at  is,  the  function  fn(x)  =  x/2. 

Hi.  "one." 

t h at  is,  the  function  fo(x)  =  1. 

T he  set  of  transfer  functions  F  is  these  three  plus  the  functions  formed  by 
composing  them  in  all  possible  ways. 

a)  Describe  the  set  F. 

b)  W h at  is  the  <  relationship  for  this  framework? 

 
632 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

c)  Give  an  example  of  a  flow  graph  with  assigned  transfer  functions,  such 

t h at  Algorithm  9.25  does  not  converge. 

d)  Is  this  framework  monotone?  Is  it  distributive? 

!  E x e r c i se  9 . 3 . 3:  We  argued  t h at  Algorithm  9.25  converges  if the  framework  is 
monotone  and  of  finite  height.  Here  is  an  example  of  a  framework  t h at  shows 
monotonicity  is  essential;  finite  height  is  not  enough.  The  domain  V  is  { 1 , 2 }, 
the  meet  operator  is  min,  and  the  set  of  functions  F  is  only  t he  identity  (/j) 
and  the  "switch"  function  (fs(x)  —  3  —  x)  t h at  swaps  1  and  2. 

a)  Show  t h at  this  framework  is  of  finite  height  but  not  monotone. 

b)  Give  an  example  of  a  flow  graph  and  assignment  of  transfer  functions  so 

t h at  Algorithm  9.25  does  not  converge. 

!  E x e r c i se  9 . 3 . 4:  Let  MOPi[B]  be  the  meet  over  all  p a t hs  of length  i  or  less  from 
the  entry  to  block  B.  Prove  t h at  after  i  iterations  of  Algorithm  9.25,  IN[B]  < 
MOPi[B].  Also,  show  t h at  as  a  consequence,  if  Algorithm  9.25  converges,  then 
it  converges  to  something  t h at  is  <  the  MOP  solution. 

!  E x e r c i se  9 . 3 . 5:  Suppose  the  set  F  of  functions  for  a  framework  are  all  of 
gen-kill  form.  T h at  is,  the  domain  V  is  the  power  set  of  some  set,  and  f(x)  = 
G  U  (x  —  K)  for  some  sets  G  and  K.  Prove  t h at  if  the  meet  operator  is  either 
(a)  union  or  (b)  intersection,  then  the  framework  is  distributive. 

9.4  Constant  Propagation 

All  the  data-flow  schemas  discussed  in  Section  9.2  are  actually  simple  examples 
of distributive  frameworks  with  finite  height.  Thus,  the  iterative  Algorithm  9.25 
applies  to  t h em  in  either  its  forward  or  backward  version  and  produces  t he  MOP 
solution  in  each  case.  In  this  section,  we  shall  examine  in  detail  a  useful  data 
flow  framework  with  more  interesting  properties. 

Recall  t h at  constant  propagation,  or  "constant  folding,"  replaces  expressions 

t h at  evaluate  to  the  same  constant  every  time  they  are  executed,  by  t h at  con 
stant.  T he  constant-propagation  framework  described  below  is  different  from 
all  the  data-flow  problems  discussed  so  far,  in  t h at 

a)  it  has  an  unbounded  set  of  possible  data-flow  values,  even  for  a  fixed  flow 

graph,  and 

b)  it  is  not  distributive. 

Constant  propagation  is  a  forward  data-flow  problem.  T he  semilattice  rep 
resenting  the  data-flow  values  and  the  family  of transfer  functions  are  presented 
next. 

9.4. 

CONSTANT  PROPAGATION 

633 

9.4.1  Data-Flow  Values  for  the  Constant-Propagation 

Framework 

T he  set  of  data-flow  values  is  a  product  lattice,  with  one  component  for  each 
variable  in  a  program.  T he  lattice  for  a  single  variable  consists  of t he  following: 

1.  All  constants  appropriate  for  the  type  of  the  variable. 

2.  T he  value  N A C,  which  stands  for  not-a-constant.  A  variable  is  mapped  to 
this  value  if  it  is  determined  not  to  have  a  constant  value.  T he  variable 
may  have  been  assigned  an  input  value,  or  derived  from  a  variable  t h at  is 
not  a  constant,  or  assigned  different  constants  along  different  paths  t h at 
lead  to  the  same  program  point. 

3.  The  value  U N D E F,  which  stands  for  undefined.  A  variable  is  assigned  this 
value  if  nothing  may  yet  be  asserted;  presumably,  no  definition  of  t he 
variable  has  been  discovered  to  reach  the  point  in  question. 

Note  t h at  N AC  and  U N D EF  are  not  the  same;  they  are  essentially  opposites. 
N AC  says  we  have  seen  so  many  ways  a  variable  could  be  defined  t h at  we  know 
it  is  not  constant;  U N D EF  says  we  have  seen  so  little  about  the  variable  t h at  we 
cannot  say  anything  at  all. 

T he  semilattice  for  a  typical  integer-valued  variable  is  shown  in  Fig.  9.25. 

Here  the  top  element  is  U N D E F,  and  the  b o t t om  element  is  N A C.  T h at  is,  the 
greatest  value  in  t he  partial  order  is  U N D EF  and  the  least  is  N A C.  T he  constant 
values  are  unordered,  but  they  are  all  less  t h an  U N D EF  and  greater  t h an  N A C. 
As  discussed  in  Section  9.3.1,  t he  meet  of  two  values  is  their  greatest  lower 
bound.  Thus,  for  all  values  v, 

U N D EF  A  v  =  v  and  N AC  A  v  =  N A C. 

For  any  constant  c, 

and  given  two  distinct  constants  c\  and  c2, 

c A  c  =  c 

d  A  c2  =  N A C. 

A  data-flow  value  for  this  framework  is  a  m ap  from  each  variable  in  the 
program  to  one  of the  values  in  the  constant  semilattice.  The  value  of a  variable 
v  in  a  m ap  m  is  denoted  by  m(v). 

9.4.2  The  Meet  for  the  Constant-Propagation  Framework 

T he  semilattice  of data-flow  values  is  simply  the  product  of the  semilattices  like 
Fig.  9.25,  one  for  each  variable.  Thus,  m  <  m'  if  and  only  if  for  all  variables  v 
we  have  m(v)  <  m'(v).  P ut  another  way,  mAm'  =  m"  if  m"(v)  =  m(v)Am'(v) 
for  all  variables  v. 

634 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

UNDEF 

•3  -2 

-1 

0 

1 

2 

3 

NAC 

Figure  9.25:  Semilattice  representing  the  possible  "values"  of  a  single  integer 
variable 

9.4.3  Transfer  Functions  for  the  Constant-Propagation 

Framework 

We  assume  in  the  following  t h at  a  basic  block  contains  only  one  statement. 
Transfer  functions  for  basic  blocks  containing  several  statements  can  be  con 
structed  by  composing  the  functions  corresponding  to  individual  statements. 
T he  set  F  consists  of  certain  transfer  functions  t h at  accept  a  m ap  of  variables 
to  values  in  the  constant  lattice  and  return  another  such  m a p. 

F  contains  the  identity  function,  which  takes  a  m ap  as  input  and  returns 
the  same  m ap  as  output.  F  also  contains  the  constant  transfer  function  for 
the  E N T RY  node.  This  transfer  function,  given  any  input  m a p,  returns  a  m ap 
mo,  where  mo(v)  =  U N D E F,  for  all  variables  v.  This  boundary  condition  makes 
sense,  because  before  executing  any  program  statements  there  are  no  definitions 
for  any  variables. 

In  general,  let  fs  be  t he  transfer  function  of  statement  s,  and  let  m  and  m' 
represent  data-flow  values  such  t h at  m'  =  f(m).  We  shall  describe  /s  in  terms 
of  the  relationship  between  m  and  m '. 

1.  If  s  is  not  an  assignment  statement,  then  fs  is  simply  t he  identity  function. 

2.  If  s  is  an  assignment  to  variable  x,  then  m'(v)  =  m(v),  for  all  variables 

v  ^  x,  provided  one  of  the  following  conditions  holds: 

(a)  If  the  right-hand-side  (RHS)  of the  statement  s  is  a  constant  c,  then 

m'(x)  =  c. 

(b)  If  the  RHS  is  of  the  form  y  +  z,  t h e n9 

m(y)  +  m(z) 

N AC 

U N D EF 

if  m(y)  and  m(z)  are  constant  values 
if either  m(y)  or  m(z)  is  N AC 
otherwise 

(c)  If t he  RHS  is  any  other  expression  (e.g.  a  function  call  or  assignment 

through  a  pointer),  then  m'(x)  =  N A C. 

9As  usual,  +  represents  a  generic  operator,  not  necessarily  addition. 

9.4. 

CONSTANT  PROPAGATION 

635 

9.4.4  Monotonicity  of  the  Constant-Propagation 

Framework 

Let  us  show  t h at  the  constant  propagation  framework  is  monotone.  First,  we 
can  consider  the  effect  of  a  function  fs  on  a  single  variable.  In  all  but  case  2(b), 
f8  either  does  not  change  the  value  of  m(x),  or  it  changes  the  m ap  to  return  a 
constant  or  N A C.  In  these  cases,  /s  must  surely  be  monotone. 

For  case  2(b),  the  effect  of  fs  is  tabulated  in  Fig  9.26.  T he  first  and  second 
columns  represent  t he  possible  input  values  of  y  and  z\  the  last  represents  t he 
output  value  of  x.  T he  values  are  ordered  from  t he  greatest  to  t he  smallest  in 
each  column  or  sub  column.  To  show  t h at  the  function  is  monotone,  we  check 
t h at  for  each  possible  input  value  of  y,  the  value  of  x  does  not  get  bigger  as  the 
value  of  z  gets  smaller.  For  example,  in  the  case  where  y  has  a  constant  value 
ci,  as  t he  value  of  z  varies  from  U N D EF  to  c2  to  N A C,  the  value  of  x  varies  from 
U N D E F,  to  ci  + c2,  and  then  to  N A C,  respectively.  We  can  repeat  this  procedure 
for  all  t he  possible  values  of  y.  Because  of  symmetry,  we  do  not  even  need  to 
repeat  the  procedure  for  the  second  operand  before  we  conclude  t h at  the  output 
value  cannot  get  larger  as  the  input  gets  smaller. 

m(y) 

m(z) 

m'(x) 

U N D EF 

U N D EF 

U N D EF 

Cl 

N AC 

C2 
N AC 

U N D EF 

C2 
N AC 

U N D EF 

C2 
N AC 

U N D EF 

N AC 

U N D EF 
Cl  +  c2 

N AC 

N AC 

N AC 

N AC 

Figure  9.26:  The  constant-propagation  transfer  function  for  x  =  y+z 

9.4.5  Nondistributivity  of  the  Constant-Propagation 

Framework 

The  constant-propagation  framework  as  defined  is  monotone  but  not  distribu 
tive.  T h at  is,  t he  iterative  solution  M FP  is  safe  b ut  may  be  smaller  t h an  t he 
MOP  solution.  An  example  will  prove  t h at  the  framework  is  not  distributive. 

E x a m p le  9 . 2 6:  In  t he  program  in  Fig.  9.27,  x  and  y  are  set  to  2  and  3  in  block 
Bi,  and  to  3  and  2,  respectively,  in  block  B2.  We  know  t h at  regardless  of which 
p a th  is  taken,  the  value  of z  at  the  end  of block  B3  is  5.  The  iterative  algorithm 
does  not  discover  this  fact,  however.  Rather,  it  applies  the  meet  operator  at 
t he  entry  of  B3,  getting  N A C 'S  as  the  values  of  x  and  y.  Since  adding  two  N A C's 

636 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

z  =  x+y 

EXIT 

Figure  9.27:  An  example  demonstrating  t h at  the  constant  propagation  frame 
work  is  not  distributive 

yields  a  NAC,  the  output  produced  by  Algorithm  9.25  is  t h at  z  —  NAC  at  the  exit 
of  the  program.  This  result  is  safe,  but  imprecise.  Algorithm  9.25  is  imprecise 
because  it  does  not  keep  track  of  the  correlation  t h at  whenever  x  is  2,  y  is  3, 
and  vice  versa.  It  is  possible,  b ut  significantly  more  expensive,  to  use  a  more 
complex  framework  t h at  tracks  all  the  possible  equalities  t h at  hold  among  pairs 
of expressions  involving  the  variables  in  the  program;  this  approach  is  discussed 
in  Exercise  9.4.2. 

Theoretically,  we  can  a t t r i b u te  this  loss  of  precision  to  t he  nondistributivity 
of  the  constant  propagation  framework.  Let  / i, 
f2,  and  fa  be  the  transfer 
functions  representing  blocks  B\,  B2  and  B3,  respectively.  As  shown  in  Fig  9.28, 

h(fi(mo)  A  /2O0))  <  h{h{mo))  A  /3( / 2 ( m0)) 

rendering  the  framework  nondistributive. 

• 

m 
m0 
h(m0) 
/2O0) 
/ i ( m0)  A /2( m0) 
hUi{m0)  A /2( m0)) 
h{himo)) 
/ s( / 2( m0)) 
/ s ( / i N ) A/ 3 ( / 2( m o )) 

m(z) 

m(y) 
m(x) 
UNDEF  UNDEF  UNDEF 
3 
UNDEF 
2 
UNDEF 
UNDEF 
NAC 
NAC 
NAC 
5 
3 
5 
2 
5 
NAC 

2 
3 
NAC 
NAC 
2 
3 
NAC 

Figure  9.28:  Example  of  nondistributive  transfer  functions 

9.4. 

CONSTANT  PROPAGATION 

637 

9.4.6 

Interpretation  of  the  Results 

T he  value  U N D EF  is  used  in  the  iterative  algorithm  for  two  purposes:  to  initialize 
t he  E N T RY  node  and  to  initialize  the  interior  points  of  t he  program  before  the 
iterations.  T he  meaning  is  slightly  different  in  the  two  cases.  The  first  says  t h at 
variables  are  undefined  at  the  beginning  of  t he  program  execution;  t he  second 
says  t h at  for  lack  of  information  at  the  beginning  of  the  iterative  process,  we 
approximate  the  solution  with  the  top  element  U N D E F.  At  t he  end  of  t he 
iterative  process,  the  variables  at  the  exit  of  t he  E N T RY  node  will  still  hold  the 
U N D EF  value,  since  O U T [ E N T R Y]  never  changes. 

It  is  possible  t h at  U N D E F 'S  may  show  up  at  some  other  program  points. 
W h en  they  do,  it  means  t h at  no  definitions  have  been  observed  for  t h at  variable 
along  any  of  t he  paths  leading  up  to  t h at  program  point.  Notice  t h at  with  t he 
way  we  define  the  meet  operator,  as  long  as  there  exists  a  p a th  t h at  defines  a 
variable  reaching  a  program  point,  t he  variable  will  not  have  an  U N D EF  value. 
If  all  the  definitions  reaching  a  program  point  have  the  same  constant  value, 
t he  variable  is  considered  a  constant  even  though  it  may  not  be  defined  along 
some  program  p a t h. 

By  assuming  t h at  the  program  is  correct,  the  algorithm  can  find  more  con 

stants  t h an  it  otherwise  would.  T h at  is,  the  algorithm  conveniently  chooses 
some  values  for  those  possibly  undefined  variables  in  order  to  make  t he  pro 
gram  more  efficient.  This  change  is  legal  in  most  programming  languages,  since 
undefined  variables  are  allowed  to  take  on  any  value.  If t he  language  semantics 
requires  t h at  all  undefined  variables  be  given  some  specific  value,  then  we  must 
change  our  problem  formulation  accordingly.  And  if instead  we  are  interested  in 
finding  possibly  undefined  variables  in  a  program,  we  can  formulate  a  different 
data-flow  analysis  to  provide  t h at  result  (see  Exercise  9.4.1). 

E x a m p le  9 . 2 7:  In  Fig.  9.29,  the  values  of  x  are  10  and  U N D EF  at  the  exit  of 
basic  blocks  B2  and  B$,  respectively.  Since  U N D EF  A  10  =  10,  the  value  of  x  is 
10  on  entry  to  block  B4.  Thus,  block  B5,  where  x  is  used,  can  be  optimized 
by  replacing  x  by  10.  Had  the  p a th  executed  been  B\  -»  Bs  ->  B4  -»  B5,  the 
value  of  x  reaching  basic  block  B5  would  have  been  undefined.  So,  it  appears 
incorrect  to  replace  the  use  of  x  by  10. 

However,  if  it  is  impossible  for  predicate  Q  to  be  false  while  Q'  is  true, 
then  this  execution  p a th  never  occurs.  While  the  programmer  may  be  aware 
of  t h at  fact,  it  may  well  be  beyond  the  capability  of  any  data-flow  analysis  to 
determine.  Thus,  if  we  assume  t h at  t he  program  is  correct  and  t h at  all  t he 
variables  are  defined  before  they  are  used,  it  is  indeed  correct  t h at  the  value 
of  x  at  the  beginning  of  basic  block  B5  can  only  be  10.  And  if  t he  program 
is  incorrect  to  begin  with,  then  choosing  10  as  the  value  of  x  cannot  be  worse 
t h an  allowing  x  to  assume  some  random  value. 

• 

9.4.7  Exercises  for  Section  9.4 

!  E x e r c i se  9. 4. 1:  Suppose  we  wish  to  detect  all  possibility  of  a  variable  being 

638 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

uninitialized  along  any  p a th  to  a  point  where  it  is  used.  How  would  you  modify 
t he  framework  of  this  section  to  detect  such  situations? 

!!  E x e r c i se  9 . 4 . 2:  An  interesting  and  powerful  data-flow-analysis  framework  is 
obtained  by  imagining  the  domain  V  to  be  all  possible  partitions  of expressions, 
so  t h at  two  expressions  are  in  the  same  class  if  and  only  if  they  are  certain  to 
have  the  same  value  along  any  p a th  to  the  point  in  question.  To  avoid  having 
to  list  an  infinity  of expressions,  we  can  represent  V  by  listing  only  the  minimal 
pairs  of  equivalent  expressions.  For  example,  if  we  execute  the  statements 

a  =  b 
c  =  a  +  d 

then  the  minimal  set  of  equivalences  is  {a  =  6, c  =  a  +  d}.  From  these  follow 
other  equivalences,  such  as  c  =  b +  d  and  a +  e  =  b  +  e,  but  there  is  no  need  to 
list  these  explicitly. 

a)  W h at  is  the  appropriate  meet  operator  for  this  framework? 

b)  Give  a  d a ta  structure  to  represent  domain  values  and  an  algorithm  to 

implement  the  meet  operator. 

c)  W h at  are  the  appropriate  functions  to  associate  with  statements?  Explain 
the  effect  t h at  a  statement  such  as  a  =  b+c  should  have  on  a  partition  of 
expressions  (i.e.,  on  a  value  in  V). 

d)  Is  this  framework  monotone?  Distributive? 

9.5. 

PARTIAL-REDUNDANCY 

ELIMINATION 

639 

9.5  Partial-Redundancy  Elimination 

In  this  section,  we  consider  in  detail  how  to  minimize  the  number  of  expression 
evaluations.  T h at  is,  we  want  to  consider  all  possible  execution  sequences  in 
a  flow  graph,  and  look  at  t he  number  of  times  an  expression  such  as  x  +  y  is 
evaluated.  By  moving  around  the  places  where  x  +  y  is  evaluated  and  keeping 
t he  result  in  a  temporary  variable  when  necessary,  we  often  can  reduce  the 
number  of  evaluations  of  this  expression  along  many  of  the  execution  paths, 
while  not  increasing  t h at  number  along  any  p a t h.  Note  t h at  the  number  of 
different  places  in  the  flow  graph  where  x  +  y  is  evaluated  may  increase,  but 
t h at  is  relatively  unimportant,  as  long  as  the  number  of  evaluations  of  t he 
expression  x  +  y  is  reduced. 

Applying  the  code  transformation  developed  here  improves  the  performance 
of the  resulting  code,  since,  as  we  shall  see,  an  operation  is  never  applied  unless 
it  absolutely  has  to  be.  Every  optimizing  compiler  implements  something  like 
the  transformation  described  here,  even  if  it  uses  a  less  "aggressive"  algorithm 
t h an  the  one  of this  section.  However,  there  is  another  motivation  for  discussing 
t he  problem.  Finding  the  right  place  or  places  in  the  flow  graph  at  which 
to  evaluate  each  expression  requires  four  different  kinds  of  data-flow  analyses. 
Thus,  the  study  of  "partial-redundancy  elimination,"  as  minimizing  t he  number 
of  expression  evaluations  is  called,  will  enhance  our  understanding  of  the  role 
data-flow  analysis  plays  in  a  compiler. 

Redundancy  in  programs  exists  in  several  forms.  As  discussed  in  Section 
9.1.4,  it  may  exist  in  the  form  of  common  subexpressions,  where  several  evalua 
tions  of t he  expression  produce  t he  same  value.  It  may  also  exist  in  the  form  of 
a  loop-invariant  expression  t h at  evaluates  to  the  same  value  in  every  iteration 
of  the  loop.  Redundancy  may  also  be  partial,  if  it  is  found  along  some  of  the 
paths,  but  not  necessarily  along  all  paths.  Common  subexpressions  and  loop-
invariant  expressions  can  be  viewed  as  special  cases  of partial  redundancy;  thus 
a  single  partial-redundancy-elimination  algorithm  can  be  devised  to  eliminate 
all  the  various  forms  of  redundancy. 

In  the  following,  we  first  discuss  the  different  forms  of  redundancy,  in  order 
to  build  up  our  intuition  about  the  problem.  We  then  describe  the  generalized 
redundancy-elimination  problem,  and  finally  we  present  the  algorithm.  This 
algorithm  is  particularly  interesting,  because  it  involves  solving  multiple  data 
flow  problems,  in  b o th  the  forward  and  backward  directions. 

9.5.1  The  Sources  of  Redundancy 

Fi  gure  9.30  illustrates  the  three  forms  of  redundancy:  common  subexpressions, 
loop-invariant  expressions,  and  partially  redundant  expressions.  The  figure 
shows  the  code  both  before  and  after  each  optimization. 

640 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

(a) 

(b) 

Figure  9.30:  Examples  of  (a)  global  common  subexpression,  (b)  loop-invariant 
code  motion,  (c)  partial-redundancy  elimination. 

G l o b al  C o m m on  S u b e x p r e s s i o ns 

In  Fig.  9.30(a),  t he  expression  b  + c  computed  in  block  B4  is  redundant;  it  has 
already  been  evaluated  by  the  time  the  flow  of  control  reaches  B4  regardless  of 
the  p a th  tsEken  to  get  there.  As  we  observe  in  this  example,  the  value  of  t he 
expression  may  be  different  on  different  paths.  We  can  optimize  the  code  by 
storing  t he  result  of  t he  computations  of  b +  c in  blocks  B2  and  B3  in  t he  same 
temporary  variable,  say  t,  and  then  assigning  the  value  of  t  to  the  variable  e  in 
block  B4,  instead  of reevaluating  the  expression.  Had  there  been  an  assignment 
to  either  b  or  c  after  the  last  computation  of  6  +  c  but  before  block  B4,  the 
expression  in  block  B4  would  not  be  redundant. 

Formally,  we  say  t h at  an  expression  b  +  c  is  (fully)  redundant  at  point  p,  if 
it  is  an  available  expression,  in  t he  sense  of  Section  9.2.6,  at  t h at  point.  T h at 
is,  the  expression  b  +  c  has  been  computed  along  all  paths  reaching  p,  and  the 
variables  b  and  c  were  not  redefined  after  t he  last  expression  was  evaluated. 
T he  latter  condition  is  necessary,  because  even  though  the  expression  b  +  c  is 
textually  executed  before  reaching  the  point  p,  the  value  of  b  +  c  computed  at 

9.5. 

PARTIAL-REDUNDANCY 

ELIMINATION 

641 

Finding  "Deep"  Common  Subexpressions 

Using  available-expressions  analysis  to  identify  redundant  expressions  only 
works  for  expressions  t h at  are  textually  identical.  For  example,  an  appli 
cation  of  common-subexpression  elimination  will  recognize  t h at  tl  in  the 
code  fragment 

tl  =  b  +  c;  a  =  tl  +  d; 

has  t he  same  value  as  does  t2  in 

t2  =  b  +  c;  e  =  t2  +  d; 

as  long  as  t he  variables  b  and  c  have  not  been  redefined  in  between. 
It 
does  not,  however,  recognize  t h at  a  and  e  are  also  the  same.  It  is  possi 
ble  to  find  such  "deep"  common  subexpressions  by  re-applying  common 
subexpression  elimination  until  no  new  common  subexpressions  are  found 
on  one  round.  It  is  also  possible  to  use  t he  framework  of Exercise  9.4.2  to 
catch  deep  common  subexpressions. 

point  p  would  have  been  different,  because  the  operands  might  have  changed. 

L o o p - I n v a r i a nt  E x p r e s s i o ns 

Fig.  9.30(b)  shows  an  example  of  a  loop-invariant  expression.  T he  expression 
b  +  c  is  loop  invariant  assuming  neither  t he  variable  b  nor  c  is  redefined  within 
t he  loop.  We  can  optimize  the  program  by  replacing  all  t he  re-executions  in 
a  loop  by  a  single  calculation  outside  the  loop.  We  assign  the  computation  to 
a  t e m p o r a ry  variable,  say  t,  and  then  replace  t he  expression  in  t he  loop  by  t. 
There  is  one  more  point  we  need  to  consider  when  performing  "code  motion" 
optimizations  such  as  this.  We  should  not  execute  any  instruction  t h at  would 
not  have  executed  without  the  optimization.  For  example,  if  it  is  possible  to 
exit  t he  loop  without  executing  t he  loop-invariant  instruction  at  all,  then  we 
should  not  move  the  instruction  out  of  the  loop.  There  are  two  reasons. 

1.  If  the  instruction  raises  an  exception,  then  executing  it  may  throw  an 

exception  t h at  would  not  have  happened  in  the  original  program. 

2.  When  the  loop  exits  early,  t he  "optimized"  program  takes  more  time  t h an 

t he  original  program. 

To  ensure  t h at  loop-invariant  expressions  in  while-loops  can  be  optimized, 

compilers  typically  represent  the  statement 

642 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

while  c  { 

S; 

} 

in  the  same  way  as  the  statement 

if  c  { 

repeat 

S; 

until not  c; 

} 

In  this  way,  loop-invariant  expressions  can  be  placed  just  prior  to  the  repeat-
until  construct. 

Unlike  common-subexpression  elimination,  where  a  redundant  expression 
computation  is  simply  dropped,  loop-invariant-expression  elimination  requires 
an  expression  from  inside  t he  loop  to  move  outside  t he  loop.  Thus,  this  opti 
mization  is  generally  known  as  "loop-invariant  code  motion."  Loop-invariant 
code  motion  may  need  to  be  repeated,  because  once  a  variable  is  determined  to 
to  have  a  loop-invariant  value,  expressions  using  t h at  variable  may  also  become 
loop-invariant. 

P a r t i a l ly  R e d u n d a nt  E x p r e s s i o ns 

An  example  of  a  partially  redundant  expression  is  shown  in  Fig.  9.30(c).  T he 
expression  b  +  c  in  block  B4  is  redundant  on  t he  p a th  B\  -»  B2  —>  B4,  but  not 
on  the  p a th  B\  ->•  B3  ->•  B4.  We  can  eliminate  t he  redundancy  on  the  former 
p a th  by  placing  a  computation  of  b  +  c  in  block  B3.  All  t he  results  of  b  +  c  are 
written  into  a  temporary  variable  t,  and  the  calculation  in  block  B4  is  replaced 
with  t.  Thus,  like  loop-invariant  code  motion,  partial-redundancy  elimination 
requires  the  placement  of  new  expression  computations. 

9.5.2  Can  All  Redundancy  Be  Eliminated? 

Is  it  possible  to  eliminate  all  redundant  computations  along  every  p a t h?  T he 
answer  is  "no,"  unless  we  are  allowed  to  change  the  flow  graph  by  creating  new 
blocks. 

E x a m p le  9 . 2 8:  In  the  example  shown  in  Fig.  9.31(a),  t he  expression  of  b  +  c 
is  computed  redundantly  in  block  B4  if t he  program  follows  t he  execution  p a th 
Bi 
B2  ->  B4.  However,  we  cannot  simply  move  the  computation  of  b  +  c  to 
block  B3,  because  doing  so  would  create  an  extra  computation  of  6  +  c  when 
the  p a th  B\  ->  B3 

B5  is  taken. 

W h at  we  would  like  to  do  is  to  insert  the  computation  of  b  +  c  only  along 
the  edge  from  block  B3  to  block  B4.  We  can  do  so  by  placing  the  instruction 
in  a  new  block,  say,  BQ,  and  making  the  flow  of  control  from  B3  go  through  B6 
before  it  reaches  B4.  T he  transformation  is  shown  in  Fig.  9.31(b). 

• 

9.5. 

PARTIAL-REDUNDANCY 

ELIMINATION 

643 

(a) 

(b) 

Figure  9.31:  B3  -+  BA  is  a  critical  edge 

We  define  a  critical  edge  of  a  flow  graph  to  be  any  edge  leading  from  a 

node  with  more  t h an  one  successor  to  a  node  with  more  t h an  one  predecessor. 
By  introducing  new  blocks  along  critical  edges,  we  can  always  find  a  block  to 
accommodate  t he  desired  expression  placement.  For  instance,  t he  edge  from 
B3  to  B4  in  Fig.  9.31(a)  is  critical,  because  B3  has  two  successors,  and  B4  has 
two  predecessors. 

Adding  blocks  may  not  be  sufficient  to  allow  t he  elimination  of  all  redundant 
computations.  As  shown  in  Example  9.29,  we  may  need  to  duplicate  code  so 
as  to  isolate  t he  p a th  where  redundancy  is  found. 

E x a m p le  9 . 2 9:  In  the  example  shown  in  Figure  9.32(a),  t he  expression  of  b+c 
is  computed  redundantly  along  the  p a th  B\  -+  B2  -+  B4  —>  BQ .  We  would  like 
to  remove  the  redundant  computation  of  b  +  c  from  block  BQ  in  this  path  and 
compute  the  expression  only  along  the  p a th  B\  -+  B3  -+  B4  -+  BQ.  However, 
there  is  no  single  program  point  or  edge  in  the  source  program  t h at  corresponds 
uniquely  to  the  latter  p a t h.  To  create  such  a  program  point,  we  can  duplicate 
the  pair  of  blocks  B4  and  BQ ,  with  one  pair  reached  through  B2  and  t he  other 
reached  through  B3:  as  shown  in  Figure  9.32(b).  The  result  of  b  +  c  is  saved  in 
variable  t  in  block  B2,  and  moved  to  variable  d  in  B'Q,  the  copy  of  BQ  reached 
from  B2. 

• 

Since  the  number  of  paths  is  exponential  in  the  number  of  conditional 
branches  in  t he  program,  eliminating  all  redundant  expressions  can  greatly 
increase  the  size  of  the  optimized  code.  We  therefore  restrict  our  discussion 
of  redundancy-elimination  techniques  to  those  t h at  may  introduce  additional 
blocks  but  t h at  do  not  duplicate  portions  of  t he  control  flow  graph. 

644 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

B 

a  = 
t  = 

b+c 
a 

B'A 

fa) 

(b) 

Figure  9.32:  Code  duplication  to  eliminate  redundancies 

9.5.3  The  Lazy-Code-Motion  Problem 

It  is  desirable  for  programs  optimized  with  a  partial-redundancy-elimination 
algorithm  to  have  t he  following  properties: 

1.  All  redundant  computations  of expressions  t h at  can  be  eliminated  without 

code  duplication  are  eliminated. 

2.  The  optimized  program  does  not  perform  any  computation  t h at  is  not  in 

the  original  program  execution. 

3.  Expressions  are  computed  at  t he  latest  possible  time. 

The  last  property  is  important  because  t he  values  of  expressions  found  to  be 
redundant  are  usually  held  in  registers  until  they  are  used.  Computing  a  value 
as  late  as  possible  minimizes  its  lifetime  —  the  duration  between  the  time  t he 
value  is  defined  and  t he  time  it  is  last  used,  which  in  t u rn  minimizes  its  usage  of 
a  register.  We  refer  to  the  optimization  of  eliminating  partial  redundancy  with 
the  goal  of  delaying  the  computations  as  much  as  possible  as  lazy  code  motion. 
To  build  up  our  intuition  of the  problem,  we  first  discuss  how  to  reason  about 
partial  redundancy  of  a  single  expression  along  a  single  p a t h.  For  convenience, 
we  assume  for  t he  rest  of  the  discussion  t h at  every  statement  is  a  basic  block 
of  its  own. 

9.5. 

PARTIAL-REDUNDANCY 

ELIMINATION 

645 

Full  R e d u n d a n cy 

An  expression  e  in  block  B  is  redundant  if  along  all  p a t hs  reaching  B,  e  has 
been  evaluated  and  the  operands  of  e  have  not  been  redefined  subsequently. 
Let  S  be  t he  set  of  blocks,  each  containing  expression  e,  t h at  renders  e  in  B 
redundant.  T he  set  of  edges  leaving  the  blocks  in  S  must  necessarily  form  a 
cutset,  which  if  removed,  disconnects  block  B  from  the  entry  of  the  program. 
Moreover,  no  operands  of  e  are  redefined  along  the  paths  t h at  lead  from  the 
blocks  in  S  to  B. 

P a r t i al  R e d u n d a n cy 

If  an  expression  e  in  block  B  is  only  partially  redundant,  the  lazy-code-motion 
algorithm  a t t e m p ts  to  render  e  fully  redundant  in  B  by  placing  additional  copies 
of  the  expressions  in  the  flow  graph.  If  the  a t t e m pt  is  successful,  the  optimized 
flow  graph  will  also  have  a  set  of  basic  blocks 5,  each  containing  expression  e, 
and  whose  outgoing  edges  are  a  cutset  between  the  entry  and  B.  Like  the  fully 
redundant  case,  no  operands  of  e  are  redefined  along  the  paths  t h at  lead  from 
t he  blocks  in  S  to  B. 

9.5.4  Anticipation  of  Expressions 

There  is  an  additional  constraint  imposed  on  inserted  expressions  to  ensure 
t h at  no  extra  operations  are  executed.  Copies  of  an  expression  must  be  placed 
only  at  program  points  where  the  expression  is  anticipated.  We  say  t h at  an 
expression  b  +  c  is  anticipated  at  point  p  if  all  paths  leading  from  t he  point  p 
eventually  compute  the  value  of the  expression  b +  c  from  the  values  of  b  and  c 
t h at  are  available  at  t h at  point. 

Let  us  now  examine  what  it  takes  to  eliminate  partial  redundancy  along  an 
acyclic  p a th  Bi  -+  B2  -»...-»  Bn.  Suppose  expression  e  is  evaluated  only  in 
blocks  B\  and  Bn,  and  t h at  the  operands  of  e  are  not  redefined  in  blocks  along 
t he  p a t h.  There  are  incoming  edges  t h at  join  the  path  and  there  are  outgoing 
edges  t h at  exit  the  path.  We  see  t h at  e  is  not  anticipated  at  the  entry  of  block 
Bi  if  and  only  if  there  exists  an  outgoing  edge  leaving  block  Bj,  i  <  j  <  n,  t h at 
leads  to  an  execution  p a th  t h at  does  not  use  the  value  of  e.  Thus,  anticipation 
limits  how  early  an  expression  can  be  inserted. 

We  can  create  a  cutset  t h at  includes  the  edge  B^i  -+  Bi  and  t h at  renders 
e  redundant  in  Bn  if  e  is  either  available  or  anticipated  at  the  entry  of  Bi.  If  e 
is  anticipated  but  not  available  at  the  entry  of  Bi,  we  must  place  a  copy  of  t he 
expression  e  along  the  incoming  edge. 

We  have  a  choice  of  where  to  place  the  copies  of  the  expression,  since  there 
are  usually  several  cutsets  in  t he  flow  graph  t h at  satisfy  all  the  requirements. 
In  the  above,  computation  is  introduced  along  the  incoming  edges  to  the  p a th 
of  interest  and  so  the  expression  is  computed  as  close  to  the  use  as  possible, 
without  introducing  redundancy.  Note  t h at  these  introduced  operations  may 
themselves  be  partially  redundant  with  other  instances  of  the  same  expression 

646 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

in  the  program.  Such  partial  redundancy  may  be  eliminated  by  moving  these 
computations  further  up. 

In  summary,  anticipation  of  expressions  limits  how  early  an  expression  can 
be  placed;  you  cannot  place  an  expression  so  early  t h at  it  is  not  anticipated 
where  you  place  it.  The  earlier  an  expression  is  placed,  the  more  redundancy 
can  be  removed,  and  among  all  solutions  t h at  eliminate  t he  same  redundancies, 
the  one  t h at  computes  the  expressions  the  latest  minimizes  t he  lifetimes  of  the 
registers  holding  the  values  of  the  expressions  involved. 

9.5.5  The  Lazy-Code-Motion  Algorithm 

This  discussion  thus  motivates  a  four-step  algorithm.  T he  first  step  uses  an 
ticipation  to  determine  where  expressions  can  be  placed;  the  second  step  finds 
the  earliest  cutset,  among  those  t h at  eliminate  as  many  redundant  operations 
as  possible  without  duplicating  code  and  without  introducing  any  unwanted 
computations.  This  step  places  the  computations  at  program  points  where  the 
values  of  their  results  are  first  anticipated.  T he  third  step  then  pushes  the 
cutset  down  to  the  point  where  any  further  delay  would  alter  the  semantics  of 
the  program  or  introduce  redundancy.  The  fourth  and  final  step  is  a  simple 
pass  to  clean  up  the  code  by  removing  assignments  to  temporary  variables  t h at 
are  used  only  once.  Each  step  is  accomplished  with  a  data-flow  pass:  t he  first 
and  fourth  are  backward-flow  problems,  t he  second  and  third  are  forward-flow 
problems. 

A l g o r i t hm  O v e r v i ew 

1.  Find  all  the  expressions  anticipated  at  each  program  point  using  a  back 

ward  data-flow  pass. 

2.  T he  second  step  places  the  computation  where  t he  values  of  t he  expres 

sions  are  first  anticipated  along  some  p a t h.  After  we  have  placed  copies 
of  an  expression  where  the  expression  is  first  anticipated,  the  expression 
would  be  available  at  program  point  p  if  it  has  been  anticipated  along  all 
paths  reaching  p.  Availability  can  be  solved  using  a  forward  data-flow 
pass. 
If  we  wish  to  place  the  expressions  at  the  earliest  possible  posi 
tions,  we  can  simply  find  those  program  points  where  t he  expressions  are 
anticipated  but  are  not  available. 

3.  Executing  an  expression  as  soon  as  it  is  anticipated  may  produce  a  value 
long  before  it  is  used.  An  expression  is  postponable  at  a  program  point  if 
the  expression  has  been  anticipated  and  has  yet  to  be  used  along  any  p a th 
reaching  the  program  point.  Postponable  expressions  are  found  using  a 
forward  data-flow  pass.  We  place  expressions  at  those  program  points 
where  they  can  no  longer  be  postponed. 

4.  A  simple,  final  backward  data-flow  pass  is  used  to  eliminate  assignments 

to  temporary  variables  t h at  are  used  only  once  in  the  program. 

9.5. 

PARTIAL-REDUNDANCY 

ELIMINATION 

647 

P r e p r o c e s s i ng  S t e ps 

We  now  present  t he  full  lazy-code-motion  algorithm.  To  keep  t he  algorithm 
simple,  we  assume  t h at  initially  every  statement  is  in  a  basic  block  of  its  own, 
and  we  only  introduce  new  computations  of  expressions  at  the  beginnings  of 
blocks.  To  ensure  t h at  this  simplification  does  not  reduce  the  effectiveness  of 
the  technique,  we  insert  a  new  block  between  the  source  and  the  destination  of 
an  edge  if  t he  destination  has  more  t h an  one  predecessor.  Doing  so  obviously 
also  takes  care  of  all  critical  edges  in  the  program. 

We  abstract  t he  semantics  of  each  block  B  with  two  sets:  e-uses  is  the  set 
of  expressions  computed  in  B  and  e-kills  is  the  set  of  expressions  killed,  t h at 
is,  t he  set  of expressions  any  of whose  operands  are  defined  in  B.  Example  9.30 
will  be  used  throughout  the  discussion  of  the  four  data-flow  analyses  whose 
definitions  are  summarized  in  Fig.  9.34. 

E x a m p le  9. 3 0:  In  the  flow  graph  in  Fig.  9.33(a),  the  expression  b + c  appears 
three  times.  Because  t he  block  B9  is  part  of  a  loop,  t he  expression  may  be 
computed  many  times.  The  computation  in  block  BQ  is  not  only  loop  invariant; 
it  is  also  a  redundant  expression,  since  its  value  already  has  been  used  in  block 
Bj.  For  this  example,  we  need  to  compute  b+c  only  twice,  once  in  block  B5  and 
once  along  the  p a th  after  B2  and  before  B7.  T he  lazy  code  motion  algorithm 
will  place  the  expression  computations  at  the  beginning  of  blocks  B4  and  B5. 
• 

A n t i c i p a t ed  E x p r e s s i o ns 

Recall  t h at  an  expression  b  +  c  is  anticipated  at  a  program  point  p  if  all  paths 
leading  from  point  p  eventually  compute  the  value  of  the  expression  b  +  c  from 
the  values  of  b  and  c  t h at  are  available  at  t h at  point. 

In  Fig.  9.33(a),  all  t he  blocks  anticipating  b + c  on  entry  are  shown  as  lightly 
shaded boxes.  T he expression b + c is  anticipated in blocks £3, £4, . B 5, £?6,  BJ, 
and  BQ. 
It  is  not  anticipated  on  entry  to  block  B2,  because  the  value  of  c  is 
recomputed  within  t he  block,  and  therefore  the  value  of  b  +  c  t h at  would  be 
computed  at  t he  beginning  of  B2  is  not  used  along  any  p a t h.  The  expression 
b+c  is  not  anticipated  on  entry  to  B\,  because  it  is  unnecessary  along t he  branch 
from  B\  to  B2  (although  it  would  be  used  along  t he  p a th  B\  —>  B5  ->  BQ). 
Similarly,  the  expression  is  not  anticipated  at  the  beginning  of  B8,  because  of 
t he  branch  from  B8  to  Bn.  The  anticipation  of  an  expression  may  oscillate 
along  a  p a t h,  as  illustrated  by £7 —>  Bg —>  BQ. 

T he  data-flow  equations  for  the  anticipated-expressions  problem  are  shown 
in  Fig  9.34(a).  T he  analysis  is  a  backward  pass.  An  anticipated  expression  at 
the  exit  of a  block  B  is  an  anticipated  expression  on  entry  only  if it  is  not  in  the 
e-kills  set.  Also  a  block  B  generates  as  new  uses  t he  set  of  ejuses  expressions. 
At  the  exit  of  the  program,  none  of  the  expressions  are  anticipated.  Since  we 
are  interested  in  finding  expressions  t h at  are  anticipated  along  every  subsequent 

648 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

d  - b+c 

anticipated 

Figure  9.33:  Flow  graph  of  Example  9.30 

(b) 

p a t h,  the  meet  operator  is  set  intersection.  Consequently,  the  interior  points 
must  be  initialized  to  the  universal  set  U,  as  was  discussed  for  t he  available-
expressions  problem  in  Section  9.2.6. 

A v a i l a b le  E x p r e s s i o ns 

At  t he  end  of this  second  step,  copies  of an  expression  will  be  placed  at  program 
points  where  t he  expression  is  first  anticipated.  If t h at  is  the  case,  an  expression 
will  be  available  at  program  point  p  if  it  is  anticipated  along  all  paths  reaching 
p.  This  problem  is  similar  to  available-expressions  described  in  Section  9.2.6. 
T he  transfer  function  used  here  is  slightly  different  though.  An  expression  is 
available  on  exit  from  a  block  if  it  is 

9.5. 

PARTIAL-REDUNDANCY  ELIMINATION 

649 

(a)  Anticipated  Expressions 

(b)  Available  Expressions 

Domain 

Sets  of  expressions 

Sets  of  expressions 

Direction 

Backwards 

IB{X)  = 

Forwards 

IB(X)  =  " 

Transfer 

function 

Boundary 

Meet  (A) 

e-uses  U 

(x  —  e-killB) 

(anticipated[B].in  U  x)  —  e-killB 

IN  [ E X I T]  =  0 

O U T [ E N T R Y]  =  '0 

n 

n 

Equations 

I N [ B] 

= 

fB(OUT[B}) 

O U T [ B]  = 

/B( I N [ B ]) 

OVT[B]  =  A sI S„C C( B)  MS] 

I N [ £]  = 

/ \P,P R E D ( B)  O U T [ P] 

Initialization  W[B]  =  U 

O U T [ £]  =  U 

(c)  Postponable  Expressions 

(d)  Used  Expressions 

Domain 

Sets  of  expressions 

Sets  of  expressions 

Direction 

Forwards 

IB(X)  = 

Backwards 

/B(X)  = 

Transfer 

function 

Boundary 

Meet  (A) 

(earliest[B]  U  x)  —  ejuseB 

(ejuseB  U  x)  —  latest[B]) 

O UT [ E N T R Y]  =  0 
n 

IN [ E X I T]  =  0 
u 

Equations 

O U T [ £] 

= 

fB(m[B}) 

m[B] = Ap,p r e d ( B)  O U T [ P] 

I N [ £]  =  /B( O U T[ f l ]) 
OUT[B]  =  / \S s u c c ( b)  m[S] 

Initialization  OUT[5] =  U 

IN[B] = 0 

earliest[B] 

=  anticipated[B].in  —  available[B].in 

latest[B] 

= 

(earliest[B]  U  postponable[B].in)  n 

(ejuseB  U  ^(C\Ssucc[B] 

(earliest[S]  U  postponable[S].in))^ 

Figure  9.34:  Four  data-flow  passes  in  partial-redundancy  elimination 

650 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

Completing  the  Square 

Anticipated expressions  (also called  "very busy expressions"  elsewhere)  is  a 
type  of data-flow  analysis  we  have  not  seen  previously.  While  we  have  seen 
backwards-flowing  frameworks  such  as  live-variable  analysis  (Sect.  9.2.5), 
and  we  have  seen  frameworks  where  the  meet  is  intersection  such  as  avail 
able  expressions  (Sect.  9.2.6),  this  is  t he  first  example  of  a  useful  analysis 
t h at  has  b o th  properties.  Almost  all  analyses  we  use  can  be  placed  in  one 
of  four  groups,  depending  on  whether  they  flow  forwards  or  backwards, 
and  depending  on  whether  they  use  union  or  intersection  for  the  meet. 
Notice  also  t h at  t he  union  analyses  always  involve  asking  a b o ut  whether 
there  exists  a  p a th  along  which  something  is  true,  while  t he  intersection 
analyses  ask  whether  something  is  true  along  all  paths. 

1.  Either 

(a)  Available,  or 

(b)  In  the  set  of  anticipated  expressions  upon  entry  (i.e.,  it  could  be 

made  available  if  we  chose  to  compute  it  here), 

and 

2.  Not  killed  in  the  block. 

The  data-flow  equations  for  available  expressions  are  shown  in  Fig  9.34(b). 
To  avoid  confusing  the  meaning  of IN,  we  refer  to  t he  result  of an  earlier  analysis 
by  appending  "[JBj.m"  to  the  name  of  the  earlier  analysis. 

W i th  t he  earliest  placement  strategy,  t he  set  of  expressions  placed  at  block 
B,  i.e.,  earliest[B],  is  defined  as  the  set  of  anticipated  expressions  t h at  are  not 
yet  available.  T h at  is, 

earliest[B]  —  anticipated[B].in  —  available[B].in. 

E x a m p le  9 . 3 1:  T he  expression  b  +  c  in  the  flow  graph  in  Figure  9.35  is  not 
anticipated  at  the  entry  of  block  B3  but  is  anticipated  at  the  entry  of  block 
B4.  It  is,  however,  not  necessary  to  compute  t he  expression  6  +  c  in  block  B4, 
because  the  expression  is  already  available  due  to  block  B2 • 

• 

E x a m p le  9 . 3 2:  Shown  with  dark  shadows  in  Fig.  9.33(a)  are  t he  blocks  for 
which  expression  b  +  c  is  not  available; 
The 
early-placement  positions  are  represented  by  t he  lightly  shaded  boxes  with  dark 
shadows,  and  are  thus  blocks  B3  and  £?5.  Note,  for  instance,  t h at  b  +  c  is 
considered  available  on  entry  to  B4,  because  there  is  a  p a th  B\  -»  B2  ->  B3  —»• 
£?4  along  which  b  +  c  is  anticipated  at  least  once  —  at  B3  in  this  case  —  and 
since  the  beginning  of  B3,  neither  b  nor  c  was  recomputed. 

they  are  Bi,B2,B3,  and  B5. 

• 

9.5. 

PARTIAL-REDUNDANCY  ELIMINATION 

651 

a =  b+c 

d  =  b+c 

Figure  9.35:  Flow  graph  for  Example  9.31  illustrating  t he  use  of  availability 

P o s t p o n a b le  E x p r e s s i o ns 

T he  third  step  postpones  the  computation  of  expressions  as  much  as  possible 
while  preserving  t he  original  program  semantics  and  minimizing  redundancy. 
Example  9.33  illustrates  the  importance  of  this  step. 

E x a m p le  9 . 3 3:  In  the  flow  graph  shown  in  Figure  9.36,  the  expression  b  +  c 
is  computed  twice  along  the  p a th  Bi  -+  B5  -»  BQ  -»  B7.  The  expression  b  +  c 
is  anticipated  even  at  the  beginning  of  block  B\.  If  we  compute  the  expression 
as  soon  as  it  is  anticipated,  we  would  have  computed  the  expression  b + c  in  B\. 
The  result  would  have  to  be  saved  from  the  beginning,  through  the  execution 
of  the  loop  comprising  blocks  B2  and £3,  until  it  is  used  in  block  B7.  Instead 
we  can  delay  the  computation  of  expression  b +  c  until  the  beginning  of  B5  and 
until  the  flow  of  control  is  about  to  transition  from  B4  to  Bq. 

• 

Formally,  an  expression  x  +  y  is  postponable  to  a  program  point  p  if  an  early 
placement  of  x  +  y  is  encountered  along  every  p a th  from  the  entry  node  to  p, 
and  there  is  no  subsequent  use  of  x  +  y  after  t he  last  such  placement. 

E x a m p le  9 . 3 4:  Let  us  again  consider  expression  b  +  c  in  Fig.  9.33.  T he  two 
earliest  points  for  b  +  c  are  B3  and  B5;  note  t h at  these  are  t he  two  blocks  t h at 
are  b o th  lightly  and  darkly  shaded  in  Fig.  9.33(a),  indicating  t h at  b +  c  is  b o th 
anticipated  and  not  available  for  these  blocks,  and  only  these  blocks.  We  cannot 
postpone  b +  c  from  B5  to  BQ ,  because  b  +  c  is  used  in  B5.  We  can  postpone  it 
from  B3 

to  B4,  however. 

But  we  cannot  postpone  b  +  c  from  B4  to  B7.  The  reason  is  t h a t,  although 
b  +  c  is  not  used  in  B4,  placing  its  computation  at  B7  instead  would  lead  to  a 

652 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

Figure  9.36:  Flow  graph  for  Example  9.33  to  illustrate  the  need  for  postponing 
an  expression 

redundant  computation  of  b  +  c  along  the  p a th  B§  -»  BQ  -»  B7.  As  we  shall 
see,  B4  is  one  of  the  latest  places  we  can  compute  b  +  c. 

• 

The  data-flow  equations  for  the  postponable-expressions  problem  are  shown 
in  Fig  9.34(c).  The  analysis  is  a  forward  pass.  We  cannot  "postpone"  an 
expression  to  the  entry  of  the  program,  so  O U T [ E N T R Y]  = 0.  An  expression 
is  postponable  to  the  exit  of  block  B  if  it  is  not  used  in  the  block,  and  either 
it  is  postponable  to  the  entry  of  B  or  it  is  in  earliest[B].  An  expression  is 
not  postponable  to  the  entry  of  a  block  unless  all  its  predecessors  include  the 
expression  in  their  postponable  sets  at  their  exits.  Thus,  the  meet  operator  is 
set  intersection,  and  the  interior  points  must  be  initialized  to  the  top  element 
of  the  semilattice  —  the  universal  set. 

Roughly  speaking,  an  expression  is  placed  at  the  frontier where  an  expression 
transitions  from  being  postponable  to  not  being  postponable.  More  specifically, 
an  expression  e  may  be  placed  at  the  beginning  of  a  block  B  only  if  the  expres 
sion  is  in  B's  earliest  or  postponable  set  upon  entry. 
postponement  frontier  of  e  if  one  of  the  following  holds: 

In  addition,  B  is  in  the 

1.  e  is  not  in  postponable[B].out.  In  other  words,  e  is  in  ejuses-

2.  e  cannot  be  postponed  to  one  of  its  successors. 

In  other  words,  there 
exists  a  successor  of  B  such  t h at  e  is  not  in  the  earliest  or  postponable  set 
upon  entry  to  t h at  successor. 

Expression  e  can  be  placed  at  the  front  of  block  B  in  either  of  t he  above 
scenarios  because  of  the  new  blocks  introduced  by  t he  preprocessing  step  in  the 
algorithm. 

9.5. 

PARTIAL-REDUNDANCY 

ELIMINATION 

653 

E x a m p le  9 . 3 5:  Fig.  9.33(b)  shows  the  result  of the  analysis.  T he  light-shaded 
boxes  represent  the  blocks  whose  earliest  set  includes  b  +  c.  The  dark  shadows 
indicate  those  t h at  include  b +  c  in  their  postponable  set.  The  latest  placements 
of  t he  expressions  are  thus  t he  entries  of  blocks  B4  and  B5,  since 

1.  b  +  c  is  in  t he  postponable  set  of  _B4  but  not  B7,  and 

2.  I Vs  earliest  set  includes  b  +  c  and  it  uses  b  +  c. 

T he  expression  is  stored  into  the  temporary  variable  t  in  blocks  B4  and  B5,  and 
t  is  used  in  place  of  b  +  c  everywhere  else,  as  shown  in  the  figure. 

• 

U s ed  E x p r e s s i o ns 

Finally,  a  backward  pass  is  used  to  determine  if  the  temporary  variables  in 
troduced  are  used  beyond  the  block  they  are  in.  We  say  t h at  an  expression  is 
used  at  point  p  if  there  exists  a  p a th  leading  from  p  t h at  uses  t he  expression 
before  the  value  is  reevaluated.  This  analysis  is  essentially  liveness  analysis  (for 
expressions,  rather  t h an  for  variables). 

T he  data-flow  equations  for  the  used  expressions  problem  are  shown  in 
Fig  9.34(d).  T he  analysis  is  a  backward  pass.  A  used  expression  at  t he  exit 
of  a  block  B  is  a  used  expression  on  entry  only  if  it  is  not  in  the  latest  set. 
A  block  generates,  as  new  uses,  t he  set  of  expressions  in  e j u s e ^.  At  t he  exit 
of  the  program,  none  of  the  expressions  are  used.  Since  we  are  interested  in 
finding  expressions  t h at  are  used  by  any  subsequent  p a t h,  t he  meet  operator  is 
set  union.  Thus,  the  interior  points  must  be  initialized  with  the  top  element  of 
the  semilattice  —  the  empty  set. 

P u t t i ng  it  A ll  T o g e t h er 

All  the  steps  of  the  algorithm  are  summarized  in  Algorithm  9.36. 

A l g o r i t hm  9.36  :  Lazy  code  motion. 

INPUT:  A  flow  graph  for  which  ejuses  and  eJtillB  have  been  computed  for 
each  block  B. 

OUTPUT:  A  modified flow graph  satisfying  the  four  lazy  code  motion  conditions 
in  Section  9.5.3. 

METHOD: 

1.  Insert  an  empty  block  along  all  edges  entering  a  block  with  more  t h an 

one  predecessor. 

2.  Find  anticipated[B].in  for  all  blocks  B,  as  defined  in  Fig.  9.34(a). 

3.  Find  available[B].in  for  all  blocks  B  as  defined  in  Fig.  9.34(b). 

654 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

4.  Compute  the  earliest  placements  for  all  blocks  B: 

earliest[B]  = 

anticipated[B].in 

- 

available[B].in 

5.  Find  postponable[B).in  for  all  blocks  B  as  defined  in  Fig.  9.34(c). 

6.  Compute  the  latest  placements  for  all  blocks  B: 

latest[B]  = 

(earliest[B]  U  postponable[B].in) 

n 

'S  in  succ[B] 

Note  t h at  -i  denotes  complementation  with  respect  to  the  set  of  all  ex 
pressions  computed  by  the  program. 

7.  Find  used[B].out  for  all  blocks  B,  as  defined  in  Fig.  9.34(d). 

8.  For  each  expression,  say  x+y,  computed  by  the  program,  do  t he  following: 

(a)  Create  a  new  temporary,  say  t,  for  x  +  y. 

(b)  For  all  blocks  B  such  t h at  x  +  y  is  in  latest[B]  n  used[B].out,  add 

t  =  x+y  at  the  beginning  of  B. 

(c)  For  all  blocks  B  such  t h at  x  +  y  is  in 

ejuses  H 

(->latest[B]  U  used.out[B]) 

replace  every  original  x  +  y  by  t. 

• 

S u m m a ry 

Partial-redundancy  elimination  finds  many  different  forms  of  redundant  opera 
tions  in  one  unified  algorithm.  This  algorithm  illustrates  how  multiple  data-flow 
problems  can  be  used  to  find  optimal  expression  placement. 

1.  T he  placement  constraints  are  provided  by  the  anticipated-expressions 
analysis,  which  is  a  backwards  data-flow  analysis  with  a  set-intersection 
meet  operator,  as  it  determines  if  expressions  are  used  subsequent  to  each 
program  point  on  all  paths. 

2.  T he  earliest  placement  of an  expression  is  given  by  program  points  where 
the  expression  is  anticipated  but  is  not  available.  Available  expressions 
are  found  with  a  forwards  data-flow  analysis  with  a  set-intersection  meet 
operator  t h at  computes  if  an  expression  has  been  anticipated  before  each 
program  point  along  all  paths. 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

655 

3.  T he  latest  placement  of  an  expression  is  given  by  program  points  where 
an  expression  can  no  longer  be  postponed.  Expressions  are  postponable 
at  a  program  point  if  for  all  p a t hs  reaching  t he  program  point,  no  use  of 
the  expression  has  been  encountered.  Postponable  expressions  are  found 
with  a  forwards  data-flow  analysis  with  a  set-intersection  meet  operator. 

4.  Temporary  assignments  are  eliminated  unless  they  are  used  by  some  p a th 
subsequently.  We  find  used  expressions  with  a  backwards  data-flow  anal 
ysis,  this  time  with  a  set-union  meet  operator. 

9.5.6  Exercises  for  Section  9.5 

Exercise 9.5.1:  For  the  flow  graph  in  Fig.  9.37: 

a)  Compute  anticipated  for  the  beginning  and  end  of  each  block. 

b)  C o m p u te  available  for  the  beginning  and  end  of  each  block. 

c)  C o m p u te  earliest  for  each  block. 

d)  Compute  postponable  for  the  beginning  and  end  of  each  block. 

e)  C o m p u te  used  for  the  beginning  and  end  of  each  block. 

f)  Compute  latest  for  each  block. 

g)  Introduce  t e m p o r a ry  variable  t;  show  where  it  is  computed  and  where  it 

is  used. 

Exercise 9.5.2:  Repeat  Exercise  9.5.1  for  the  flow  graph  of Fig.  9.10  (see  the 
exercises  to  Section  9.1).  You  may  limit  your  analysis  to  the  expressions  a  +  6, 
c —  a,  a nd  b * d. 

!! Exercise 9.5.3:  T he  concepts  discussed  in  this  section  can  also be  applied to 
eliminate  partially  dead  code.  A  definition  of  a  variable  is  partially  dead  if  the 
variable  is  live  on  some  p a t hs  and  not  others.  We  can  optimize  the  program 
execution  by  only  performing  the  definition  along  paths  where  the  variable 
is  live.  Unlike  partial-redundancy  elimination,  where  expressions  are  moved 
before  t he  original,  t he  new  definitions  are  placed  after  t he  original.  Develop 
an  algorithm  to  move  partially  dead  code,  so  expressions  are  evaluated  only 
where  they  will  eventually  be  used. 

9.6  Loops  in  Flow  Graphs 

In  our  discussion  so  far,  loops  have  not  been  handled  differently;  they  have  been 
treated  just  like  any  other  kind  of  control  flow.  However,  loops  are  important 
because  programs  spend  most  of  their  time  executing  them,  and  optimizations 

656 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

ENTRY 

= x+y 

Bl 

B2 

B3 

B4 

x = 

= x+y 

= x+y 

EXIT 

Figure  9.37:  Flow  graph  for  Exercise  9.5.1 

t h at  improve  the  performance  of  loops  can  have  a  significant  impact.  Thus,  it 
is  essential  t h at  we  identify  loops  and  treat  t h em  specially. 

Loops  also  affect  t he  running  time  of  program  analyses.  If  a  program  does 
not  contain  any  loops,  we  can  obtain  the  answers  to  data-flow  problems  by 
making  just  one  pass  through  the  program.  For  example,  a  forward  data-flow 
problem  can  be  solved  by  visiting  all  t he  nodes  once,  in  topological  order. 

In  this  section,  we  introduce  the  following  concepts:  dominators,  depth-first 
ordering,  back  edges,  graph  depth,  and  reducibility.  Each  of  these  is  needed 
for  our  subsequent  discussions  on  finding  loops  and  the  speed  of  convergence  of 
iterative  data-flow  analysis. 

9.6.1  Dominators 

We  say  node  d  of  a  flow  graph  dominates  node  n,  written  d  dom  n,  if  every  p a th 
from  t he  entry  node  of  t he  flow  graph  to  n  goes  through  d.  Note  t h at  under 
this  definition,  every  node  dominates  itself. 

E x a m p le  9 . 3 7:  Consider  the  flow  graph  of  Fig.  9.38,  with  entry  node  1.  T he 
entry  node  dominates  every  node  (this  statement  is  t r ue  for  every  flow  graph). 
Node  2  dominates  only itself,  since  control  can  reach  any  other  node  along  a p a th 
t h at  begins  with  1  ->  3.  Node  3  dominates  all  but  1  and  2.  Node  4  dominates 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

657 

3 

all  but  1,  2  and  3,  since  all  paths  from  1  must  begin  with  l - > - 2 - > - 3 - > - 4 or 
1 
4.  Nodes  5  and  6  dominate  only  themselves,  since  flow  of control  can 
skip  around  either  by  going  through  the  other.  Finally,  7  dominates  7,  8,  9, 
and  10;  8  dominates  8,  9,  and  10;  9  and  10  dominate  only  themselves. 

• 

Figure  9.38:  A  flow  graph 

A  useful  way  of  presenting  dominator  information  is  in  a  tree,  called  the 
dominator  tree,  in  which  t he  entry  node  is  the  root,  and  each  node  d  dominates 
only  its  descendants  in  the  tree.  For  example,  Fig.  9.39  shows  the  dominator 
tree  for  t he  flow  graph  of  Fig.  9.38. 

Figure  9.39:  Dominator  tree  for  flow  graph  of  Fig.  9.38 

The  existence  of  dominator  trees  follows  from  a  property  of  dominators: 
each  node  n  has  a  unique  immediate  dominator  m  t h at  is  the  last  dominator 
of  n  on  any  p a th  from  the  entry  node  to  n.  In  terms  of  the  dom  relation,  t he 

658 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

immediate  dominator  m  has  t h at  property  t h at  if  d  ^  n  and  d  dom  n,  then 
d  dom  m. 

We  shall  give  a  simple  algorithm  for  computing  the  dominators  of  every 
node  n  in  a  flow  graph,  based  on  the  principle  t h at  if pi,p2,  •  •  •  ,Pk  are  all  t he 
predecessors  of  n,  and  d  ^  n,  then  d  dom  n  if  and  only  if  d  dom  pi  for  each  i. 
This  problem  can  be  formulated  as  a  forward  data-flow  analysis.  T he  data-flow 
values  are  sets  of  basic  blocks.  A  node's  set  of  dominators,  other  t h an  itself,  is 
the  intersection  of the  dominators  of all  its  predecessors;  thus  t he  meet  operator 
is  set  intersection.  The  transfer  function  for  block  B  simply  adds  B  itself  to  t he 
set  of  input  nodes.  T he  boundary  condition  is  t h at  the  E N T RY  node  dominates 
itself.  Finally,  the  initialization  of  the  interior  nodes  is  t he  universal  set,  t h at 
is,  the  set  of  all  nodes. 

A l g o r i t hm  9 . 3 8:  Finding  dominators. 

INPUT:  A  flow  graph  G  with  set  of  nodes  N,  set  of  edges  E  a nd  entry  node 

E N T R Y. 

OUTPUT:  D(n),  the  set  of  nodes  t h at  dominate  node  n,  for  all  nodes  n  in  N. 

METHOD:  Find  the  solution  to  the  data-flow  problem  whose  parameters  are 
shown  in  Fig.  9.40.  The  basic  blocks  are  the  nodes.  D(n)  =  O U T[ n]  for  all  n  in 
N. 

• 

Finding  dominators  using  this  data-flow  algorithm  is  efficient.  Nodes  in  the 

graph  need  to  be  visited  only  a  few  times,  as  we  shall  see  in  Section  9.6.7. 

Domain 

Direction 

Dominators 

The  power  set  of  N 

Forwards 

Transfer  function 

fB(x)=xU{B} 

Boundary 

Meet ( A) 

Equations 

O UT [ E N T R Y]  = 

{ E N T R Y} 

IT 

0 U T[ 5 ] = /B( I N [ J 3 ]) 

m[B]  =  AP,p r

e d ( B)  O U T [ P] 

Initialization 

O UT  [B]  =  N 

Figure  9.40:  A  data-flow  algorithm  for  computing  dominators 

E x a m p le  9 . 3 9:  Let  us  return  to  the  flow  graph  of  Fig.  9.38,  and  suppose 
t he  for-loop  of  lines  (4)  through  (6)  in  Fig.  9.23  visits  the  nodes  in  numerical 
order.  Let  D(n)  be  t he  set  of  nodes  in  OUT[n].  Since  1  is  t he  entry  node, 
D(l)  was  assigned  {1}  at  line  (1).  Node  2  has  only  1  for  a  predecessor,  so 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

659 

Properties  of  the  dom  Relation 

A  key  observation  about  dominators  is  t h at  if  we  take  any  acyclic  p a th 
from  the  entry  to  node  n,  then  all  the  dominators  of  n  appear  along  this 
p a t h,  and  moreover,  they  must  appear  in  the  same  order  along  any  such 
p a t h.  To  see  why,  suppose  there  were  one  acyclic  p a th  Pi  to  n  along  which 
dominators  a  and  b  appeared  in  t h at  order  and  another  p a th  P2  to  n,  along 
which  b  preceded  a.  Then  we  could  follow  Pi  to  a  and  P2  to  n,  thereby 
avoiding  b  altogether.  Thus,  b  would  not  really  dominate  a. 

This  reasoning  allows  us  to  prove  t h at  dom  is  transitive:  if  a  dom  b 
and  b  dom  c,  then  a  dom  c.  Also,  dom  is  antisymmetric:  it  is  never  possible 
t h at  b o th  a  dom  b  and  b  dom  a  hold,  if  a  /  b.  Moreover,  if  a  and  b  are 
two  dominators  of n,  then  either  a  dom  6  or  &  dom  a  must  hold.  Finally,  it 
follows  t h at  each  node  n  except  the  entry  must  have  a  unique  immediate 
dominator  —  the  dominator  t h at  appears  closest  to  n  along  any  acyclic 
p a th  from  the  entry  to  n. 

D(2)  =  { 2 } U D ( 1 ).  Thus,  D{2)  is  set  to  {1,  2}.  Then  node  3,  with  predecessors 
1,  2,  4,  and  8,  is  considered.  Since  all  the  interior  nodes  are  initialized  with  the 
universal  set  N, 

£>(3)  =  {3}  U  ({1} n  {1,2}  n  { 1 , 2 , . ..  , 10}  n  { 1 , 2 , . ..  , 10})  =  {1,3} 

The  remaining  calculations  are  shown  in  Fig.  9.41.  Since  these  values  do  not 
change  in  the  second  iteration  through  the  outer  loop  of  lines  (3)  through  (6) 
in  Fig.  9.23(a),  they  are  the  final  answers  to  the  dominator  problem. 

• 

D(4)  =  {4}  U  (D(3)  n  D(7))  =  {4}  U  ({1,3} n  { 1 , 2 , . ..  ,  10})  =  { 1 , 3 , 4} 

D(5)  =  {5}  U  P ( 4)  =  {5}  U  { 1 , 3 , 4}  =  { 1 , 3 , 4 , 5} 

D(6)  =  {6}  U  0 ( 4)  =  {6}  U  { 1 , 3 , 4}  =  { 1 , 3 , 4 , 6} 

D{7)  =  {7}  U  (U(5)  n  D(6)  n  £>(10)) 

=  {7}  U  ( { 1 , 3 , 4 , 5} n  { 1 , 3 , 4 , 6} n  { 1 , 2 , . ..  ,  10})  =  { 1 , 3 , 4 , 7} 

D(S)  =  {8}  U  D{7)  =  {8}  U  { 1 , 3 , 4 , 7}  =  { 1 , 3 , 4 , 7 , 8} 

D(9)  =  {9}  U  D(8)  =  {9}  U  { 1 , 3 , 4 , 7 , 8}  =  { 1 , 3 , 4 , 7 , 8 , 9} 

D(10)  =  {10}  U  £>(8)  =  {10}  U  { 1 , 3 , 4 , 7 , 8}  =  { 1 , 3 , 4 , 7 , 8 , 1 0} 

Figure  9.41:  Completion  of  the  dominator  calculation  for  Example  9.39 

660 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

9.6.2  Depth-First  Ordering 

As  introduced  in  Section  2.3.4,  a  depth-first  search  of  a  graph  visits  all  t he 
nodes  in  the  graph  once,  by  starting  at  the  entry  node  and  visiting  t he  nodes 
as  far  away  from  the  entry  node  as  quickly  as  possible.  T he  route  of t he  search 
in  a  depth-first  search  forms  a  depth-first  spanning  tree  (DFST).  Recall  from 
Section  2.3.4  t h at  a  preorder  traversal  visits  a  node  before  visiting  any  of  its 
children,  which  it  then  visits  recursively  in  left-to-right  order.  Also,  a  postorder 
traversal  visits  a node's  children,  recursively  in  left-to-right  order,  before  visiting 
the  node  itself. 

There  is  one  more  variant  ordering  t h at  is  important  for  flow-graph  analysis: 
a  depth-first  ordering  is  t he  reverse  of  a  postorder  traversal.  T h at  is,  in  a  depth-
first  ordering,  we  visit  a  node,  then  traverse  its  rightmost  child,  the  child  to  its 
left,  and  so  on.  However,  before  we  build  the  tree  for  the  flow  graph,  we  have 
choices  as  to  which  successor  of  a  node  becomes  the  rightmost  child  in  the  tree, 
which  node  becomes  t he  next  child,  and  so  on.  Before  we  give  the  algorithm 
for  depth-first  ordering,  let  us  consider  an  example. 

E x a m p le  9 . 4 0:  One  possible  depth-first  presentation  of  the  flow  graph  in 
Fig.  9.38  is  illustrated  in  Fig.  9.42.  Solid  edges  form  the  tree;  dashed  edges  are 
the  other  edges  of  the  flow  graph.  A  depth-first  traversal  of  the  tree  is  given 
by:  1  ->  3  ->•  4  -»  6  ->  7  -»•  8  ->•  10,  then  back  to  8,  then  to  9.  We  go  back  to  8 
once  more,  retreating  to  7,  6,  and  4,  and  then  forward  to  5.  We  retreat  from  5 
back  to  4,  then  back  to  3  and  1.  From  1  we  go  to  2,  then  retreat  from  2,  back 
to  1,  and  we  have  traversed  the  entire  tree. 

The  preorder  sequence  for  the  traversal  is  thus 

1 , 3 , 4 , 6 , 7 , 8 , 1 0 , 9 , 5 , 2. 

The  postorder  sequence  for  the  traversal  of  the  tree  in  Fig.  9.42  is 

1 0 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1. 

The  depth-first  ordering,  which  is  t he  reverse  of  the  postorder  sequence,  is 

1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 1 0. 

• 

We  now  give  an  algorithm  t h at  finds  a  depth-first  spanning  tree  and  a  depth-
first  ordering  of  a  graph.  It  is  this  algorithm  t h at  finds  the  D F ST  in  Fig.  9.42 
from  Fig.  9.38. 

A l g o r i t hm  9 . 4 1:  Depth-first  spanning  tree  and  depth-first  ordering. 

I N P U T:  A  flow  graph  G. 

O U T P U T:  A  D F ST  T  of  G  and  an  ordering  of  the  nodes  of  G. 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

661 

Figure  9.42:  A  depth-first  presentation  of  the  flow  graph  in  Fig.  9.38 

M E T H O D:  We  use  the  recursive  procedure  search(n)  of  Fig.  9.43.  T he  algo 
rithm  initializes  all  nodes  of  G  to  "unvisited,"  then  calls  search(no),  where  no 
is  the  entry.  When  it  calls  search(n),  it  first  marks  n  "visited"  to  avoid  adding 
n  to  the  tree  twice.  It  uses  c  to  count  from  the  number  of  nodes  of  G  down  to 
1,  assigning  depth-first  numbers  dfn[n]  to  nodes  n  as  we  go.  T he  set  of  edges 
T  forms  t he  depth-first  spanning  tree  for  G. 

• 

E x a m p le  9 . 4 2:  For  the  flow  graph  in  Fig.  9.42,  Algorithm  9.41  sets  c  to  10 
and  begins  the  search  by  calling  search(l).  The  rest  of  the  execution  sequence 
is  shown  in  Fig.  9.44. 

• 

9.6.3  Edges  in  a  Depth-First  Spanning  Tree 

When  we  construct  a  D F ST  for  a  flow  graph,  the  edges  of  the  flow  graph  fall 
into  three  categories. 

1.  There  are  edges,  called  advancing  edges,  t h at  go  from  a  node  m  to  a  proper 
descendant  of  m  in  the  tree.  All  edges  in  the  D F ST  itself  are  advancing 
edges.  There  are  no  other  advancing  edges  in  Fig.  9.42,  but,  for  example, 
if  4  —>•  8  were  an  edge,  it  would  be  in  this  category. 

2.  There  are  edges  t h at  go  from  a  node  m  to  an  ancestor  of  m  in  the  tree 
(possibly  to  m  itself).  These  edges  we  shall  term  retreating  edges.  For 
example,  4 - > 3,  7 - > 4,  1 0 - »7  and  9  ->•  1  are  the  retreating  edges  in 
Fig.  9.42. 

662 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

v o id  search(n)  { 

mark  n  "visited"; 
for  (each  successor  s  of  n) 

if  (s  is  "unvisited")  { 

add  edge  n —>•  s  to  T; 
search(s); 

} 
dfn[n]  =  c; 
c  =  c  -  1; 

} 

mainQ 

{ 

T  =  0;  /*  set  of  edges  */ 
for  (each  node  n  of  G) 

mark  n  "unvisited"; 
c  =  number  of  nodes  of  G; 
search(no); 

} 

Figure  9.43:  Depth-first  search  algorithm 

3.  There  are  edges  m  —>  n  such  t h at  neither  m  nor  n  is  an  ancestor  of  the 
other  in  the  D F S T.  Edges  2 - ^3  and  5  ->  7  are  the  only  such  examples 
in  Fig.  9.42.  We  call  these  edges  cross  edges.  An  important  property  of 
cross  edges  is  t h at  if  we  draw  the  D F ST  so  children  of  a  node  are  drawn 
from  left  to  right  in  the  order  in  which  they  were  added  to  the  tree,  then 
all  cross  edges  travel  from  right  to  left. 

\ 

terminates  before  search(n),  so  dfn[m]  >  dfn[n].  Conversely, 

It  should  be  noted  t h at  m  ->•  n  is  a  retreating  edge  if  and  only  if  dfn[m]  > 
dfn[n].  To  see  why,  note  t h at  if  m  is  a  descendant  of  n  in  t he  D F S T,  then 
if 
search(m) 
terminates  before  search(n),  or  m  =  n.  But 
dfn[m]  >  dfn[n],  then  search(m) 
search(n)  must  have  begun  before  search(m)  if  there  is  an  edge  m  —>  n,  or  else 
the  fact  t h at  n  is  a  successor  of  m  would  have  made  n  a  descendant  of  m  in  the 
D F S T.  Thus  the  time  search(m)  is  active  is  a  subinterval  of  the  time  search(n) 
is  active,  from  which  it  follows  t h at  n  is  an  ancestor  of  m  in  the  D F S T. 

9.6.4  Back  Edges  and  Reducibility 

A  back  edge  is  an  edge  a  ->  b  whose  head  b  dominates  its  tail  a.  For  any 
flow  graph,  every  back  edge  is  retreating,  but  not  every  retreating  edge  is  a 
back  edge.  A  flow  graph  is  said  to  be  reducible  if  all  its  retreating  edges  in 
any  depth-first  spanning  tree  are  also  back  edges. 
In  other  words,  if  a  graph 
is  reducible,  then  all  the  D F S T 's  have  the  same  set  of  retreating  edges,  and 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

663 

Call 

search(l) 

Call 
Call 

search(3) 
search(A) 

Call 
Call 

search(6) 
search{7) 

Call 

search{8) 

Call  searc/i(10) 

to  search(8) 

R e t u rn 
Call 

search(9) 

R e t u rn 

to  search(8) 

R e t u rn 

to  search(7) 

R e t u rn 

to  search(6) 

R e t u rn 

to  search(A) 

Call 

search(5) 

R e t u rn 

to  search{4) 

R e t u rn 
R e t u rn 
Call 
R e t u rn 

to  search(S) 
to 
search(l) 
search(2) 
to 

search(l) 

Node  1  has  two  successors.  Suppose  s  —  3  is  consid 
ered  first;  add  edge  1  —>•  3  to  T. 
Add  edge  3  ->•  4  to  T. 
Node  4  has  two  successors,  4  and  6.  Suppose  s  —  6  is 
considered  first;  add  edge  4  —>  6  to  T. 
Add  6  -»  7  to  T. 
Node  7  has  two  successors,  4  and  8.  But  4  is  already 
marked  "visited"  by  search(A),  so  do  nothing  when 
s  =  4.  For  s  =  8,  add  edge  7  ->•  8  to  T. 
Node  8  has  two  successors,  9  and  10.  Suppose  s  =  10 
is  considered  first;  add  edge  8  —>  10. 
10  has  a  successor,  7,  but  7  is  already  marked 
Thus,  search(10)  completes  by  setting 
"visited." 
dfn[10]  =  10  and  c  =  9. 
Set  s  =  9  and  add  edge  8  ->•  9  to  T. 
T he  only  successor  of  9,  node  1,  is  already  "visited," 
so  set  dfn[9]  =  9  and  c  =  8. 
T he  last  successor  of  8,  node  3,  is  "visited,"  so  do 
nothing  for  s  =  3.  At  this  point,  all  successors  of  8 
have  been  considered,  so  set  dfn[8]  =  8  and  c  =  7. 
All  of  7's  successors  have  been  considered,  so  set 
dfn[7)  =  7  and  c  =  6. 
Similarly,  6's  successors  have  been  considered,  so  set 
dfn[6]  =  6  and  c  =  5. 
Successor  3  of  4  has  been  "visited,"  but  5  has  not,  so 
add  4  ->•  5  to  the  tree. 
Successor  7 of 5  has  been  "visited,"  thus  set  dfn[b]  =  5 
and  c  =  4. 
All successors of 4 have been considered,  set  dfn[4]  —  4 
and  c  =  3. 
Set  dfn[3]  =  3  and  c  =  2. 
2  has  not  been  visited  yet,  so  add  1  -»  2  to  T. 
Set  dfn[2]  =  2,  c  =  1. 
Set  rf/n[l]  =  1  and  c  =  0. 

Figure  9.44:  Execution  of  Algorithm  9.41  on  the  flow  graph  in  Fig.  9.43 

664 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

Why  Are  Back  Edges  Retreating  Edges? 

Suppose  a  —>  b  is  a  back  edge;  i.e.,  its  head  dominates  its  tail.  The 
sequence  of  calls  of  the  function  search  in  Fig.  9.43  t h at  lead  to  node  a 
must  be  a  p a th  in  the  flow  graph.  This  p a th  must,  of  course,  include  any 
dominator  of  a. 
It  follows  t h at  a  call  to  search(b)  must  be  open  when 
search(a)  is  called.  Therefore  b  is  already  in  the  tree  when  a  is  added  to 
b  must  be  a 
t he  tree,  and  o  is  added  as  a  descendant  of  b.  Therefore,  a 
retreating  edge. 

those  are  exactly  the  back  edges  in  the  graph. 
If  t he  graph  is  nonreducible 
(not  reducible),  however,  all  the  back  edges  are  retreating  edges  in  any  D F S T, 
but  each  D F ST  may  have  additional  retreating  edges  t h at  are  not  back  edges. 
These  retreating  edges  may  be  different  from  one  D F ST  to  another.  Thus,  if 
we  remove  all  the  back  edges  of  a  flow  graph  and  the  remaining  graph  is  cyclic, 
then  the  graph  is  nonreducible,  and  conversely. 

Flow  graphs  t h at  occur  in  practice  are  almost  always  reducible.  Exclusive 
use  of  structured  flow-of-control  statements  such  as  if-then-else,  while-do,  con 
tinue,  and  break  statements  produces  programs  whose  flow  graphs  are  always 
reducible.  Even  programs  written  using  goto  statements  often  t u rn  out  to  be 
reducible,  as  the  programmer  logically  thinks  in  terms  of loops  and  branches. 

E x a m p le  9 . 4 3:  The  flow  graph  of Fig.  9.38  is  reducible.  T he  retreating  edges 
in  the  graph  are  all  back  edges;  t h at  is,  their  heads  dominate  their  respective 
tails. 

• 

E x a m p le  9 . 4 4:  Consider  the  flow  graph  of  Fig.  9.45,  whose  initial  node  is  1. 
Node  1  dominates  nodes  2  and  3,  but  2  does  not  dominate  3,  nor  vice-versa. 
Thus,  this flow graph  has  no  back  edges,  since  no  head  of any  edge  dominates  its 
tail.  There  are  two  possible  depth-first  spanning  trees,  depending  on  whether 
we  choose  to  call  search(2)  or  search(3)  first,  from  search(l).  In  the  first  case, 
3 
edge  3  -»  2  is  a  retreating  edge  but  not  a  back  edge;  in  the  second  case,  2 
is  t he  retreating-but-not-back  edge. 
Intuitively,  t he  reason  this  flow  graph  is 
not  reducible  is  t h at  t he  cycle  2-3  can  be  entered  at  two  different  places,  nodes 
2  a nd  3. 

• 

Figure  9.45:  The  canonical  nonreducible  flow  graph 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

665 

9.6.5  Depth  of  a  Flow  Graph 

Given  a  depth-first  spanning  tree  for  the  graph,  the  depth  is  t he  largest  number 
of  retreating  edges  on  any  cycle-free  path.  We  can  prove  t he  depth  is  never 
greater  t h an  what  one  would  intuitively  call  the  depth  of  loop  nesting  in  the 
flow  graph.  If  a  flow  graph  is  reducible,  we  may  replace  "retreating"  by  "back" 
in  t he  definition  of  "depth,"  since  the  retreating  edges  in  any  D F ST  are  exactly 
the  back  edges.  The  notion  of  depth  then  becomes  independent  of  the  D F ST 
actually  chosen,  and  we  may  truly  speak  of the  "depth  of  a  flow  graph,"  rather 
t h an  t he  depth  of a  flow  graph  in  connection  with  one  of its  depth-first  spanning 
trees. 

E x a m p le  9 . 4 5:  In  Fig.  9.42,  the  depth  is  3,  since  there  is  a  p a th 

10  ->  7  -)>  4  ->•  3 

with  three  retreating  edges,  but  no  cycle-free  p a th  with  four  or  more  retreating 
It  is  a  coincidence  t h at  t he  "deepest"  p a th  here  has  only  retreating 
edges. 
edges;  in  general  we  may  have  a  mixture  of  retreating,  advancing,  and  cross 
edges  in  a  deepest  path. 

• 

9.6.6  Natural  Loops 

Loops  can  be  specified  in  a  source  program  in  many  different  ways:  they  can  be 
written  as  for-loops,  while-loops,  or  repeat-loops;  they  can  even  be  defined  using 
labels  and  goto  statements.  From  a  program-analysis  point  of  view,  it  does  not 
m a t t er  how  the  loops  appear  in  the  source  code.  W h at  m a t t e rs  is  whether  they 
have  the  properties  t h at  enable  easy  optimization.  In  particular,  we  care  about 
whether  a  loop  has  a  single-entry  node;  if  it  does,  compiler  analyses  can  assume 
certain  initial  conditions  to  hold  at  the  beginning  of  each  iteration  through  t he 
loop.  This  opportunity  motivates  the  need  for  the  definition  of a  "natural  loop." 

A  natural  loop  is  defined  by  two  essential  properties. 

1.  It  must  have  a  single-entry  node,  called  the  header.  This  entry  node 
dominates  all  nodes  in  the  loop,  or  it  would  not  be  the  sole  entry  to  the 
loop. 

2.  There  must  be  a  back  edge  t h at  enters  the  loop  header.  Otherwise,  it  is 
not  possible  for  the  flow  of  control  to  return  to  t he  header  directly  from 
the  "loop";  i.e.,  there  really  is  no  loop. 

Given  a  back  edge  n  ->•  d,  we  define  the  natural  loop  of  the  edge  to  be  d 

plus  the  set  of  nodes  t h at  can  reach  n  without  going  through  d.  Node  d  is  the 
header  of  the  loop. 

A l g o r i t hm  9.46  :  Constructing  the  natural  loop  of  a  back  edge. 

I N P U T:  A  flow  graph  G  and  a  back  edge  n  ->  d. 

666 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

O U T P U T:  T he  set  loop  consisting  of  all  nodes  in  the  natural  loop  of n  ->  d. 

M E T H O D:  Let  loop  be  {n,  d}.  Mark  d  as  "visited,"  so  t h at  the  search  does  not 
reach  beyond  d.  Perform  a  depth-first  search  on  the  reverse  control-flow  graph 
starting  with  node  n.  Insert  all  the  nodes  visited  in  this  search  into  loop.  This 
procedure  finds  all  the  nodes  t h at  reach  n  without  going  through  d. 

• 

In  Fig.  9.38,  there  are  five  back  edges,  those  whose  heads 
E x a m p le  9 . 4 7: 
1.  Note  t h at 
dominate  their  tails:  10 
these  are  exactly  the  edges  t h at  one  would  think  of  as  forming  loops  in  the  flow 
graph. 

7,  7  -+  4,  4  -»  3,  8  ->•  3  and  9 

Back  edge  10  ->  7  has  natural  loop  { 7 , 8 , 1 0 },  since  8  and  10  are  the  only 
nodes  t h at  can  reach  10  without  going  through  7.  Back  edge  7  ->  4  has  a 
natural  loop  consisting  of  { 4 , 5 , 6 , 7 , 8 , 1 0}  and  therefore  contains  the  loop  of 
10  —>•  7.  We  thus  assume  t he  latter  is  an  inner  loop  contained  inside  t he  former. 
3  and  8  ->•  3  have  t he  same  header, 
node  3,  and  they  also  happen  to  have  the  same  set  of nodes:  { 3 , 4 , 5 , 6 , 7 , 8 , 1 0 }. 
We  shall  therefore  combine  these  two  loops  as  one.  This  loop  contains  the  two 
smaller  loops  discovered  earlier. 

T he  natural  loops  of  back  edges  4 

Finally,  the  edge  9  ->  1  has  as  its  natural  loop  the  entire  flow  graph,  and 
therefore  is  the  outermost  loop. 
In  this  example,  t he  four  loops  are  nested 
within  one  another.  It  is  typical,  however,  to  have  two  loops,  neither  of  which 
is  a  subset  of  the  other. 

• 

In  reducible  flow  graphs,  since  all  retreating  edges  are  back  edges,  we  can 
associate  a  natural  loop  with  each  retreating  edge.  T h at  statement  does  not 
hold  for  nonreducible  graphs.  For  instance,  the  nonreducible  flow  graph  in 
Fig.  9.45  has  a  cycle  consisting  of  nodes  2  and  3.  Neither  of  t he  edges  in  t he 
cycle  is  a  back  edge,  so  this  cycle  does  not  fit  t he  definition  of  a  natural  loop. 
We  do  not  identify  the  cycle  as  a  natural  loop,  and  it  is  not  optimized  as  such. 
This  situation  is  acceptable,  because  our  loop  analyses  can  be  made  simpler  by 
assuming  t h at  all  loops  have  single-entry  nodes,  and  nonreducible  programs  are 
rare  in  practice  anyway. 

By  considering  only  natural  loops  as  "loops,"  we  have  the  useful  property 
t h at  unless  two  loops  have  the  same  header,  they  are  either  disjoint  or  one  is 
nested  within  the  other.  Thus,  we  have  a  natural  notion  of  innermost  loops: 
loops  t h at  contain  no  other  loops. 

When  two  natural  loops  have  the  same  header,  as  in  Fig.  9.46,  it  is  hard  to 
tell  which  is  the  inner  loop.  Thus,  we  shall  assume  t h at  when  two  natural  loops 
have  t he  same  header,  and  neither  is  properly  contained  within  the  other,  they 
are  combined  and  treated  as  a  single  loop. 

E x a m p le  9 . 4 8:  T he  natural  loops  of  the  back  edges  3  -»•  1  and  4  ->  1  in 
Fig.  9.46  are  { 1 , 2 , 3}  and  { 1 , 2 , 4 },  respectively.  We  shall  combine  t h em  into  a 
single  loop,  { 1 , 2 , 3 , 4 }. 

However,  were  there  another  back  edge  2  ->  1  in  Fig.  9.46,  its  natural 
loop  would  be  {1,  2 },  a  third  loop  with  header  1.  This  set  of  nodes  is  properly 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

667 

Figure  9.46:  Two  loops  with  the  same  header 

contained  within  {1,  2 , 3 , 4 },  so  it  would  not  be  combined  with  the  other  natural 
loops,  b ut  rather  treated  as  an  inner  loop,  nested  within. 

• 

9.6.7  Speed  of  Convergence  of Iterative  Data-Flow 

Algorithms 

We  are  now  ready  to  discuss  the  speed  of  convergence  of  iterative  algorithms. 
As  discussed  in  Section  9.3.3,  t he  maximum  number  of  iterations  t he  algorithm 
may  take  is  the  product  of  the  height  of  the  lattice  and  the  number  of  nodes 
in  the  flow  graph.  For  many  data-flow  analyses,  it  is  possible  to  order  the 
evaluation  such  t h at  the  algorithm  converges  in  a  much  smaller  number  of 
iterations.  T he  property  of  interest  is  whether  all  events  of  significance  at  a 
node  will  be  propagated  to  t h at  node  along  some  acyclic  p a t h.  Among  t he 
data-flow  analyses  discussed  so  far,  reaching  definitions,  available  expressions 
and  live  variables  have  this  property,  b ut  constant  propagation  does  not.  More 
specifically: 

•  If  a  definition  d  is  in  IN[.£?],  then  there  is  some  acyclic  p a th  from  the  block 
containing  d  to  B  such  t h at  d  is  in  the  iN's  and  OUT's  all  along  t h at  p a t h. 

•  If  an  expression  x  +  y  is  not  available  at  the  entrance  to  block  B,  then 
there  is  some  acyclic  p a th  t h at  demonstrates  t h at  either  t he  p a th  is  from 
the  entry  node  and  includes  no  statement  t h at  kills  or  generates  x  + y,  or 
the  p a th  is  from  a  block  t h at  kills  x  +  y  and  along  the  p a th  there  is  no 
subsequent  generation  of  x  +  y. 

•  If  x  is  live  on  exit  from  block  B,  then  there  is  an  acyclic  p a th  from  B  to 

a  use  of  x,  along  which  there  are  no  definitions  of  x. 

We  should  check  t h at  in  each  of these  cases,  p a t hs  with  cycles  add  nothing.  For 
example,  if  a  use  of  x  is  reached  from  the  end  of  block  B  along  a  p a th  with  a 
cycle,  we  can  eliminate  t h at  cycle  to  find  a  shorter  p a th  along  which  the  use  of 
x  is  still  reached  from  B. 

In  contrast,  constant  propagation  does  not  have  this  property.  Consider  a 

simple  program  t h at  has  one  loop  containing  a  basic  block  with  statements 

668 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

L: 

a = b 

b = c 
c  =  1 
goto L 

The  first  time  the  basic  block  is  visited,  c  is  found  to  have  constant  value  1,  but 
both  a  and  b  are  undefined.  Visiting  the  basic  block  the  second  time,  we  find 
t h at  b  and  c  have  constant  values  1.  It  takes  three  visits  of  the  basic  block  for 
the  constant  value  1  assigned  to  c  to  reach  a. 

If all  useful  information  propagates  along  acyclic  paths,  we  have  an  opportu 
nity  to  tailor  the  order  in  which  we  visit  nodes  in  iterative  data-flow  algorithms, 
so  t h at  after  relatively  few  passes  through  the  nodes  we  can  be  sure  information 
has  passed  along  all  the  acyclic  p a t h s. 

Recall  from  Section  9.6.3  t h at  if  a  ->•  b  is  an  edge,  then  the  depth-first 
number  of  b  is  less  t h an  t h at  of  a  only  when  the  edge  is  a  retreating  edge.  For 
forward  data-flow  problems,  it  is  desirable  to  visit  the  nodes  according  to  the 
depth-first  ordering.  Specifically,  we  modify  the  algorithm  in  Fig.  9.23(a)  by 
replacing  line  (4),  which  visits  the  basic  blocks  in  the  flow  graph  with 

for  (each  block  B  other  t h an  E N T R Y,  in  depth-first  order)  { 

E x a m p le  9.49  :  Suppose  we  have  a  p a th  along  which  a  definition  d  propagates, 
such  as 

3 

5  -)>  19  -»  35  ->  16  -+  23  -+  45  -+  4  ->  10 

17 

where  integers  represent  the  depth-first  numbers  of  the  blocks  along  the  p a t h. 
Then  the  first  time  through  the  loop  of lines  (4)  through  (6)  in  the  algorithm  in 
Fig.  9.23(a),  d  will  propagate  from  OUT[3]  to  IN[5]  to  OUT[5],  and  so  on,  up  to 
OUT[35].  It  will  not  reach  IN[16]  on  t h at  round,  because  as  16  precedes  35,  we 
had  already  computed  IN[16]  by  the  time  d  was  put  in  OUT[35].  However,  t he 
next  time  we  run  through  the  loop  of  lines  (4)  through  (6),  when  we  compute 
IN[16],  d will  be  included  because  it  is  in  OUT[35].  Definition  d  will  also  propa 
gate  to  OUT[16],  IN[23],  and  so  on,  up  to  OUT[45],  where  it  must  wait  because 
IN[4]  was  already  computed  on  this  round.  On  t he  third  pass,  d  travels  to  IN[4], 
OUT[4],  IN[10],  OUT[10],  and  IN[17],  so  after  three  passes  we  establish  t h at  d 
reaches  block  17. 

• 

It  should  not  be  hard  to  extract  the  general  principle  from  this  example.  If 
we  use  depth-first  order  in  Fig.  9.23(a),  then  the  number  of  passes  needed  to 
propagate  any  reaching  definition  along  any  acyclic  p a th  is  no  more  t h an  one 
greater  t h an  the  number  of  edges  along  t h at  p a th  t h at  go  from  a  higher  num 
bered  block  to  a  lower  numbered  block.  Those  edges  are  exactly  t he  retreating 
edges,  so  the  number  of  passes  needed  is  one  plus  the  depth.  Of  course  Algo 
rithm  9.11  does  not  detect  the  fact  t h at  all  definitions  have  reached  wherever 
they  can  reach,  until  one  more  pass  has  yielded  no  changes.  Therefore,  the 
upper  bound  on  the  number  of  passes  taken  by  t h at  algorithm  with  depth-first 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

669 

A  Reason  for  Nonreducible  Flow  Graphs 

There  is  one  place  where  we  cannot  generally  expect  a  flow  graph  to  be 
If  we  reverse  the  edges  of  a  program  flow  graph,  as  we  did 
reducible. 
in  Algorithm  9.46  to  find  n a t u r al  loops,  then  we  may  not  get  a  reducible 
flow  graph.  T he  intuitive  reason  is  t h a t,  while  typical  programs  have  loops 
with  single  entries,  those  loops  sometimes  have  several  exits,  which  become 
entries  when  we  reverse  the  edges. 

block  ordering  is  actually  two  plus  t he  depth.  A  s t u d y10  has  shown  t h at  typical 
flow  graphs  have  an  average  depth  around  2.75.  Thus,  the  algorithm  converges 
very  quickly. 

In  the  case  of backward-flow  problems,  like  live  variables,  we  visit  the  nodes 
in  the  reverse  of  the  depth-first  order.  Thus,  we  may  propagate  a  use  of  a 
variable  in  block  17  backwards  along  the  p a th 

3  ->  5 

19  ->•  35 

16 

23  ->  45 

4  ->  10 

17 

in  one  pass  to  IN [4],  where  we  must  wait  for  the  next  pass  in  order  to  reach 
OUT[45].  On  the  second  pass  it  reaches  IN[16],  and  on  the  third  pass  it  goes 
from  OUT[35]  to  OUT[3]. 

In  general,  one-plus-the-depth  passes  suffice  to  carry  the  use  of  a  variable 
backward,  along  any  acyclic  p a t h.  However,  we  must  choose  the  reverse  of 
depth-first  order  to  visit  the  nodes  in  a  pass,  because  then,  uses  propagate 
along  any  decreasing  sequence  in  a  single  pass. 

T he  bound  described  so  far  is  an  upper  bound  on  all  problems  where  cyclic 
In  special  problems  such  as  domi 
p a t hs  add  no  information  to  the  analysis. 
nators,  the  algorithm  converges  even  faster.  In  the  case  where  the  input  flow 
graph  is  reducible,  the  correct  set  of  dominators  for  each  node  is  obtained  in 
t he  first  iteration  of  a  data-flow  algorithm  t h at  visits  the  nodes  in  depth-first 
ordering.  If  we  do  not  know  t h at  the  input  is  reducible  ahead  of  time,  it  takes 
an  extra  iteration  to  determine  t h at  convergence  has  occurred. 

9.6.8  Exercises  for  Section  9.6 

E x e r c i se  9 . 6 . 1:  For  the  flow  graph  of  Fig.  9.10  (see  the  exercises  for  Sec 
tion  9.1): 

i.  Compute  the  dominator  relation. 

ii.  Find  t he  immediate  dominator  of  each  node. 

1 0D.  E.  Knuth,  "An  empirical  study  of  FORTRAN  programs,"  Software  —  Practice  and 

Experience  1:2  (1971),  pp.  105-133. 

670 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

Hi.  Construct  the  dominator  tree. 

iv.  Find  one  depth-first  ordering  for  the  flow  graph. 

v.  Indicate  the  advancing,  retreating,  cross,  and  tree  edges  for  your  answer 

to  iv. 

vi.  Is  t he  flow  graph  reducible? 

vii.  Compute  the  depth  of  the  flow  graph. 

viii.  Find  the  natural  loops  of  the  flow  graph. 

E x e r c i se  9 . 6 . 2:  Repeat  Exercise  9.6.1  on  the  following  flow  graphs: 

a)  Fig.  9.3. 

b)  Fig.  8.9. 

c)  Your  flow  graph  from  Exercise  8.4.1. 

d)  Your  flow  graph  from  Exercise  8.4.2. 

!  E x e r c i se  9 . 6 . 3:  Prove  the  following  about  the  dom  relation: 

a)  If  a  dom  b  and  b  dom  c,  then  a  dom  c  (transitivity). 

b)  It  is  never  possible  t h at  both  a  dom  b  and  b  dom  a  hold,  if  a  ^  b  (anti 

symmetry) 

. 

c)  If  a  and  b  are  two  dominators  of  n,  then  either  a  dom  b  or  b  dom  a  must 

hold. 

d)  Each  node  n  except  the  entry  has  a  unique  immediate  dominator  —  t he 
dominator  t h at  appears  closest  to  n  along  any  acyclic  p a th  from  the  entry 
to  n. 

!  E x e r c i se  9 . 6. 4:  Figure  9.42  is  one  depth-first  presentation  of the  flow  graph  of 
Fig.  9.38.  How  many  other  depth-first  presentations  of this  flow  graph  are  there? 
Remember,  order  of children  m a t t e rs  in  distinguishing  depth-first  presentations. 

!!  E x e r c i se  9 . 6 . 5:  Prove  t h at  a  flow  graph  is  reducible  if  and  only  if  when  we 
remove  all  the  back  edges  (those  whose  heads  dominate  their  tails),  t he  resulting 
flow  graph  is  acyclic. 

!  E x e r c i se  9 . 6 . 6:  A  complete  flow  graph  on  n  nodes  has  arcs  i  ->  j  between 
any  two  nodes  i  and  j  (in  both  directions).  For  what  values  of  n  is  this  graph 
reducible? 

!  E x e r c i se  9 . 6 . 7:  A  complete,  acyclic  flow  graph  on  n  nodes  1 , 2 , . ..  ,  n  has  arcs 

i  -»  j  for  all  nodes  i  and  j  such  t h at  i  <  j.  Node  1  is  the  entry. 

9.6. 

LOOPS  IN  FLOW  GRAPHS 

671 

a)  For  what  values  of  n  is  this  graph  reducible? 

b)  Does  your  answer  to  (a)  change  if  you  add  self-loops  i  -+  i  for  all  nodes 

i? 

! Exercise  9 . 6 . 8:  The  natural  loop  of  a  back  edge  n  -+  h  was  defined  to  be  h 
plus  t he  set  of  nodes  t h at  can  reach  n  without  going  through  h.  Show  t h at  h 
dominates  all  the  nodes  in  the  natural  loop  of  n  -+  h. 

!! Exercise  9 . 6 . 9:  We  claimed  t h at  the  flow  graph  of Fig.  9.45  is  nonreducible. 
If  t he  arcs  were  replaced  by  paths  of  disjoint  nodes  (except  for  the  endpoints, 
of  course),  then  t he  flow  graph  would  still  be  nonreducible. 
In  fact,  node  1 
need  not  be  the  entry;  it  can  be  any  node  reachable  from  the  entry  along  a 
p a th  whose  intermediate  nodes  are  not  part  of  any  of  the  four  explicitly  shown 
paths.  Prove  the  converse:  t h at  every  nonreducible  flow  graph  has  a  subgraph 
like  Fig.  9.45,  but  with  arcs  possibly  replaced  by  node-disjoint  paths  and  node  1 
being  any  node  reachable  from  the  entry  by  a  p a th  t h at  is  node-disjoint  from 
the  four  other  paths. 

'.! Exercise  9 . 6 . 1 0:  Show  t h at  every  depth-first  presentation  for  every  nonre 

ducible  flow  graph  has  a  retreating  edge  t h at  is  not  a  back  edge. 

!! Exercise  9 . 6 . 1 1:  Show  t h at  if the  following condition 

f(a)Ag(a)Aa<f(g(a)) 

holds  for  all  functions  /  and g,  and  value  a,  then  the  general  iterative  algorithm, 
Algorithm  9.25,  with  iteration  following  a  depth-first  ordering,  converges  within 
2-plus-the-depth  passes. 

! Exercise  9 . 6 . 1 2:  Find  a  nonreducible  flow  graph  with  two  different  D F S T 's 

t h at  have  different  depths. 

! Exercise  9 . 6 . 1 3:  Prove the  following: 

a)  If a  definition  d  is  in  IN [B],  then  there  is  some  acyclic  p a th  from  the  block 
containing  d  to  B  such  t h at  d  is  in  the  I N's  and  O U T's  all  along  t h at  path. 

b)  If  an  expression  x  +  y  is  not  available  at  the  entrance  to  block  B,  then 
there  is  some  acyclic  p a th  t h at  demonstrates  t h at  fact;  either  the  p a th 
is  from  the  entry  node  and  includes  no  statement  t h at  kills  or  generates 
x + y,  or  the  p a th  is  from  a  block  t h at  kills  x + y  and  along  the  p a th  there 
is  no  subsequent  generation  of  x  +  y. 

c)  If  x  is  live  on  exit  from  block  B,  then  there  is  an  acyclic  p a th  from  B  to 

a  use  of  x,  along  which  there  are  no  definitions  of  x. 

672 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

9.7  Region-Based  Analysis 

The  iterative  data-flow  analysis  algorithm  we  have  discussed  so  far  is  just  one 
approach  to  solving  data-flow  problems.  Here  we  discuss  another  approach 
called  region-based  analysis.  Recall  t h at  in  the  iterative-analysis  approach,  we 
create  transfer  functions  for  basic  blocks,  then  find  t he  fixedpoint  solution  by 
repeated  passes  over  the  blocks.  Instead  of  creating  transfer  functions  just  for 
individual  blocks,  a  region-based  analysis  finds  transfer  functions  t h at  summa 
rize  the  execution  of  progressively  larger  regions  of  the  program.  Ultimately, 
transfer  functions  for  entire  procedures  are  constructed  and  then  applied,  to  get 
the  desired  data-flow  values  directly. 

While  a  data-flow  framework  using  an  iterative  algorithm  is  specified  by 
a  semilattice  of  data-flow  values  and  a  family  of  transfer  functions  closed  un 
der  composition,  region-based  analysis  requires  more  elements.  A  region-based 
framework  includes  b o th  a  semilattice  of  data-flow  values  and  a  semilattice 
of  transfer  functions  t h at  must  possess  a  meet  operator,  a  composition  oper 
ator,  and  a  closure  operator.  We  shall  see  what  all  these  elements  entail  in 
Section  9.7.4. 

A  region-based  analysis  is  particularly  useful  for  data-flow  problems  where 
paths  t h at  have  cycles  may  change  t he  data-flow  values.  T he  closure  operator 
allows  the  effect  of a  loop  to  be  summarized  more  effectively  t h an  does  iterative 
analysis.  T he  technique  is  also  useful  for  interprocedural  analysis,  where  trans 
fer  functions  associated  with  a  procedure  call  may  be  treated  like  t he  transfer 
functions  associated  with  basic  blocks. 

For  simplicity,  we  shall  consider  only  forward  data-flow  problems  in  this 
section.  We  first  illustrate  how  region-based analysis  works  by  using t he  familiar 
example  of  reaching  definitions.  In  Section  9.8  we  show  a  more  compelling  use 
of  this  technique,  when  we  study  the  analysis  of  induction  variables. 

9.7.1  Regions 

In  region-based  analysis,  a  program  is  viewed  as  a  hierarchy  of  regions,  which 
are  (roughly)  portions  of  a  flow  graph  t h at  have  only  one  point  of  entry.  We 
should  find  this  concept  of  viewing  code  as  a  hierarchy  of  regions  intuitive, 
because  a  block-structured  procedure  is  naturally  organized  as  a  hierarchy  of 
regions.  Each  statement  in  a  block-structured  program  is  a  region,  as  control 
flow  can  only  enter  at  the  beginning  of  a  statement.  Each  level  of  statement 
nesting  corresponds  to  a  level  in  the  region  hierarchy. 

Formally,  a  region  of  a  flow  graph  is  a  collection  of  nodes  N  and  edges  E 

such  t h at 

1.  There  is  a  header  h  in  N  t h at  dominates  all  t he  nodes  in  N. 

2.  If  some  node  m  can  reach  a  node  n  in  N  without  going  through  h,  then 

m  is  also  in  N. 

9.7. 

REGION-BASED  ANALYSIS 

673 

3.  E  is  t he  set  of  all  t he  control  flow  edges  between  nodes  n\  and  n2  in  N, 

except  (possibly)  for  some  t h at  enter  h. 

E x a m p le  9 . 5 0:  Clearly  a  natural  loop  is  a  region,  but  a  region  does  not 
necessarily  have  a  back  edge  and  need  not  contain  any  cycles.  For  example,  in 
Fig.  9.47,  nodes  B\  and  B2,  together  with  t he  edge  B\  —>  B2:  form  a  region;  so 
do  nodes  Bi,B2,  and  B3  with  edges  Bx 

B2,  B2  ->•  B3,  and  Bi  ->  B3. 

However,  the  subgraph  with  nodes  B2  and #3  with  edge  B2  —>  B3  does  not 
form  a  region,  because  control  may  enter  t he  subgraph  at  b o th  nodes  B2  and 
B3.  More  precisely,  neither  B2  nor  B3  dominates  the  other,  so  condition  (1)  for 
a  region  is  violated.  Even  if  we  picked,  say,  B2  to  be  the  "header,"  we  would 
violate  condition  (2),  since  we  can  reach  B3  from  B\  without  going  through  B2, 
and  J5i  is  not  in  the  "region." 

• 

(ENTRY) 

Figure  9.47:  Examples  of  regions 

9.7.2  Region  Hierarchies  for  Reducible  Flow  Graphs 

In  what  follows,  we  shall  assume  the  flow  graph  is  reducible.  If  occasionally  we 
must  deal  with  nonreducible  flow  graphs,  then  we  can  use  a  technique  called 
"node  splitting"  t h at  will  be  discussed  in  Section  9.7.6. 

To  construct  a  hierarchy  of  regions,  we  identify  t he  natural  loops.  Recall 
from  Section  9.6.6  t h at  in  a  reducible  flow  graph,  any  two  n a t u r al  loops  are 
either  disjoint  or  one  is  nested  within  the  other.  The  process  of  "parsing"  a 
reducible  flow  graph  into  its  hierarchy  of  loops  begins  with  every  block  as  a 
region  by  itself.  We  call  these  regions  leaf  regions.  Then,  we  order  t he  natural 
loops  from  t he  inside  out,  i.e.,  starting  with  the  innermost  loops.  To  process  a 
loop,  we  replace  t he  entire  loop  by  a  node  in  two  steps: 

1.  First,  the  body  of the  loop  L  (all  nodes  and  edges  except  the  back  edges  to 
the  header)  is  replaced  by  a  node  representing  a  region  R.  Edges  to  the 
header  of  L  now  enter  t he  node  for  R.  An  edge  from  any  exit  of loop  L  is 
replaced  by  an  edge  from  R  to  t he  same  destination.  However,  if t he  edge 
is  a  back  edge,  then  it  becomes  a  loop  on  R.  We  call  R  a  body  region. 

674 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

2.  Next,  we  construct  a  region  R'  t h at  represents  the  entire  natural  loop  L. 
We  call  R'  a  loop  region.  T he  only  difference  between  R  and  R'  is  t h at 
the  latter  includes  the  back  edges  to  the  header  of  loop  L.  P ut  another 
way,  when  R'  replaces  R  in  the  flow  graph,  all  we  have  to  do  is  remove 
the  edge  from  R  to  itself. 

We  proceed  this  way,  reducing  larger  and  larger  loops  to  single  nodes,  first  with 
a  looping  edge  and  then  without.  Since  loops  of  a  reducible  flow  graph  are 
nested  or  disjoint,  the  loop  region's  node  can  represent  all  the  nodes  of  the 
natural  loop  in  t he  series  of flow graphs  t h at  are  constructed  by  this  reduction 
process. 

Eventually,  all  natural  loops  are  reduced  to  single  nodes.  At  t h at  point, 
the  flow  graph  may  be  reduced  to  a  single  node,  or  there  may  be  several  nodes 
remaining,  with  ho  loops;  i.e.,  t he  reduced  flow  graph  is  an  acyclic  graph  of 
more  t h an  one  node. 
In  the  former  case  we  are  done  constructing  t he  region 
hierarchy,  while  in  the  latter  case,  we  construct  one  more  body  region  for  the 
entire  flow  graph. 

E x a m p le  9 . 5 1:  Consider  the  control  flow  graph  in  Fig.  9.48(a).  There  is  one 
back  edge  in  this  flow  graph,  which  leads  from  B4  to  B2.  T he  hierarchy  of 
regions  is  shown  in  Fig.  9.48(b);  t he  edges  shown  are  the  edges  in  the  region 
flow  graphs.  There  are  altogether  8  regions: 

1.  Regions  Ri,... 

,R&  are  leaf  regions  representing  blocks  B\ 
respectively.  Every  block  is  also  an  exit  block  in  its  region. 

through  B$, 

2.  Body  region  RQ  represents  the  body  of t he  only  loop  in  the  flow  graph;  it 

consists  of  regions  R2,R3,  and  R4  and  three  interregion  edges:  B2  -»  B3, 
B2  -»  BA,  and  B3  ->  J54. 
It  has  two  exit  blocks,  B3  and  £?4,  since  they 
both  have  outgoing  edges  not  contained  in  the  region.  Figure  9.49(a) 
shows  the  flow  graph  with  R$  reduced  to  a  single  node.  Notice  t h at 
although  the  edges  R3  ->  R5  and  R4 -» -R5  have  b o th  been  replaced  by 
edge RQ -» #5,  it  is important to remember t h at  the latter edge represents 
the  two  former  edges,  since  we  shall  have  to  propagate  transfer  functions 
across  this  edge  eventually,  and  we  need  to  know  t h at  what  comes  out  of 
b o th  blocks  B3  and  B4  will  reach  t he  header  of  R$. 

3.  Loop  region  R7  represents  the  entire  natural  loop.  It  includes  one  subre-
gion,  RQ,  and  one  back  edge  B4  ->  B2.  It  has  also  two  exit  nodes,  again 
B3  and  B4.  Figure  9.49(b)  shows  t he  flow  graph  after  the  entire  natural 
loop  is  reduced  to  R7. 

4.  Finally,  body  region  R8  is  t he  top  region.  It  includes  three  regions,  R±, 
B5. 
R7,  R5  and  three  interregion  edges,  B\  ->  B2,  B3  -»  B5,  and  B4 
When  we  reduce  t he  flow  graph  to  R8,  it  becomes  a  single  node.  Since 
there  are  no  back  edges  to  its  header,  B±,  there  is  no  need  for  a  final  step 
reducing  this  body  region  to  a  loop  region. 

9.7. 

REGION-BASED  ANALYSIS 

675 

Figure  9.48: 
and  (b)  Its  region  hierarchy 

(a)  An  example  flow  graph  for  the  reaching  definitions  problem 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

676 

• 

(a) After reducing to 

(b) After reducing to 

a body region 

a loop region 

Fi  gure  9.49:  Steps  in  the  reduction  of  the  flow  graph  of  Fig.  9.47  to  a  single 
region 

To  summarize  the  process  of  decomposing  reducible  flow  graphs  hierarchi 

cally,  we  offer  t he  following  algorithm. 

A l g o r i t hm  9 . 5 2:  Constructing  a  bottom-up  order  of  regions  of  a  reducible 
flow  graph. 

I N P U T:  A  reducible flow graph  G. 

O U T P U T:  A  list  of  regions  of  G  t h at  can  be  used  in  region-based  data-flow 
problems. 

M E T H O D: 

1.  Begin  t he  list  with  all  the  leaf  regions  consisting  of  single  blocks  of  G,  in 

any  order. 

2.  Repeatedly  choose  a  natural  loop  L  such  t h at  if  there  are  any  natural 
loops  contained  within  L,  then  these  loops  have  had  their  body  and  loop 
regions  added  to  t he  list  already.  Add  first  the  region  consisting  of  the 
body  of  L  (i.e.,  L  without  the  back  edges  to  the  header  of  L),  and  then 
the  loop  region  of  L. 

3.  If  t he  entire  flow  graph  is  not  itself  a  natural  loop,  add  at  the  end  of  t he 

list  the  region  consisting  of  t he  entire  flow  graph. 

• 

9.7.3  Overview  of  a  Region-Based  Analysis 

For  each  region  R,  and  for  each  subregion  R'  within  R,  we  compute  a  transfer 
function  / R J N I J ? ']  t h at  summarizes  the  effect  of  executing  all  possible  paths 

9.7. 

REGION-BASED  ANALYSIS 

677 

Where  "Reducible"  Comes  From 

We  now  see  why  reducible  flow  graphs  were  given  t h at  name.  While  we 
shall  not  prove  this  fact,  the  definition  of  "reducible  flow  graph"  used  in 
this  book,  involving  t he  back  edges  of  the  graph,  is  equivalent  to  several 
definitions  in  which  we  mechanically  reduce  t he  flow  graph  to  a  single 
node.  T he  process  of  collapsing  natural  loops  described  in  Section  9.7.2 
is  one  of  them.  Another  interesting  definition  is  t h at  the  reducible  flow 
graphs  are  all  and  only  those  graphs  t h at  can  be  reduced  to  a  single  node 
by  the  following  two  transformations: 

T\\  Remove  an  edge  from  a  node  to  itself. 

T2:  If  node  n  has  a  single  predecessor  m,  and  n  is  not  the  entry  of  the 

flow  graph,  combine  m  and  n. 

leading  from  the  entry  of  R  to  the  entry  of  R',  while  staying  within  R.  We  say 
t h at  a  block  B  within  R  is  an  exit  block  of  region  R  if  it  has  an  outgoing  edge  to 
some  block  outside  R.  We  also  compute  a  transfer  function  for  each  exit  block 
B  of  R,  denoted 
/ f t , o U T[ . B ]>  t h at  summarizes  the  effect  of  executing  all  possible 
p a t hs  within  R,  leading  from  the  entry  of  R  to  t he  exit  of  B. 

We  then  proceed  up  the  region  hierarchy,  computing  transfer  functions  for 
progressively larger  regions.  We  begin  with  regions  t h at  are  single  blocks,  where 
is,IN[13]  is  Ju st  fne  identity  function  and  / B50U T[ B]  is  the  transfer  function  for 
t he  block  B  itself.  As  we  move  up  the  hierarchy, 

•  If  R  is  a  body  region,  then  the  edges  belonging  to  R  form  an  acyclic 
graph  on  the  subregions  of  R.  We  may  proceed  to  compute  the  transfer 
functions  in  a  topological  order  of  the  subregions. 

•  If  R  is  a  loop  region,  then  we  only  need  to  account  for  the  effect  of  t he 

back  edges  to  the  header  of  R. 

Eventually,  we  reach  the  top  of  the  hierarchy  and  compute  the  transfer 
functions  for  region  Rn  t h at  is  t he  entire  flow  graph.  How  we  perform  each  of 
these  computations  will  be  seen  in  Algorithm  9.53. 

The  next  step  is  to  compute  the  data-flow  values  at  the  entry  and  exit  of 
each  block.  We  process  the  regions  in  the  reverse  order,  starting  with  region 
Rn  and  working  our  way  down  the  hierarchy.  For  each  region,  we  compute  the 
data-flow  values  at  t he  entry.  For  region  Rn,  we  apply  /#n )iN[.R] ( I N [ E N T R Y ]) 
to  get  t he  data-flow  values  at  the  entry  of  the  subregions  R  in  Rn.  We  repeat 
until  we  reach  the  basic  blocks  at  the  leaves  of  the  region  hierarchy. 

678 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

9.7.4  Necessary  Assumptions  About  Transfer  Functions 

In  order  for  region-based  analysis  to  work,  we  need  to  make  certain  assumptions 
about  properties  of  the  set  of  transfer  functions  in  t he  framework.  Specifically, 
we  need  three  primitive  operations  on  transfer  functions:  composition,  meet 
and  closure;  only  the  first  is  required  for  data-flow  frameworks  t h at  use  the 
iterative  algorithm. 

C o m p o s i t i on 

The  transfer  function  of  a  sequence  of  nodes  can  be  derived  by  composing  the 
functions  representing  the  individual  nodes.  Let  /i  and  f2  be  transfer  functions 
of  nodes  n\  and  n2.  The  effect  of  executing  n\  followed  by  n2  is  represented 
by  f2  o  /]_.  Function  composition  has  been  discussed  in  Section  9.2.2,  and  an 
example  using  reaching  definitions  was  shown  in  Section  9.2.4.  To  review,  let 
gerii  and  kilk  be  the  gen  and  kill  sets  for 

Then: 

(kilh  U  kill2)) 

Thus,  t he  gen  and  kill  sets  for  f2°fi  a r eg e n2  U  (gen\—kill2)  and  kill\  U  kill2, 
respectively.  The  same  idea  works  for  any  transfer  function  of t he  gen-kill  form. 
Other  transfer  functions  may  also  be  closed,  but  we  have  to  consider  each  case 
separately. 

M e et 

Here,  t he  transfer  functions  themselves  are  values  of  a  semilattice  with  a  meet 
operator  A/.  The  meet  of  two  transfer  functions  /i  and  f2,  /i  A/  f2,  is  defined 
by  (/i  A/  fi){x)  =  fi(x)  A  f2(x),  where  A  is  the  meet  operator  for  data-flow 
values.  The  meet  operator  on  transfer  functions  is  used  to  combine  the  effect 
of  alternative  paths  of execution  with  t he  same  end  points.  Where  it  is  not  am 
biguous,  from  now  on,  we  shall  refer  to  t he  meet  operator  of  transfer  functions 
also  as  A.  For  t he  reaching-definitions  framework,  we  have 

( / i A /2) ( a O = / i ( a O A /2( aO 

=  (gen-i  U  (x  -  kilh))  U  (gen2  U  (x  -  kill2)) 

=  (geni  U  gen2)  U  (x  -  (kilh  D  kill2)) 

T h at  is,  t he  gen  and  kill  sets  for  /i  A  f2  are  gen\  U  gen2  and  killi  n  kill2, 
respectively.  Again,  the  same  argument  applies  to  any  set  of  gen-kill  transfer 
functions. 

9.7. 

REGION-BASED  ANALYSIS 

679 

C l o s u re 

If  /  represents  t he  transfer  function  of  a  cycle,  then  fn  represents  the  effect  of 
going  around  the  cycle  n  times.  In  the  case  where  the  number  of  iterations  is 
not  known,  we  have  to  assume  t h at  the  loop  may  be  executed  0  or  more  times. 
We  represent  t he  transfer  function  of  such  a  loop  by  / *,  the  closure  of  /,  which 
is  defined  by 

/* = A fn-

n>0 

Note  t h at  /°  must  be  the  identity  transfer  function,  since  it  represents  t he 
effect  of  going  zero  times  around  the  loop,  i.e.,  starting  at  the  entry  and  not 
moving.  If  we  let  /  represent  the  identity  transfer  function,  then  we  can  write 

r  = 

i A ( / \ n-
n>0 

Suppose  the  transfer  function  /  in  a  reaching  definitions  framework  has  a 

gen  set  and  a  kill  set.  Then, 

f(x)  = 

f(f(x)) 

=  (jgen  U  ((gen  U  (x  —  kill))  —  kilfj 

=  gen  U  (x  —  kill) 

f(x)=f(f(x)) 

=  gen  U  (x  —  kill) 

and  so  on:  any  fn(x)  is  gen  U  (x  —  kill).  T h at  is,  going  around  a  loop  doesn't 
affect  the  transfer  function,  if  it  is  of  t he  gen-kill  form.  Thus, 

r(x)^lAf1(x)Af(x)A... 

=  x  U  (gen  U  (x  —  kill)) 

= gen  U x 

Intuitively, 
T h at  is,  the  gen  and  kill  sets  for  /*  are  gen  and  0,  respectively. 
since  we  might  not  go  around  a  ioop  at  all,  anything  in  x  will  reach  the  entry 
to  t he  loop.  In  all  subsequent  iterations,  the  reaching  definitions  include  those 
in t he gen set. 

680 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

9.7.5  An  Algorithm  for  Region-Based  Analysis 

T he  following  algorithm  solves  a  forward  data-flow-analysis  problem  on  a  re 
ducible  flow  graph,  according  to  some  framework  t h at  satisfies  the  assumptions 
of  Section  9.7.4.  Recall  t h at  / R J N ^ ']  and  /j^ouTps] 
t h at  transform  data-flow  values  at  the  entry  to  region  R  into  t he  correct  value 
at  the  entry  of  subregion  R'  and  t he  exit  of  the  exit  block  B,  respectively. 

to  transfer  functions 

r efer 

A l g o r i t hm  9 . 5 3:  Region-based  analysis. 

I N P U T:  A  data-flow  framework  with  the  properties  outlined  in  Section  9.7.4 
and  a  reducible  flow  graph  G. 

O U T P U T:  Data-flow  values  m[B]  for  each  block  B  of  G. 

M E T H O D: 

1.  Use  Algorithm  9.52  to  construct  t he  b o t t o m - up  sequence  of  regions  of  G, 

say  Ri,  R2,... 

,Rn,  where  Rn 

is  t he  topmost  region. 

2.  Perform  the  b o t t o m - up  analysis  to  compute  the  transfer  functions  sum 
marizing  the  effect  of  executing  a  region.  For  each  region  Ri,  R2,... 
in  the  b o t t o m - up  order,  do  the  following: 

,Rn, 

(a)  If  R  is  a  leaf  region  corresponding  to  block  B,  let  / R J N [ . B]  — 

a nd 

/ H ,O U T [ B] 

=  / B,  the  transfer  function  associated  with  block  B. 

(b)  If  R  is  a  body  region,  perform  the  computation  of  Fig.  9.50(a). 

(c)  If  R  is  a  loop  region,  perform  t he  computation  of  Fig.  9.50(b). 

3.  Perform  the  top-down  pass  to  find  the  data-flow  values  at  the  beginning 

of  each  region. 

(a)  w[Rn]  = 

I N [ E N T R Y ]. 

(b)  For  each  region  R  in  {Ri,...  Rn-i},  in  the  top-down  order,  compute 

I N [JR] - / ^JIN [ J R ]( I N [JR ' ] ), 
where  R'  is  the  immediate  enclosing  region  of  R. 

Let  us  first  look  at  the  details  of  how  the  b o t t o m - up  analysis  works. 
In 
line  (1)  of Fig.  9.50(a)  we  visit  the  subregions  of a  body  region,  in  some  topolog 
ical  order.  Line  (2)  computes  the  transfer  function  representing  all  t he  possible 
p a t hs  from  the  header  of  R  to  the  header  of  S;  then  in  lines  (3)  and  (4)  we  com 
pute  the  transfer  functions  representing  all  t he  possible  p a t hs  from  t he  header 
of  R  to  the  exits  of  R  —  t h at  is,  to  the  exits  of  all  blocks  t h at  have  successors 
outside  S.  Notice  t h at  all  t he  predecessors  B'  in  R  must  be  in  regions  t h at 
precede  S  in  the  topological  order  constructed  at  line  (1).  Thus,  /#(OUT[jB'] 
will  have  been  computed  already,  in  line  (4)  of a  previous  iteration  through  t he 
outer  loop. 

9.7. 

REGION-BASED  ANALYSIS 

681 

For  loop  regions,  we  perform  the  steps  of lines  (1)  through  (4)  in  Fig.  9.50(b) 
Line  (2)  computes  the  effect  of  going  around  the  loop  b o dy  region  S  zero  or 
more  times.  Lines  (3)  and  (4)  compute  the  effect  at  the  exits  of  the  loop  after 
one  or  more  iterations. 

In  t he  top-down  pass  of  the  algorithm,  step  3(a)  first  assigns  t he  boundary 
condition  to  t he  input  of  t he  top-most  region.  T h en  if  R  is  immediately  con 
tained  in  R',  we  can  simply  apply  the transfer function  /#'5IN[JR]  to the  data-flow 
value  w[R']  to  compute  m[R]. 

• 

1)  for  (each  subregion  S  immediately  contained  in  R,  in 

topological  order)  { 

2) 

3) 

4) 

} 

IR,W[S]  =  Apredecessors  B  in  R  of t he  header  of  S  /fl.OUTps] 5 
/*  if  S  is  the  header  of  region  R,  then  / R J N [S]  is  the 

meet  over  nothing,  which  is  the  identity  function  */ 

for  (each  exit  block  B  in  S) 

/R,OVT[B] 

- 

/ s, O U T [ B] 

0 

/ R , I N [ S ]; 

(a)  Constructing  transfer  functions  for  a  body  region  R 

1) 

l et  S  be  the  body  region  immediately  nested  within  R]  t h at  is, 

S  is  R  without  back  edges  from  R  to  the  header  of  R; 

fR,W[S)  =  (Apredecessors  B  in  R  of  t he  header  of  S  /s,0UTp3])  5 

2) 
3)  for  (each  exit  block  B  in  R) 

4) 

/ f l , O U T[ B]  =  / s, O U T p 3]  °  /fl,IN[S]; 

(b)  Constructing  transfer  functions  for  a  loop  region  R' 

Figure  9.50:  Details  of  region-based  data-flow  computations 

E x a m p le  9.54  :  Let  us  apply  Algorithm  9.53  to  find  reaching  definitions  in  the 
flow  graph  in  Fig.  9.48(a).  Step  1  constructs  the  bottom-up  order  in  which  the 
regions  are  visited;  this  order  will  be  the  numerical  order  of  their  subscripts, 
R±,R2,... 

,  Rn. 

The  values  of the  gen  and  kill  sets  for  the  five  blocks  are  summarized  below: 

B 

genB 
kills 

Bi 
{di,d2,d3} 
{d4,d5,d6} 

B2 

B3 

{di} 

B4 
W 
{d2} 

B5 
0 
0 

Remember  the  simplified  rules  for  gen-kill  transfer  functions,  from  Section 
9.7.4: 

682 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

•  To  take  the  meet  of  transfer  functions,  take  the  union  of  t he  pen's  and 

t he  intersection  of  t he  kiWs. 

•  To  compose  transfer  functions,  take  t he  union  of  b o th  t he  pen's  and  t he 
kill's.  However,  as  an  exception,  an  expression  t h at  is  generated  by  the 
first  function,  not  generated  by  the  second,  b ut  killed  by  the  second  is  not 
in  the  gen  of  the  result. 

•  To  take  the  closure  of  a  transfer  function,  retain  its  gen  and  replace  t he 

kill  by  0. 

The  first  five  regions  Ri,... 

,  R5  are  blocks  B\,... 

,  B5,  respectively.  For 

1  <  i  <  5,  /Ri (iN[B.]  *s  *he  identity  function,  a nd  / / ji (o u T[ B i]  *s  t he  transfer 
function  for  block  Bi: 

fBi,OUT[Bi]{x) 

= 

{x- 

killBi)  U  genBi. 

Transfer  Function 

gen 

kill 

Re 

/ #6, I N[ f l2] 

= J 

/ i ?6, O U T[ B2] 

= 

/ f l2, O U T[ B2] 

0 

/ K6, I N [ K2] 

/.Re.INLRs] 

= 

/ f l6, O U T[ B2] 

/ i *6, O U T[ B3] 

//j6,IN[i?4] 

- 

/ f l3, O U T[ B3] 

0 

fR6,IN[R3] 

=  /i26,OUT[B2]  A / i i6, O U T[ B3] 

/ft6,OUTp34] 

=  /fl4,OUT[B4]  0 

/i?6,IN[R4] 

Rr 

fll7,IN 

[R6] 

= 

f*R6,0\JT[B4] 

/ #7, O U T[ B3] 

= 

/ j ?6, O U T[ B3]  ° 

fR7,IN[R6] 

/ K7, O U T [ B4] 

= 

/ i i6, O U T[ B4]  °  /fl7,IN[fl6] 

Rs 

/fl8,IN[«i] 

=  I 

/fl8,OUTp3i]  =  /flx.OUTtB!] 

/ #8, I N [ K7] 

/ n8, O U T[ B3] 

/ i ?8, O U T[ B4] 

= 

= 

= 

/ B8, O U T [ B I] 

/ B7, O U T [ B3] 

0 

/ K8, I N [ J ?7] 

/ R7, O U T [ B4] 

° / H8 )I N [JR7] 

/ H8 )I N [ f l5] 

= 

/ f l8, O U T[ B3] 

A 

/ f l8, O U T[ B4] 

0 
{ d4} 

{ci4} 

{ ^ 4 , ^ 5} 

{ d4,  d5} 

{dA,d,5,dQ} 

{d4,d5,de} 

{d4,dn,d6} 

{ d4, r f 5 , d e} 
0 
{dx,d2,da} 

{di,d2,ds} 

{d2,d4,d5,ds} 

{d3,d4,d5,d6} 

{d2,dz,d4,d5,d 

6} 

/ i ?8, O U T[ B5] 

=  ./fl8,OUT[BB]  0  /jR8,INp3B] 

{ ( ^ 2 , ^ 3 , ^ 4 , ^ 5 ,^  6} 

0 
{di} 

{di} 

{di:  dz} 

{di} 

0 
{rfi,rf3} 

{(2i,d2) 
0 
{d4,d5,d&} 

{d4,d5,d&} 

{di,ds} 

{di,d2} 

{di} 

{di} 

Figure  9.51:  Computing  transfer  functions  for  t he  flow  graph  in  Fig.  9.48(a), 
using  region-based  analysis 

T he  rest  of  t he  transfer  functions  constructed  in  Step  2  of  Algorithm  9.50 
are  summarized  in  Fig.  9.51.  Region  Re,  consisting  of  regions  R2,  R3,  and  R4, 

9.7. 

REGION-BASED  ANALYSIS 

683 

B2.  T he 
represents  t he  loop  body  and  thus  does  not  include  t he  back  edge  B4 
order  of  processing  these  regions  will  be  the  only  topological  order:  R2,R3,R4. 
First,  R2  has  no  predecessors  within  R6;  remember  t h at  the  edge  B4  -»  B2  goes 
outside  R6.  Thus,  / R6 )T N [ B2] 
transfer  function  for  block  B2  itself. 

ne  identity  function,11  and  /fl6,oUTp32] 

is  the 

is 

t

T he  header  of  region  B3  has  one  predecessor  within  R6:  namely  R2.  T he 
transfer  function  to  its  entry  is  simply  the  transfer  function  to  the  exit  of  B2, 
/ f i6, O U T [ B2]'  which  has  already  been  computed.  We  compose  this  function 
with  t he  transfer  function  of  B3  within  its  own  region  to  compute  t he  transfer 
function  to  the  exit  of  B3. 

Last,  for  t he  transfer  function  to  the  entry  of  R4,  we  must  compute 

/.Re.OUTpBa] 

A  /fl6,OUTp3s] 

because  b o th  B2  and  B3  are  predecessors  of  B4,  the  header  of  R4.  This  transfer 
function  is  composed  with  the  transfer  function  / i ?4, o U T[ B4]  to  get  t he  desired 
function /ij6,0UT[B4]-  Notice,  for  example,  t h at  d3  is  not  killed  in  this  transfer 
function,  because  the  p a th  B2  -»  B4  does  not  redefine  variable  a. 

Now,  consider  loop  region  R7. 

It  contains  only  one  subregion  RQ  which 
represents  its  loop  body.  Since  there  is  only  one  back  edge,  B4  —»•  B2,  to  the 
header  of RQ ,  the  transfer  function  representing  the  execution  of the  loop  body 
0  or  more  times  is  just 
set  is  0.  There  are  two  exits  out  of  region  R7,  blocks  B3  and  B4.  Thus,  this 
transfer  function  is  composed  with  each  of  the  transfer  functions  of  RQ  to  get 
the  corresponding  transfer  functions  of  R7.  Notice,  for  instance,  how  d6  is  in 
the  gen  set  for  fn.7,B3  because  of  paths  like  B2  ->•  B4  ->•  B2  -»  B3,  or  even 
B2  —>  B3  —y  B4 

s et  is  {d4,d^,do}  and  the  kill 

B2  —>  B3. 

o u T [ s4]: 

ne  9en 

t

Finally,  consider  R8,  the  entire  flow  graph.  Its  subregions  are  Ri,  R7,  and 
R5,  which  we  shall  consider  in  t h at  topological  order.  As  before,  the  transfer 
function  /fj8 )iN[jBi]  is  simply  the  identity  function,  and  the  transfer  function 
/.Rs.OUTpBi] 

cn  in  t u rn  is  fBl. 

/R I , O U T [ B! ],  w h

is  Ju st 

i

The  header  of  R7,  which  is  B2,  has  only  one  predecessor,  Bi,  so  the  transfer 
function  to  its  entry  is  simply  the  transfer  function  out  of  B\  in  region  R$. 
We  compose  / ^8 )o u T[ B i]  with  the  transfer  functions  to  the  exits  of  B3  and  B4 
within  R7  to  obtain  their  corresponding  transfer  functions  within  R8.  Lastly,  we 
consider  R5.  Its  header,  B5,  has  two  predecessors  within  R8,  namely  B3  and  B4. 
Therefore,  we  compute 
transfer  function  of  block  B5  is  the  identity  function,  / R8 )O UT[ B6]  —  fR8,lN[B5]-

fRs,0VT[B3)  A 

fR8,o\JT[B4] 

/ f l8 )i N[ BB]- 

to  get 

T HE 

CE 

N

S

I

Step  3  computes  the  actual  reaching  definitions  from  t he  transfer  functions. 
In  step  3(a),  m[R8]  =  0  since  there  are  no  reaching  definitions  at  t he  beginning 
of  the  program.  Figure  9.52  shows  how  step  3(b)  computes  the  rest  of  the 
data-flow  values.  T he  step  starts  with  t he  subregions  of  R8.  Since  the  transfer 
function  from  the  start  of  R8  to  the  start  of  each  of  its  subregion  has  been 

11 Strictly  speaking,  we  mean  fR&  j N[ R2]' 

b

ut  w h

en 

a  region  like  R2  is  a  single  block,  it  is 

often  clearer  if  we  use  the  block  name  rather  than  the  region  name  in  this  context. 

684 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

computed,  a  single  application  of the  transfer  function  finds  the  data-flow  value 
at  the  start  each  subregion.  We  repeat  the  steps  until  we  get  the  data-flow 
values  of  the  leaf  regions,  which  are  simply  the  individual  basic  blocks.  Note 
t h at  the  data-flow  values  shown  in  Figure  9.52  are  exactly  what  we  would  get 
had  we  applied  iterative  data-flow  analysis  to  the  same  flow  graph,  as  must  be 
the  case,  of  course. 

• 

INpRg]  =  0 

— 
m[R7]  — 
m[R5]  — 
m[R6]  — 
IN[R4]  — 
m[R3]  — 
IN [R2] 
= 

fRs,IN[R7 
/i?8,IN[fi5 

/R8 lIN[iEi  (m[R8}) 
(m[R8)) 
(m[R8}) 
(m[R7]) 
(m[R6]) 
(m[R6]) 
(m[R6]) 

fR6,IN[R3 

fR6,IN[R4 

fR7,IN[R6 

fR6,IN[R2 

=  0 
= 
= 
= 
= 

= 
= 

{di  d2,d3  } 
{d2  d3,d4 
{di  d2,d3 
{d2  d3,d4 
{d2  d3,d4 
{di  d2,  d3  d4  C?5, d% } 

,d5  d6] 
,d4  d5,d$} 
d5  d&} 
d5  do] 

Figure  9.52:  Final  steps  of  region-based  flow  analysis 

9.7.6  Handling  Nonreducible  Flow  Graphs 

If  nonreducible  flow  graphs  are  expected  to  be  common  for  t he  programs  to  be 
processed  by  a  compiler  or  other  program-processing  software,  then  we  recom 
mend  using  an  iterative  rather  t h an  a  hierarchy-based  approach  to  data-flow 
analysis.  However,  if  we  need  only  to  be  prepared  for  the  occasional  nonre 
ducible  flow  graph,  then  the  following  "node-splitting  "  technique  is  adequate. 
Construct  regions  from  natural  loops  to  the  extent  possible.  If t he flow graph 
is  nonreducible,  we  shall  find  t h at  the  resulting  graph  of regions  has  cycles,  but 
no  back  edges,  so  we  cannot  parse  the  graph  any  further.  A  typical  situation 
is  suggested  in  Fig.  9.53(a),  which  has  t he  same  structure  as  the  nonreducible 
flow  graph  of  Fig.  9.45,  but  t he  nodes  in  Fig.  9.53  may  actually  be  complex 
regions,  as  suggested  by  the  smaller  nodes  within. 

We  pick  some  region  R  t h at  has  more  t h an  one  predecessor  and  is  not  the 
header  of  the  entire  flow  graph.  If  i?  has  k  predecessors,  make  k  copies  of  the 
entire  flow  graph  R,  and  connect  each  predecessor  of  i?'s  header  to  a  different 
copy  of  R.  Remember  t h at  only  the  header  of  a  region  could  possibly  have  a 
predecessor  outside  t h at  region.  It  turns  out,  although  we  shall  not  prove  it, 
t h at  such  node  splitting  results  in  a  reduction  by  at  least  one  in  the  number  of 
regions,  after  new  back  edges  are  identified  and  their  regions  constructed.  T he 
resulting  graph  may  still  not  be  reducible,  but  by  alternating  a  splitting  phase 
with  a  phase  where  new  natural  loops  are  identified  and  collapsed  to  regions, 
we  eventually  are  left  with  a  single  region;  i.e.,  the  flow  graph  has  been  reduced. 

685 

E x a m p le  9 . 5 5:  T he  splitting  shown  in  Fig.  9.53(b)  has  turned  the  edge 
R2b  ->  R3  into  a  back  edge,  since  f?3  now  dominates  R2b-  These  two  regions 
may  thus  be  combined  into  one.  T he  resulting  three  regions  —  Ri,  R2a  and 
the  new  region  —  form  an  acyclic  graph,  and  therefore  may  be  combined  into 
a  single  body  region.  We  thus  have  reduced  the  entire  flow  graph  to  a  single 
region.  In  general,  additional  splits  may  be  necessary,  and  in  the  worst  case, 
the  total  number  of  basic  blocks  could  become  exponential  in  the  number  of 
blocks  in  the  original  flow  graph. 

• 

We  must  also  think  about  how  the  result  of  the  data-flow  analysis  on  the 
split  flow  graph  relates  to  the  answer  we  desire  for  the  original  flow  graph. 
There  are  two  approaches  we  might  consider. 

1.  Splitting  regions  may  be  beneficial  for  the  optimization  process,  and  we 
can  simply  revise  the  flow  graph  to  have  copies  of  certain  blocks.  Since 
each  duplicated  block  is  entered  along  only  a  subset  of  the  p a t hs  t h at 
reached  t he  original,  t he  data-flow  values  at  these  duplicated  blocks  will 
tend  to  contain  more  specific  information  t h an  was  available  at  t he  orig 
inal.  For  instance,  fewer  definitions  may  reach  each  of  t he  duplicated 
blocks  t h at  reach  the  original  block. 

2.  If  we  wish  to  retain  the  original  flow  graph,  with  no  splitting,  then  after 
analyzing  the  split  flow  graph,  we  look  at  each  split  block  B,  and  its 
corresponding  set  of  blocks  B1:  B2,... 
,Bk.  We  may  compute  m[B]  — 
m[Bi]  A  IN[B2]  A  •  •  •  A  lN[Bf c],  and  similarly  for  the  OUT's. 

686 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

9.7.7  Exercises  for  Section  9.7 

E x e r c i se  9 . 7 . 1:  For  the  flow  graph  of  Fig.  9.10  (see  the  exercises  for  Section 
9.1): 

i.  Find  all  the  possible  regions.  You  may,  however,  omit  from  the  list  the 

regions  consisting  of  a  single  node  and  no  edges. 

ii.  Give  the  set  of  nested  regions  constructed  by  Algorithm  9.52. 

Hi.  Give  a  T\-T2  reduction  of the flow graph  as  described  in  the  box  on  "Where 

'Reducible'  Comes  From"  in  Section  9.7.2. 

E x e r c i se  9 . 7 . 2:  Repeat  Exercise  9.7.1  on  the  following  flow  graphs: 

a)  Fig.  9.3. 

b)  Fig.  8.9. 

c)  Your  flow  graph  from  Exercise  8.4.1. 

d)  Your  flow  graph  from  Exercise  8.4.2. 

E x e r c i se  9 . 7 . 3:  Prove  t h at  every  natural  loop  is  a  region. 

!!  E x e r c i se  9 . 7 . 4:  Show  t h at  a  flow  graph  is  reducible  if  and  only  it  can  be 

transformed  to  a  single  node  using: 

a)  The  operations  Ti  and  T2  described  in  the  box  in  Section  9.7.2. 

b)  The  region  definition  introduced  in  Section  9.7.2. 

!  E x e r c i se  9 . 7 . 5:  Show  t h at  when  you  apply  node  splitting  to  a  nonreducible 
flow  graph,  and  then  perform  T\-T2  reduction  on  the  resulting  split  graph,  you 
wind  up  with  strictly  fewer  nodes  t h an  you  started  with. 

!  E x e r c i se  9 . 7 . 6:  W h at  happens  if  you  apply  node-splitting  and  T\-T2  reduc 

tion  alternately,  to  reduce  a  complete  directed  graph  of  n  nodes? 

9.8  Symbolic  Analysis 

We  shall  use  symbolic  analysis  in  this  section  to  illustrate  the  use  of  region-
based  analysis.  In  this  analysis,  we  track  the  values  of  variables  in  programs 
symbolically  as  expressions  of  input  variables  and  other  variables,  which  we 
call  reference  variables.  Expressing  variables  in  terms  of  the  same  set  of  ref 
erence  variables  draws  out  their  relationships.  Symbolic  analysis  can  be  used 
for  a  range  of  purposes  such  as  optimization,  parallelization,  and  analyses  for 
program  understanding. 

9.8. 

SYMBOLIC  ANALYSIS 

687 

1) 
2) 
3) 
4) 
5) 
6) 
7) 

x  =  i n p u t ( ); 
y  =  x - 1; 
z  =  y - 1; 
A[x]  =  10; 
ACy]  =  1 1; 
(z  >  x) 
if 

z  =  x; 

Figure  9.54:  An  example  program  motivating  symbolic  analysis 

E x a m p le  9 . 5 6:  Consider  the  simple  example  program  in  Fig.  9.54.  Here,  we 
use  x  as  the  sole  reference  variable.  Symbolic  analysis  will  find  t h at  y  has  the 
value  x — 1  and  z  has  the  value  x — 2  after  their  respective  assignment  statements 
in  lines  (2)  and  (3).  This  information  is  useful,  for  example,  in  determining  t h at 
the  two  assignments  in  lines  (4)  and  (5)  write  to  different  memory  locations  and 
can  thus  be  executed  in  parallel.  Furthermore,  we  can  tell  t h at  t he  condition 
z  >  x  is  never  true,  thus  allowing  the  optimizer  to  remove  the  conditional 
statement  in  lines  (6)  and  (7)  all  together. 

• 

9.8.1  Affine  Expressions  of  Reference  Variables 

Since  we  cannot  create  succinct  and  closed-form  symbolic  expressions  for  all 
values  computed,  we  choose  an  abstract  domain  and  approximate  the  compu 
tations  with  the  most  precise  expressions  within  the  domain.  We  have  already 
In  constant 
seen  an  example  of  this  strategy  before:  constant  propagation. 
propagation,  our  abstract  domain  consists  of  the  constants,  an  U N D EF  symbol 
if  we  have  not  yet  determined  if  the  value  is  a  constant,  and  a  special  NAC 
symbol  t h at  is  used  whenever  a  variable  is  found  not  to  be  a  constant. 

T he  symbolic  analysis  we  present  here  expresses  values  as  affine  expressions 
of reference  variables  whenever  possible.  An  expression  is  affine  with  respect  to 
i >2, . ..  ,vn  if  it  can  be  expressed  as  Co  +  c\V\  +  •  •  •  +  cnvn,  where 
variables 
are  constants.  Such  expressions  are  informally  known  as  linear 
expressions.  Strictly  speaking,  an  affine  expression  is  linear  only  if  CQ  is  zero. 
We  are  interested  in  affine  expressions  because  they  are  often  used  to  index 
arrays  in  loops—such  information  is  useful  for  optimizations  and  parallelization. 
Much  more  will  be  said  about  this  topic  in  Chapter  11. 

I n d u c t i on  V a r i a b l es 

Instead  of  using  program  variables  as  reference  variables,  an  affine  expression 
can  also  be  written  in  terms  of  the  count  of  iterations  through  the  loop.  Vari 
ables  whose  values  can  be  expressed  as  cii + c0,  where  i  is  t he  count  of iterations 
through  the  closest  enclosing  loop,  are  known  as 

induction  variables. 

E x a m p le  9 . 5 7:  Consider  the  code  fragment 

688 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

f or  (m  =  10;  m  < 20;  m++) 

{  x  =  m*3;  A[ x]  = 0;  } 

Suppose  we  introduce  for  the  loop  a  variable,  say  i,  representing  the  number  of 
iterations  executed.  T he  value  i  is 0  in  t he  first  iteration  of  t he  loop, 1  in  the 
second,  and  so  on.  We  can  express  variable  m  as  an  affine  expression  of i,  namely 
m  —  i + 10.  Variable  x,  which  is 3m,  takes  on  values 30,33,... ,57  during 
successive  iterations  of  the  loop.  Thus,  x  has  the  affine  expression  x  = 30 +  Si. 
We  conclude  t h at  b o th  m  and  x  are  induction  variables  of  this  loop. 

• 

Expressing  variables  as  affine  expressions  of  loop  indexes  makes  t he  series 
of  values  being  computed  explicit  and  enables  several  transformations.  T he 
series  of  values  taken  on  by  an  induction  variable  can  be  computed  with  addi 
tions  rather  t h an  multiplications.  This  transformation  is  known  as  "strength 
reduction"  and  was  introduced  in  Sections  8.7  and 9.1.  For  instance,  we  can 
eliminate  the  multiplication  x=m*3  from  the  loop  of  Example 9.57  by  rewriting 
the  loop  as 

x  = 27; 
f or  (m  =  10;  m  < 20;  m++) 

{  x  =  x+3;  A[ x]  = 0;  } 

In  addition,  notice  t h at  the  locations  assigned 0  in  t h at  loop,  SzA + S0,  &,A + 
3 3 ,. ..  ,  &  A  + 57,  are  also  affine  expressions  of  the  loop  index.  In  fact,  this  series 
of  integers  is  the  only  one  t h at  needs  to  be  computed;  We  need  neither  m  nor 
x.  T he  code  above  can  be  replaced  simply  by: 

f or 

(x  =  &A+30;  x  <=  &A+57;  x  =  x+3) 
*x  =  0; 

Besides  speeding  up  t he  computation,  symbolic  analysis  is  also  useful  for 
parallelization.  W h en  t he  array  indexes  in  a  loop  are  affine  expressions  of  loop 
indexes,  we  can  reason  about  relations  of  d a ta  accessed  across  t he  iterations. 
For  example,  we  can  tell  t h at  the  locations  written  are  different  in  each  itera 
tion  and  therefore  all  t he  iterations  in  the  loop  can  be  executed  in  parallel  on 
different  processors.  Such  information  is  used  in  Chapters 10  and 11  to  extract 
parallelism  from  sequential  programs. 

O t h er  R e f e r e n ce  V a r i a b l es 

If  a  variable  is  not  a  linear  function  of  the  reference  variables  already  chosen, 
we  have  the  option  of  treating  its  value  as  reference  for  future  operations.  For 
example,  consider  t he  code  fragment: 

a  = 

b  = 

c  = 

f ( ); 
a  +  10; 
a  +  11; 

9.8. 

SYMBOLIC  ANALYSIS 

689 

While  t he  value  held  by  a  after  the  function  call  cannot  itself  be  expressed 
as  a  linear  function  of  any  reference  variables,  it  can  be  used  as  reference  for 
subsequent  statements.  For  example,  using  a  as  a  reference  variable,  we  can 
discover  t h at  c  is  one  larger  t h an  b  at  the  end  of  t he  program. 

1) 
2) 

3) 
4) 
5) 
6) 
7) 
8) 

a  =  0; 
f or  (f  =  100;  f  <  200;  f++)  { 

a  =  a  +  1 •  > 
b  =  10  *  a; 
c  =  0; 
f or 

(g  =  10;  g  < 
d  =  b  +  c; 
c  =  c  +  1; 

} 

} 

Figure  9.55:  Source  code  for  Example  9.58 

E x a m p le  9 . 5 8:  Our  running  example  for  this  section  is  based  on  the  source 
code  shown  in  Fig.  9.55.  The  inner  and  outer  loops  are  easy  to  understand, 
since  /  and  g  are  not  modified  except  as  required  by  the  for-loops.  It  is  thus 
possible  to  replace  /  and  g  by  reference  variables  i  and  j  t h at  count  the  number 
of  iterations  of  the  outer  and  inner  loops,  respectively.  T h at  is,  we  can  let 
/  —  i  +  99  and  g  =  j  +  9,  and  substitute  for  /  and  g  throughout.  W h en 
translating  to  intermediate  code,  we  can  take  advantage  of  the  fact  t h at  each 
loop  iterates  at  least  once,  and  so  postpone  the  test  for  i  <  100  and  j  <  10  to 
the  ends  of t he  loops.  Figure  9.56  shows  the  flow  graph  for  t he  code  of Fig.  9.55, 
after  introducing  i  and  j  and  treating  t he  for-loops  as  if they  were  repeat-loops. 

It  turns  out  t h at  a,  b,  c,  and  d  are  all  induction  variables.  T he  sequences  of 
values  assigned  to  the  variables  in  each  line  of the  code  are  shown  in  Figure  9.57. 
As  we  shall  see,  it  is  possible  to  discover the  affine  expressions for these  variables, 
in  terms  of the  reference  variables  i  and  j.  T h at  is,  at  line  (4)  a  —  i,  at  line  (7) 
d  =  lOi  + j  —  1,  and  at  line  (8),  c  =  j. 

• 

9.8.2  Data-Flow  Problem  Formulation 

This  analysis  finds  affine  expressions  of  reference  variables  introduced  (1)  to 
count  t he  number  of  iterations  executed  in  each  loop,  and  (2)  to  hold  values 
at  the  entry  of  regions  where  necessary.  This  analysis  also  finds  induction 
variables,  loop  invariants,  as  well  as  constants,  as  degenerate  affine  expressions. 
Note  t h at  this  analysis  cannot  find  all  constants  because  it  only  tracks  affine 
expressions  of  reference  variables. 

690 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

Figure  9.56:  Flow  graph  and  its  region  hierarchy  for  Example  9.58 

D a t a - F l ow  V a l u e s:  S y m b o l ic  M a ps 

T he  domain  of  data-flow  values  for  this  analysis  is  symbolic  maps,  which  are 
functions  t h at  m ap  each  variable  in  t he  program  to  a  value.  T he  value  is  either 
an  affine  function  of  reference  values,  or  t he  special  symbol  N AA  to  represent 
a  non-afflne  expression.  If  there  is  only  one  variable,  t he  b o t t om  value  of  the 
semilattice  is  a  m ap  t h at  sends  the  variable  to  N A A.  T he  semilattice  for  n 
variables  is  simply  t he  product  of  t he  individual  semilattices.  We  use  mN AA  to 
denote  t he  b o t t om  of the  semilattice  which  maps  all  variables  to  N A A.  We  can 
define  the  symbolic  m ap  t h at  sends  all  variables  to  an  unknown  value  to  be  t he 
top  data-flow  value,  as  we  did  for  constant  propagation.  However,  we  do  not 
need  top  values  in  region-based  analysis. 

E x a m p le  9 . 5 9:  The  symbolic  maps  associated  with  each  block  for  the  code 
in  Example  9.58  are  shown  in  Figure  9.58.  We  shall  see  later  how  these  maps 
are  discovered;  they  are  t he  result  of  doing  region-based  data-flow  analysis  on 
t he  flow  graph  of  Fig.  9.56. 

9.8. 

SYMBOLIC  ANALYSIS 

691 

line 
2 
3 
7 
8 

var 
a 
b 
d 
c 

,10 

i  =  1 
j  =  l , . .. 
1 
10 
1 0 , . ..  ,19 
1 , . . . , 10 

i  = 2 
j  =  1 , . ..  ,10 
2 
20 
20,  . . . , 29 
1,.  ..  ,10 

1  <  i <  100 
i  =  i  . ..  ,10 
i 
lOi 
10z,. 
1 . ..  10 

i  =  100 
j  =  l , . .. 
100 
1000 

,10 

.  ,  lOi  + 9  1 0 0 0 . ..  ,1009 

1 . ..  10 

Figure  9.57:  Sequence  of  values  seen  in  program  points  in  Example  9.58. 

m  m (a) 
IN[Bi]  NAA 

O U T [ B i] 

IN[£2] 
O U T [ S2] 

IN[B3] 
O U T [ B3] 
IN[S4] 

O U T [B4] 

0 
i  -  1 
i 
i 
i 
i 
i  -  1 

m(b) 
NAA 
NAA 
NAA 
10« 
10* 
10? 
lOi 
lOi  -  10 

m(c) 
NAA 
NAA 
NAA 
0 

i -i 
j 
j 
j 

m(d) 
NAA 
NAA 
NAA 
NAA 
NAA 
lOz  + j-
lOi  + j~ 
lOi  +  j-

1 
1 
11 

Figure  9.58:  Symbolic  maps  of  the  program  in  Example  9.58. 

T he  symbolic  m ap  associated  with  the  entry  of  the  program  is  mN A A.  At 
t he  exit  of  Bi,  the  value  of  a  is  set  to  0.  Upon  entry  to  block  _B2,  a  has  value 
0  in  t he  first  iteration  and  increments  by  one  in  each  subsequent  iteration  of 
the  outer  loop.  T h us  a  has  value  i  —  1  at  the  entry  of  the  i th  iteration  and 
value  i  at  the  end.  T he  symbolic  m ap  at  the  entry  of  B2  maps  variables  6,  c, d 
to  NAA,  because  the  variables  have  unknown  values  on  entry  to  the  inner  loop. 
Their  values  depend  on  t he  number  of  iterations  of  t he  outer  loop,  so  far.  T he 
symbolic  m ap  on  exit  from  B2  reflects  the  assignment  statements  to  a,  b,  and 
c  in  t h at  block.  T he  rest  of  the  symbolic  maps  can  be  deduced  in  a  similar 
manner.  Once  we  have  established  the  validity  of the  maps  in  Fig.  9.58,  we  can 
replace  each  of the  assignments  to  a,  b,  c,  and  d  in  Fig.  9.55  by  the  appropriate 
affine  expressions.  T h at  is,  we  can  replace  Fig.  9.55  by  t he  code  in  Fig.  9.59. 
• 

Transfer  F u n c t i on  of  a  S t a t e m e nt 

T he  transfer  functions  in  this  data-flow  problem  send  symbolic  maps  to  sym 
bolic  maps.  To  compute  the  transfer  function  of  an  assignment  statement,  we 
interpret  the  semantics  of  t he  statement  and  determine  if  the  assigned  vari 
able  can  be  expressed  as  an  affine  expression  of  the  values  on  t he  right  of  t he 

692 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

1)  a  =  0; 
2) 
f or 
3) 
4) 
5) 

a = 

b = 
c  = 

6) 

7) 
8) 

} 

f or 

} 

(i  = 

1; 

i  <=  100; 

i++)  { 

i; 
1 0 * i; 
0; 
(j  =  1; 

j  <=  10; 

j + +)  { 

d  =  10*i  +  j  - 1; 
c  =  j; 

Figure  9.59:  T he  code  of  Fig.  9.55  with  assignments  replaced  by  affine  expres 
sions  of  the  reference  variables  i  and  j 

Cautions  Regarding  Transfer  Functions  on  Value 
Maps 

A  subtlety  in  the  way  we  define  the  transfer  functions  on  symbolic  maps 
is  t h at  we  have  options  regarding  how  the  effects  of  a  computation  are 
expressed.  W h en  m  is  t he  m ap  for  the  input  of  a  transfer  function,  m(x) 
is  really  just  "whatever  value  variable  x  happens  to  have  on  entry".  We 
t ry  very  hard  to  express  the  result  of  t he  transfer  function  as  an  affine 
expression  of  values  t h at  are  described  by  the  input  m a p. 

You  should  observe  t he  proper 

like 
f(m)(x),  where  /  is  a  transfer  function,  m  a  m a p,  and  x  a  variable.  As 
is  conventional  in  mathematics,  we  apply  functions  from  the  left,  meaning 
t h at  we  first  compute  / ( m ),  which  is  a  m a p.  Since  a  m ap  is  a  function, 
we  may  then  apply  it  to  variable  x  to  produce  a  value. 

interpretation  of  expressions 

assignment.  T he  values  of  all  other  variables  remain  unchanged. 

T he  transfer  function  of  statement  s,  denoted  fs,  is  defined  as  follows: 

1.  If  s  is  not  an  assignment  statement,  then  f8  is  the  identity  function. 

2.  If  s  is  an  assignment  statement  to  variable  x,  then 

fs(m)(x) 

m(v) 
c0  +  cim(y)  +  c2m ( ^) 

= < 

N AA 

for  all  variables  v  ^  x 
if  x  is  assigned  c0  +  c\y  +  c2z, 
(ci  =  0,  or  m(y)  ^  NAA),  and 

0, 

(c2 
= 
or 
otherwise. 

7 7 1 ( 2) 

^  N A A) 

9.8. 

SYMBOLIC  ANALYSIS 

693 

T he  expression  CQ  +  cira(y)  +  c2m(z)  is  intended  to  represent  all  the  possible 
forms  of  expressions  involving  arbitrary  variables  y  and  z  t h at  may  appear  on 
the  right  side  of  an  assignment  to  x  and  t h at  give  x  a  value  t h at  is  an  affine 
transformation  on  prior  values  of  variables.  These  expressions  are:  Co,  Co  +  y, 
co  —  Vi  V  +  zi  x  —  Vi  ci  *  Vi  a nd  y / ( l / c i ).  Note  t h at  in  many  cases,  one  or  more 
of  Co,  c i,  and  c2  are  0. 

E x a m p le  9 . 6 0:  If  the  assignment  is  x=y+z,  then  Co  =  0  and  c\  —  c2  —  1.  If 
t he  assignment  is  x = y / 5,  then  c0  =  c2  =  0,  and  ci  =  1/5. 

• 

C o m p o s i t i on  of  Transfer  F u n c t i o ns 

To  compute  f2  °  fi,  where  fi  and  f2  are  defined  in  terms  of  input  m ap  m, 
we  substitute  the  value  of  m(vi)  in  the  definition  of  f2  with  t he  definition  of 
fi(m)(vi).  We  replace  all  operations  on  NAA  values  with  NAA.  T h at  is, 

1.  If  f2(m)(v)  =  NAA,  then  (f2  o  /1) ( m ) ( v)  =  NAA. 

2.  If  f2(m)(v)  =  c0  +  J2i  Cim(vi), 

then 

( / 2 ° / i ) ( m ) ( «) 

_  f  NAA, 
\  Co  + 

cifi(m)(vi) 

if  fi(m)(vi)  =  NAA  for  some  i  ^  0,  a  ^  0 
otherwise 

E x a m p le  9 . 6 1:  T he  transfer  functions  of  the  blocks  in  Example  9.58  can  be 
computed  by  composing  the  transfer  functions  of  their  constituent  statements. 
These  transfer  functions  are  defined  in  Fig.  9.60. 

• 

/  / ( m ) ( o) 
0 
fBi 
m ( a)  +  1 
IB2 
m(a) 
/BS 
IB4 

m(a) 

f(m)(b) 

f(m)(c) 

f(m)(d) 

m(b) 
10m(a)  +  10 
m(b) 
m(b) 

m(d) 
m(d) 

m(c) 
0 
m(c)  +  1  m(b)  +  m(c) 
m(c) 

m(d) 

Figure  9.60:  Transfer  Functions  of  Example  9.58 

S o l u t i on  to  D a t a - F l ow  P r o b l em 

We  use  the  notation  lNij[B3]  and  OVTij[B3]  to  refer  to  the  input  and  o u t p ut 
data-flow  values  of  block  B3  in  iteration  j  of  the  inner  loop  and  iteration  i  of 
the  outer  loop.  For  the  other  blocks,  we  use  lNi[Bk]  and  OUTi[Bk]  to  refer 
to  these  values  in  the  i th  iteration  of  the  outer  loop.  Also,  we  can  see  t h at 

694 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

/ B( I N[ 5 * ] ), 

= 
OVT[Bk] 
OUT[Bi]  >  mi[B2] 
> 
OVTi[B2] 
> 
O U Ti tj _ i [ B3] 
OUTi,io[^3]  > 
I N i [ ^4], 
OUTi_i[B4]  >  INi[S2], 

I NM[ £3], 

for  all  Bk 

1  <  i  <  10 
1  <  i  <  100,  2  <  j  <  10 
2  <  i  <  100 
1  <  i  <  100 

Figure  9.61:  Constraints  satisfied  on  each  iteration  of  the  nested  loops 

the  symbolic  maps  shown  in  Fig.  9.58  satisfy  the  constraints  imposed  by  the 
transfer  functions,  listed  in  Fig.  9.61. 

T he  first  constraint  says  t h at  the  o u t p ut  m ap  of  a  basic  block  is  obtained 
by  applying  t he  block's  transfer  function  to  the  input  m a p.  The  rest  of  the 
constraints  say  t h at  the  o u t p ut  m ap  of  a  basic  block  must  be  greater  t h an  or 
equal  to  the  input  m ap  of  a  successor  block  in  the  execution. 

Note  t h at  our  iterative  data-flow  algorithm  cannot  produce  the  above  solu 
tion  because  it  lacks  the  concept  of  expressing  data-flow  values  in  terms  of  the 
number  of  iterations  executed.  Region-based  analysis  can  be  used  to  find  such 
solutions,  as  we  shall  see  in  t he  next  section. 

9.8.3  Region-Based  Symbolic  Analysis 

We  can  extend  t he  region-based  analysis  described  in  Section  9.7  to  find  ex 
pressions  of  variables  in  the  ith.  iteration  of  a  loop.  A  region-based  symbolic 
analysis  has  a  b o t t o m - up  pass  and  a  top-down  pass,  like  other  region-based  al 
gorithms.  The  b o t t o m - up  pass  summarizes  the  effect  of  a  region  with  a  transfer 
function  t h at  sends  a  symbolic  m ap  at  t he  entry  to  an  o u t p ut  symbolic  m ap  at 
the  exit.  In  the  top-down  pass,  values  of  symbolic  maps  are  propagated  down 
to  the  inner  regions. 

The  difference  lies  in  how  we  handle  loops.  In  Section  9.7,  the  effect  of a  loop 
is  summarized  with  a  closure  operator.  Given  a  loop  with  body  /,  its  closure 
/*  is  defined  as  an  infinite  meet  of  all  possible  numbers  of  applications  of  /. 
However,  to  find  induction  variables,  we  need  to  determine  if a value  of a variable 
is  an  affine  function  of  t he  number  of  iterations  executed  so  far.  The  symbolic 
m ap  must  be  parameterized  by  the  number  of  t he  iteration  being  executed. 
Furthermore,  whenever  we  know  the  total  number  of  iterations  executed  in  a 
loop,  we  can  use  t h at  number  to  find  the  values  of  induction  variables  after  the 
loop.  For  instance,  in  Example  9.58,  we  claimed  t h at  a  has  the  value  of  i  after 
executing  the  ith  iteration.  Since  the  loop  has  100  iterations,  t he  value  of  a 
must  be  100  at  the  end  of  t he  loop. 

In  what  follows,  we  first  define  the  primitive  operators:  meet  and  composi 
tion  of  transfer  functions  for  symbolic  analysis.  Then  show  how  we  use  them 
to  perform  region-based  analysis  of  induction  variables. 

9.8. 

SYMBOLIC  ANALYSIS 

695 

M e et  of  Transfer  F u n c t i o ns 

W h en  computing  the  meet  of two  functions,  the  value  of a  variable  is  NAA  unless 
t he  two  functions  m ap  t he  variable  to  the  same  value  and  the  value  is  not  NAA. 
Thus, 

P a r a m e t e r i z ed  F u n c t i on  C o m p o s i t i o ns 

To  express  a  variable  as  an  affine  function  of  a  loop  index,  we  need  to  compute 
t he  effect  of  composing  a  function  some  given  number  of  times.  If  the  effect  of 
one  iteration  is  summarized  by  transfer  function  /,  then  the  effect  of  executing 
i  iterations,  for  some  i  >  0,  is  denoted  /\  Note  t h at  when  i  =  0,  fl  =  f°  =  I, 
t he  identify  function. 

Variables  in  the  program  are  divided  into  three  categories: 

1.  If  f(m)(x)  =  m(x)  +  c,  where  c  is  a  constant,  then  fl(m)(x)  —  m(x)  +  ci 
for  every  value  of  i  >  0.  We  say  t h at  a:  is  a  basic  induction  variable  of  the 
loop  whose  body  is  represented  by  the  transfer  function  /. 

2.  If  f(m)(x)  =  m(x), 

then  fl(m)(x)  =  m(x)  for  all  i  >  0.  T he  variable  x 

is  not  modified  and  it  remains  unchanged  at  the  end  of  any  number  of 
iterations  through  t he  loop  with  transfer  function  /.  We  say  t h at  x  is  a 
symbolic  constant  in  the  loop. 

3.  l£f(m)(x)  =  co+cim(xi)-\ 

\-cnm(xn),  where  each  xk 

is  either  a  basic 

induction  variable  or  a  symbolic  constant,  then  for  i  >  0, 

f{m){x)  =  c0  +  c i / ' C m X z i)  +  •  •  •  +  cnf  (m)(xn). 

We  say  t h at  x  is  also  an  induction  variable,  though  not  a  basic  one.  Note 
t h at  the  formula  above  does  not  apply  if  i  =  0. 

4. 

In  all  other  cases,  fl(m)(x)  =  NAA. 

To  find  the  effect  of executing  a  fixed  number  of iterations,  we  simply  replace 
i  above  by  t h at  number.  In  the  case  where  the  number  of iterations  is  unknown, 
the  value  at  the  start  of t he  last  iteration  is  given  by  / *.  In  this  case,  the  only 
variables  whose  values  can  still  be  expressed  in  the  affine  form  are  the  loop-
invariant  variables. 

m(v) 
NAA 

if  f{m)(v)  =  m(v) 

otherwise 

E x a m p le  9 . 62  :  For the  innermost  loop  in  Example  9.58,  the  effect  of executing 
i  iterations,  i  >  0,  is  summarized  by  / j ^.  From  t he  definition  of  fBs,  we  see 
t h at  a  and  6  are  symbolic  constants,  c  is  a  basic  induction  variable  as  it  is 

696 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

incremented  by  one  every  iteration,  d  is  an  induction  variable  because  it  is  an 
affine  function  t he  symbolic  constant  b  and  basic  induction  variable  c.  Thus, 

flB3(™>)(v)  = 

m(a) 
m(b) 
m(c)  +i 
m(b)  +  m(c)  +  i 

if  v  =  a 
if  v  =  b 
if  v  =  c 
if  v  =  d. 

If  we  could  not  tell  how  many  times  the  loop  of  block  B3  iterated,  then  we 
could  not  use  /*  and  would  have  to  use  /*  to  express  t he  conditions  at  the  end 
of  the  loop.  In  this  case,  we  would  have 

if  v  =  a 
if  v  =  b 
if  v  =  c 
if  v  =  d. 

• 

A  R e g i o n - B a s ed  A l g o r i t hm 

A l g o r i t hm  9 . 63  :  Region-based  symbolic  analysis. 

I N P U T:  A  reducible  flow  graph  G. 

O U T P U T:  Symbolic  maps  IN[B]  for  each  block  B  of G. 

M E T H O D:  We  make  the  following  modifications  to  Algorithm  9.53. 

1.  We  change  how  we  construct  t he  transfer  function  for  a  loop  region.  In 
the  original  algorithm  we  use  the  /#,IN[.S]  transfer  function  to  m ap  the 
symbolic  m ap  at  the  entry  of  loop  region  R  to  a  symbolic  m ap  at  the 
entry  of loop  body  S  after  executing  an  unknown  number  of  iterations.  It 
is  defined  to  be  the  closure  of  the  transfer  function  representing  all  p a t hs 
leading  back  to  the  entry  of  the  loop,  as  shown  in  Fig.  9.50(b).  Here  we 
define  /jy,iN[S]  t°  represent  the  effect  of  execution  from  the  start  of  the 
loop  region  to  the  entry  of  the  ith.  iteration.  Thus, 

fR,i,IN[S)  =  ( 

A 
predecessors  B  in  R  of  the  header  of  S 

/ s . O U T p S ]) 

2.  If the  number  of iterations  of a  region  is  known,  the  summary  of t he  region 

is  computed  by  replacing  i  with  the  actual  count. 

3.  In  t he  top-down  pass,  we  compute /jjt<)iN[B] 

to 

f i nd 

t

he  symbolic  m ap 

associated  with  the  entry  of  the  ith  iteration  of  a  loop. 

9.8. 

SYMBOLIC 

ANALYSIS 

697 

4.  In  t he  case  where  the  input  value  of  a  variable  m(v)  is  used  on  the  right-
hand-side  of  a  symbolic  m ap  in  region  R,  and  m(v)  =  N AA  upon  entry  to 
thexregion,  we  introduce  a  new  reference  variable  t,  add  assignment  t  =  v 
to  t he  beginning  of region  R,  and  all  references  of  m(v)  are  replaced  by  t. 
If  we  did  not  introduce  a  reference  variable  at  this  point,  the  N AA  value 
held  by  v  would  penetrate  into  inner  loops. 

fR6,j,W[Bs] 

- 

JB3 

/ i ?B, i , O U T [ B3]  — 

fBz 

/ i ?6, I N [ B2] 

/ R e J N f R s] 

= 

= 

I 

JB2 

Jfl6,OUT[/34]  = 

I  °  / j *6, 1 0 , O U T p 38l  °  fi 

fR7,i,IN[R6] 

/fl7,*,OUTp34] 

/.Rs.INpBi] 

fR8,IN[R7] 

/ f l8, O U T p 34] 

= 

= 

= 

= 

= 

^6, O U T [ B4] 

/ f l6, O U T [ B4] 

I 

/-Bi 

/fi7,100,OUT[/34]  °  / Bi 

Figure  9.62:  Transfer  function  relations  in  the  bottom-up  pass  for  Example  9.58. 

E x a m p le  9 . 6 4:  For  Example  9.58,  we  show  how  the  transfer  functions  for  the 
program  are  computed  in  t he  b o t t o m - up  pass  in  Fig.  9.62.  Region  R5  is  t he 
inner  loop,  with  body  B§.  T he  transfer  function  representing  t he  p a th  from  t he 
entry  of  region  R§  to  the  beginning  of  the  j th  iteration,  j  >  1,  is  fB~X-  T he 
transfer  function  representing  the  p a th  to  the  end  of  the  j th  iteration,  j  >  1, 
is  4-

Region  RQ  consists  of  blocks  B2  and  B4,  with  loop  region  R$  in  the  middle. 
T he  transfer  functions  from  the  entry  of  B2  and  R§  can  be  computed  in  the 
same way as in the original algorithm.  Transfer function / R6, O UT[ B3]  represents 
the  composition  of  block  B2  and  the  entire  execution  of  the  inner  loop,  since 
fs4  is  t he  identity  function.  Since  the  inner  loop  is  known  to  iterate  10  times, 
we  can  replace  j  by  10  to  summarize  the  effect  of  t he  inner  loop  precisely.  T he 

698 

CHAPTER 

9. 

MACHINE-INDEPENDENT  OPTIMIZATIONS 

f 

fR5,j,m[B3] 
fR5,j,0\JT[B3] 

fR6,IN[B2] 
fR6,W[R5] 

/i?6,OUT[B4l 
fR7,iJN[R6] 
fR7,i,OXJT[B4] 

/ ( m ) ( a) 

f(m)(b) 

/ ( m ) ( c) 

f(m)(d) 

m ( a) 
m ( a) 

m(b) 
m(b) 

m(c)  + j  —  1  NAA 
m{c)  + j 

m(b)  +  m{c)+ 

m(b) 
10m(a)  +  10 
10m(a)  +  10 

m ( a) 
m ( a)  +  1 
m ( a)  +  1 
m{a) + i  —  1  NAA 
m ( a)  + i 

10m(a)  +  lOi 

m(c) 
0 
10 

NAA 

10 

m(c) 
m(c) 
10 

m(d) 
m(d) 
10m(a)  +  9 

NAA 
10m ( a )+ 
10i + 9 

m(d) 
m(d) 
1009 

fR8,W[Bi) 
fR8,W[R7] 
IR8,0\JT\BA] 

m ( a) 
0 
100 

m(b) 
m(b) 
1000 

Figure  9.63:  Transfer  functions  computed  in  the  b o t t o m - up  pass  for  Exam 
ple  9.58 

rest  of the  transfer  functions  can  be  computed  in  a  similar  manner.  T he  actual 
transfer  functions  computed  are  shown  in  Fig.  9.63. 

T he  symbolic  m ap  at  the  entry  of  the  program  is  simply  mN A A.  We  use  the 
top-down  pass  to  compute  the  symbolic  m ap  to  the  entry  to  successively  nested 
regions  until  we  find  all  t he  symbolic  maps  for  every  basic  block.  We  start  by 
computing  the  data-flow  values  for  block  B\  in  region  Rs: 

IN[i?i] 

=  mN AA 

OUT[J3i] 

- 

/B I( I N [ 5 I ]) 

Descending  down  to  regions  R?  and  i? 6,  we  get 

INi[B2]  = 

/*7 > i,IN[iifl](OUTp9i]) 

ouTi[J32]  = 

/B2(IN4£2]) 

Finally,  in  region  R5,  we  get 

INitj[B3] 

= 

/ i ?5J , I N [ B 3 ] (O U Ti[52 ]) 

OUTi:j[B3] 

= 

fB3(lNij[B3}) 

Not  surprisingly,  these  equations  produce  the  results  we  showed  in  Fig.  9.58. 
• 

Example  9.58  shows  a  simple  program  where  every  variable  used  in  t he 
symbolic  m ap  has  an  affine  expression.  We  use  Example  9.65  to  illustrate  why 
and  how  we  introduce  reference  variables  in  Algorithm  9.63. 

9.8. 

SYMBOLIC  ANALYSIS 

699 

i++}  { 

j  <  10; 

{ 

f or 

1) 
2) 
3) 
4) 
5) 
6) 

i  <  n; 

(i  =  1; 
a  = 
f or  (j  =  1; 

i n p u t ( ); 

a  =  a  -  1 
b  =  j  +  a 
a  =  a  +  1 

} 

} 

(a)  A  loop  where  a  fluctuates. 

i++}  { 

i  <  n; 

f or  (i  =  1; 
a  = 
t  =  a; 
f or  (j  =  1; 

i n p u t ( ); 

j  <  10; 

j++)  { 

a  =  t  -  1; 
b  =  t  -  1  +  j; 
a  =  t; 

} 

} 

(b)  A  reference  variable  t  makes  b  an  induction  variable. 

Figure  9.64:  T he  need  to  introduce  reference  variables 

E x a m p le  9 . 6 5:  Consider  the  simple  example  in  Fig.  9.64(a).  Let  fj  be  the 
transfer  function  summarizing  the  effect  of  executing  j  iterations  of  the  inner 
loop.  Even  though  t he  value  of  a  may  fluctuate  during  the  execution  of  t he 
loop,  we  see  t h at  b  is  an  induction  variable  based  on  t he  value  of  a  on  entry  of 
the  loop;  t h at  is,  fj(m)(b)  —  m(a)  —  1+ j.  Because  a  is  assigned  an  input  value, 
the  symbolic  m ap  upon  entry  to  the  inner  loop  maps  a  to  NAA.  We  introduce 
a  new  reference  variable  t  to  save  t he  value  of  a  upon  entry,  and  perform  t he 
substitutions  as  in  Fig.  9.64(b). 

• 

9.8.4  Exercises  for  Section  9.8 

E x e r c i se  9 . 8 . 1:  For  the  flow  graph  of  Fig.  9.10  (see  the  exercises  for  Section 
9.1),  give  the  transfer  functions  for 

a)  Block  B2. 

b)  Block  B4. 

c)  Block  B5. 

700 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

E x e r c i se  9 . 8 . 2:  Consider  the  inner  loop  of  Fig.  9.10,  consisting  of  blocks  B3 
and  B4. 
If  i  represents  the  number  of  times  around  the  loop,  and  /  is  t he 
transfer  function  for  the  loop  body  (i.e.,  excluding  the  edge  from  B4  to  B3) 
from  the  entry  of  the  loop  (i.e.,  the  beginning  of  B3)  to  the  exit  from  B4,  then 
what  is  /*?  Remember  t h at  /  takes  as  argument  a  m ap  m,  and  m  assigns  a 
value  to  each  of  variables  a,  b,  d,  and  e.  We  denote  these  values  m ( o ),  and  so 
on,  although  we  do  not  know  their  values. 

E x e r c i se  9 . 8 . 3:  Now  consider  the  outer  loop  of  Fig.  9.10,  consisting  of  blocks 
B2,  B3,  B4,  and  B5.  Let  g  be  the  transfer  function  for  the  loop  body,  from  the 
entry  of the  loop  at  B2  to  its  exit  at  B5.  Let  i  measure  the  number  of iterations 
of the  inner  loop  of B3  and  B4  (which  count  of  iterations  we  cannot  know),  and 
let  j  measure  the  number  of  iterations  of  the  outer  loop  (which  we  also  cannot 
know).  W h at  is  <?J? 

9.9  Summary  of Chapter  9 

4-  Global  Common  Subexpressions:  An 

is  finding 
computations  of  the  same  expression  in  two  different  basic  blocks.  If  one 
precedes  t he  other,  we  can  store  t he  result  t he  first  time  it  is  computed 
and  use  the  stored  result  on  subsequent  occurrences. 

important  optimization 

•  Copy  Propagation:  A  copy  statement,  u  —  v,  assigns  one  variable  v  to 
another,  u.  In  some  circumstances,  we  can  replace  all  uses  of u  by  v,  thus 
eliminating  both  t he  assignment  and  u. 

•  Code  Motion:  Another  optimization  is  to  move  a  computation  outside  the 
loop  in  which  it  appears.  This  change  is  only  correct  if  the  computation 
produces  the  same  value  each  time  around  the  loop. 

• 

Induction  Variables:  Many  loops  have  induction  variables,  variables  t h at 
take  on  a  linear  sequence  of  values  each  time  around  the  loop.  Some  of 
these  are  used  only  to  count  iterations,  and  they  often  can  be  eliminated, 
thus  reducing  the  time  it  takes  to  go  around  the  loop. 

•  Data-Flow  Analysis:  A  data-flow  analysis  schema  defines  a  value  at  each 
point  in  the  program.  Statements  of t he  program  have  associated  transfer 
functions  t h at  relate  the  value  before  the  statement  to  the  value  after. 
Statements  with  more  t h an  one  predecessor  must  have  their  value  defined 
by  combining  the  values  at  t he  predecessors,  using  a  meet  (or  confluence) 
operator. 

4-  Data-Flow  Analysis  on  Basic  Blocks:  Because  the  propagation  of  data 
flow  values  within  a  block  is  usually  quite  simple,  data-flow  equations 
are  generally  set  up  to  have  two  variables  for  each  block,  called  IN  and 
O U T,  t h at  represent  the  data-flow  values  at  the  beginning  and  end  of  t he 

9.9. 

SUMMARY  OF  CHAPTER  9 

701 

block,  respectively.  T he  transfer  functions  for  the  statements  in  a  block 
are  composed  to  get  the  transfer  function  for  the  block  as  a  whole. 

4  Reaching  Definitions:  T he  reaching-definitions  data-flow  framework  has 
values  t h at  are  sets  of  statements  in  the  program  t h at  define  values  for 
one  or  more  variables.  The  transfer  function  for  a  block  kills  definitions 
of  variables  t h at  are  definitely  redefined  in  the  block  and  adds  ("gener 
ates" )  in  those  definitions  of  variables  t h at  occur  within  t he  block.  T he 
confluence  operator  is  union,  since  definitions  reach  a  point  if  they  reach 
any  predecessor  of  t h at  point. 

4  Live  Variables:  Another  important  data-flow  framework  computes  the 
variables  t h at  are  live  (will  be  used  before  redefinition)  at  each  point. 
The  framework  is  similar  to  reaching  definitions,  except  t h at  the  transfer 
function  runs  backward.  A  variable  is  live  at  the  beginning  of  a  block  if 
it  is  either  used  before  definition  in  the  block  or  is  live  at  the  end  of  the 
block  and  not  redefined  in  t he  block. 

4  Available  Expressions:  To  discover  global  common  subexpressions,  we 
determine  t he  available  expressions  at  each  point  —  expressions  t h at  have 
been  computed  and  neither  of  the  expression's  arguments  were  redefined 
after  the  last  computation.  The  data-flow  framework  is  similar  to  reaching 
definitions,  but  the  confluence  operator  is  intersection  rather  t h an  union. 

4  Abstraction  of  Data-Flow  Problems:  Common  data-flow  problems,  such 
as  those  already  mentioned,  can  be  expressed  in  a  common  mathematical 
structure.  T he  values  are  members  of  a  semilattice,  whose  meet  is  the 
confluence  operator.  Transfer  functions  m ap  lattice  elements  to  lattice 
elements.  The  set  of  allowed  transfer  functions  must  be  closed  under 
composition  and  include  the  identity  function. 

4  Monotone  Frameworks:  A  semilattice  has  a  <  relation  defined  by  a  <  b 
if  and  only  if  a  A  b  =  a.  Monotone  frameworks  have  the  property  t h at 
each  transfer  function  preserves  the  <  relationship;  t h at  is,  a  <  b  implies 
f{o)  <  f(b),  for  all  lattice  elements  a  and  b  and  transfer  function  /. 

4  Distributive  Frameworks:  These  frameworks  satisfy 

t h at 
f{a/\b)  =  f(a)Af(b),  for  all  lattice  elements  a  and  b  and  transfer  function 
/.  It  can  be  shown  t h at  t he  distributive  condition  implies  t he  monotone 
condition. 

the  condition 

4  Rerative  Solution  to  Abstract  Frameworks:  All  monotone  data-flow  frame 
works  can  be  solved  by  an  iterative  algorithm, 
in  which  the  IN  and 
O UT  values  for  each  block  are  initialized  appropriately  (depending  on 
the  framework),  and  new  values  for  these  variables  are  repeatedly  com 
puted  by  applying  the  transfer  and  confluence  operations.  This  solution 
is  always  safe  (optimizations  t h at  it  suggests  will  not  change  what  t he 

702 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

program  does),  but  the  solution  is  certain  to  be  the  best  possible  only  if 
the  framework  is  distributive. 

•  The  Constant  Propagation  Framework:  While  t he  basic  frameworks  such 
as  reaching  definitions  are  distributive,  there  are  interesting  monotone-
but-not-distributive  frameworks  as  well.  One  involves  propagating  con 
stants  by  using  a  semilattice  whose  elements  are  mappings  from  t he  pro 
gram  variables  to  constants,  plus  two  special  values  t h at  represent  "no 
information"  and  "definitely  not  a  constant." 

•  Partial-Redundancy  Elimination:  Many  useful  optimizations,  such  as  code 
motion  and  global  common-subexpression  elimination,  can  be  generalized 
to  a  single  problem  called  partial-redundancy  elimination.  Expressions 
t h at  are  needed,  but  are  available  along  only  some  of  the  paths  to  a 
point,  are  computed  only  along  the  paths  where  they  are  not  available. 
The  correct  application  of  this  idea  requires  t he  solution  to  a  sequence  of 
four  different  data-flow  problems  plus  other  operations. 

•  Dominators:  A  node  in  a  flow  graph  dominates  another  if  every  p a th  to 
the  latter  must  go  through  the  former.  A  proper  dominator  is  a  dominator 
other  t h an  the  node  itself.  Each  node  except  the  entry  node  has  an  imme 
diate  dominator  —  t h at  one  of  its  proper  dominators  t h at  is  dominated 
by  all  the  other  proper  dominators. 

4  Depth-First  Ordering  of  Flow  Graphs: 

If  we  perform  a  depth-first  search 

of  a  flow  graph,  starting  at  its  entry,  we  produce  a  depth-first  spanning 
tree.  T he  depth-first  order  of  the  nodes  is  the  reverse  of  a  postorder 
traversal  of  this  tree. 

4-  Classification  of  Edges:  W h en  we  construct  a  depth-first  spanning  tree, 
all  t he  edges  of  the  flow  graph  can  be  divided  into  three  groups:  advanc 
ing  edges  (those  t h at  go  from  ancestor  to  proper  descendant),  retreating 
edges  (those  from  descendant  to  ancestor)  and  cross  edges  (others).  An 
important  property  is  t h at  all  t he  cross  edges  go  from  right  to  left  in  the 
tree.  Another  important  property  is  t h at  of these  edges,  only  the  retreat 
ing  edges  have  a  head  lower  t h an  its  tail  in  t he  depth-first  order  (reverse 
postorder). 

•  Back  Edges:  A  back  edge  is  one  whose  head  dominates  its  tail.  Every 
back  edge  is  a  retreating  edge,  regardless  of  which  depth-first  spanning 
tree  for  its  flow  graph  is  chosen. 

4  Reducible  Flow  Graphs:  If  every  retreating  edge  is  a  back  edge,  regardless 
of which  depth-first  spanning  tree  is  chosen,  then  the  flow  graph  is  said  to 
be  reducible.  The  vast  majority  of flow graphs  are  reducible;  those  whose 
only  control-flow  statements  are  the  usual  loop-forming  and  branching 
statements  are  certainly  reducible. 

9.10. 

REFERENCES  FOR  CHAPTER  9 

703 

4  Natural  Loops:  A  natural  loop  is  a  set  of  nodes  with  a  header  node  t h at 
dominates  all  t he  nodes  in  the  set  and  has  at  least  one  back  edge  entering 
t h at  node.  Given  any  back  edge,  we  can  construct  its  natural  loop  by 
taking  t he  head  of  t he  edge  plus  all  nodes  t h at  can  reach  the  tail  of  t he 
edge  without  going  through  the  head.  Two  natural  loops  with  different 
headers  are  either  disjoint  or  one  is  completely  contained  in  the  other; 
this  fact  lets  us  talk  about  a  hierarchy  of  nested  loops,  as  long  as  "loops" 
are  taken  to  be  n a t u r al  loops. 

4  Depth-First  Order  Makes 

the  Rerative  Algorithm  Efficient:  T he  iterative 
algorithm  requires  few  passes,  as  long  as  propagation  of information  along 
acyclic  paths  is  sufficient;  i.e.,  cycles  add  nothing. 
If  we  visit  nodes  in 
depth-first  order,  any  data-flow  framework  t h at  propagates  information 
forward,  e.g.,  reaching  definitions,  will  converge  in  no  more  t h an  2  plus 
the  largest  number  of  retreating  edges  on  any  acyclic  p a t h.  The  same 
holds  for  backward-propagating  frameworks,  like  live  variables,  if  we  visit 
in  the  reverse  of  depth-first  order  (i.e.,  in  postorder). 

4  Regions:  Regions  are  sets  of  nodes  and  edges  with  a  header  h  t h at  domi 
nates  all  nodes  in  the  region.  The  predecessors  of  any  node  other  t h an  h 
in  the  region  must  also  be  in  the  region.  T he  edges  of  t he  region  are  all 
t h at  go  between  nodes  of  the  region,  with  the  possible  exception  of  some 
or  all  t h at  enter  the  header. 

4  Regions  and  Reducible  Flow  Graphs:  Reducible  flow  graphs  can  be  parsed 
into  a  hierarchy  of  regions.  These  regions  are  either  loop  regions,  which 
include  all  the  edges  into  the  header,  or  body  regions  t h at  have  no  edges 
into  the  header. 

4  Region-Based  Data-Flow  Analysis:  An  alternative 

iterative  ap 
proach  to  data-flow  analysis  is  to  work  up  and  down  the  region  hierarchy, 
computing  transfer  functions  from  the  header  of  each  region  to  each  node 
in  t h at  region. 

the 

to 

4  Region-Based  Induction  Variable  Detection:  An  important  application  of 
region-based  analysis  is  in  a  data-flow  framework  t h at  tries  to  compute 
formulas  for  each  variable  in  a  loop  region  whose  value  is  an  affine  (linear) 
function  of  the  number  of  times  around  the  loop. 

9.10  References  for  Chapter  9 

Two  early  compilers  t h at  did  extensive  code  optimization  are  Alpha  [7]  and 
Fortran  H  [16].  The  fundamental  treatise  on  techniques  for  loop  optimization 
(e.g.,  code  motion)  is  [1],  although  earlier  versions  of some  of these  ideas  appear 
in  [8].  An  informally  distributed  book  [4]  was  influential  in  disseminating  code-
optimization  ideas. 

704 

CHAPTER 

9. 

MACHINE-INDEPENDENT 

OPTIMIZATIONS 

The  first  description  of the  iterative  algorithm  for  data-flow  analysis  is  from 
the  unpublished  technical  report  of  Vyssotsky  and  Wegner  [20].  T he  scientific 
study  of  data-flow  analysis  is  said  to  begin  with  a  pair  of  papers  by  Allen  [2] 
and  Cocke  [3]. 

T he  lattice-theoretic  abstraction  described  here  is  based  on  the  work  of  Kil-
dall  [13].  These  frameworks  assumed  distributivity,  which  many  frameworks  do 
not  satisfy.  After  a  number  of  such  frameworks  came  to  light,  the  monotonicity 
condition  was  embedded  in  the  model  by  [5]  and  [11]. 

Partial-redundancy  elimination  was  pioneered  by  [17].  T he  lazy-code-mo¬ 

tion  algorithm  described  in  this  chapter  is  based  on  [14] 

Dominators  were  first  used  in  t he  compiler  described  in  [13].  However,  the 

idea  dates  back  to  [18]. 

The  notion  of  reducible  flow  graphs  comes  from  [2].  The  structure  of  these 
flow  graphs,  as  presented  here,  is  from  [9]  and  [10].  [12]  and  [15]  first  connected 
reducibility  of flow graphs  to  the  common  nested  control-flow  structures,  which 
explains  why  this  class  of flow  graphs  is  so  common. 

T he  definition  of  reducibility  by  T1-T2  reduction,  as  used  in  region-based 
analysis,  is  from  [19].  The  region-based  approach  was  first  used  in  a  compiler 
described  in  [21]. 

The  static  single-assignment  (SSA)  form  of  intermediate  representation  in 
troduced  in  Section  6.1  incorporates  b o th  d a ta  flow  and  control  flow  into  its 
representation.  SSA  facilitates  t he  implementation  of  many  optimizing  trans 
formations  from  a  common  framework  [6]. 

1.  Allen,  F.  E.,  "Program  optimization,"  Annual  Review  in  Automatic  Pro 

gramming  5  (1969),  pp.  239-307. 

2.  Allen,  F.  E.,  "Control  flow  analysis,"  ACM  Sigplan  Notices  5:7  (1970), 

pp.  1-19. 

3.  Cocke,  J.,  "Global  common  subexpression  elimination,"  ACM  SIGPLAN 

Notices  5:7  (1970),  pp.  20-24. 

4.  Cocke,  J.  and  J.  T.  Schwartz,  Programming  Languages  and  Their  Com 
pilers:  Preliminary  Notes,  Courant  Institute  of  Mathematical  Sciences, 
New  York  Univ.,  New  York,  1970. 

5.  Cousot,  P.  and  R.  Cousot,  "Abstract  interpretation:  a  unified  lattice 
model  for  static  analysis  of programs  by  construction  or  approximation  of 
fixpoints,"  Fourth  ACM  Symposium  on  Principles  of  Programming  Lan 
guages  (1977),  pp.  238-252. 

6.  Cytron,  R.,  J.  Ferrante,  B.  K.  Rosen,  M.  N.  Wegman,  and  F.  K.  Zadeck, 
"Efficiently  computing  static  single  assignment  form  and  the  control  de 
pendence  graph,"  ACM  Transactions  on  Programming  Languages  and 
Systems  13:4  (1991),  pp.  451-490. 

9.10. 

REFERENCES  FOR  CHAPTER  9 

705 

7.  Ershov,  A.  P.,  "Alpha  —  an  automatic  programming  system  of  high  effi 

ciency,"  J.  ACM  13:1  (1966),  p p.  17-24. 

8.  Gear,  C.  W.,  "High  speed  compilation  of  efficient  object  code,"  Comm. 

ACM  8:8  (1965),  pp.  483-488. 

9.  Hecht,  M.  S.  and  J.  D.  Ullman,  "Flow  graph  reducibility,"  SI  AM  J.  Com 

puting  1  (1972),  pp.  188-202. 

10.  Hecht,  M.  S.  and  J.  D.  Ullman,  "Characterizations  of  reducible  flow 

graphs,"  J.  ACM  21  (1974),  pp.  367-375. 

11.  Kam,  J.  B.  and  J.  D.  Ullman,  "Monotone  d a ta flow analysis  frameworks," 

Acta  Informatica  7:3  (1977),  p p.  305-318. 

12.  Kasami,  T.,  W.  W.  Peterson,  and  N.  Tokura,  "On  the  capabilities  of while, 
repeat,  and  exit  statements,"  Comm.  A CM  16:8  (1973),  pp.  503-512. 

13.  Kildall,  G.,  "A  unified  approach  to  global  program  optimization,"  ACM 
Symposium  on  Principles  of  Programming  Languages  (1973),  pp.  194-206. 

14.  Knoop,  J.,  "Lazy  code  motion,"  Proc.  ACM  SIGPLAN  1992  conference 
on  Programming  Language  Design  and  Implementation,  pp.  224-234. 

15.  Kosaraju,  S.  R.,  "Analysis  of  structured  programs,"  J.  Computer  and 

System  Sciences  9:3  (1974),  pp.  232-255. 

16.  Lowry,  E.  S.  and  C.  W.  Medlock,  "Object  code  optimization,"  Comm. 

ACM  12:1  (1969),  pp.  13-22. 

17.  Morel,  E.  and  C.  Renvoise,  "Global  optimization  by  suppression  of partial 

redundancies,"  Comm.  ACM  22  (1979),  pp.  96-103. 

18.  Prosser,  R.  T.,  "Application  of  boolean  matrices  to  the  analysis  of  flow 

diagrams,"  AFIPS  Eastern  Joint  Computer  Conference 
Books,  Baltimore  MD,  pp.  133-138. 

(1959),  Spartan 

19.  Ullman,  J.  D.,  "Fast  algorithms  for  the  elimination  of common  subexpres 

sions,"  Acta  Informatica  2  (1973),  pp.  191-213. 

20.  Vyssotsky,  V.  and  P.  Wegner,  "A  graph  theoretical  Fortran  source  lan 

guage  analyzer,"  unpublished  technical  report,  Bell  Laboratories,  Murray 
Hill  NJ,  1963. 

2 1.  Wulf,  W.  A.,  R.  K.  Johnson,  C.  B.  Weinstock,  S.  O.  Hobbs,  and  C.  M. 

Geschke,  The  Design  of  an  Optimizing  Compiler,  Elsevier,  New  York, 
1975. 

Chapter  10 

Instruction-Level 
Parallelism 

Every  modern  high-performance  processor  can  execute  several  operations  in  a 
single  clock  cycle.  T he  "billion-dollar  question"  is  how  fast  can  a  program  be 
r un  on  a  processor  with  instruction-level  parallelism?  T he  answer  depends  on: 

1.  T he  potential  parallelism  in  the  program. 

2.  T he  available  parallelism  on  t he  processor. 

3.  Our  ability  to  extract  parallelism  from  the  original  sequential  program. 

4.  Our  ability  to  find  t he  best  parallel  schedule  given  scheduling  constraints. 

If  all  the  operations  in  a  program  are  highly  dependent  upon  one  another, 
then  no  amount  of hardware  or  parallelization  techniques  can  make  the  program 
run  fast  in  parallel.  There  has  been  a  lot  of  research  on  understanding  t he 
limits  of  parallelization.  Typical  nonnumeric  applications  have  many  inherent 
dependences.  For  example,  these  programs  have  many  data-dependent  branches 
t h at  make  it  hard  even  to  predict  which  instructions  are  to  be  executed,  let  alone 
decide  which  operations  can  be  executed  in  parallel.  Therefore,  work in  this  area 
has  focused  on  relaxing  the  scheduling  constraints,  including  the  introduction 
of new  architectural  features,  rather  t h an  the  scheduling  techniques  themselves. 

Numeric  applications,  such  as  scientific  computing  and  signal  processing, 
tend  to  have  more  parallelism.  These  applications  deal  with  large  aggregate 
d a ta  structures;  operations  on  distinct  elements  of the  structure  are  often  inde 
pendent  of  one  another  and  can  be  executed  in  parallel.  Additional  hardware 
resources  can  take  advantage  of  such  parallelism  and  are  provided  in  high-
performance,  general-purpose  machines  and  digital  signal  processors.  These 
programs  tend  to  have  simple  control  structures  and  regular  data-access  pat 
terns,  and  static  techniques  have  been  developed  to  extract  t he  available  paral 
lelism  from  these  programs.  Code  scheduling  for  such  applications  is  interesting 

707 

708 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

and  significant,  as  they  offer  a  large  number  of  independent  operations  to  be 
mapped  onto  a  large  number  of  resources. 

Both  parallelism  extraction  and  scheduling  for  parallel  execution  can  be 
In  fact, 
performed  either  statically  in  software,  or  dynamically  in  hardware. 
even  machines  with  hardware  scheduling  can  be  aided  by  software  scheduling. 
This  chapter  starts  by  explaining  the  fundamental  issues  in  using  instruction-
level  parallelism,  which  is  the  same  regardless  of  whether  the  parallelism  is 
managed  by  software  or  hardware.  We  then  motivate  the  basic  data-dependence 
analyses  needed  for  the  extraction  of  parallelism.  These  analyses  are  useful  for 
many  optimizations  other  t h an  instruction-level  parallelism  as  we  shall  see  in 
Chapter  11. 

Finally,  we  present  the  basic  ideas  in  code  scheduling.  We  describe  a  tech 
nique  for  scheduling  basic  blocks,  a  method  for  handling  highly  data-dependent 
control  flow  found  in  general-purpose  programs,  and  finally  a  technique  called 
software  pipelining  t h at  is  used  primarily  for  scheduling  numeric  programs. 

10.1  Processor  Architectures 

When  we  think  of  instruction-level  parallelism,  we  usually  imagine  a  processor 
In  fact,  it  is  possible  for 
issuing  several  operations  in  a  single  clock  cycle. 
a  machine  to  issue  just  one  operation  per  clock1  and  yet  achieve  instruction-
level  parallelism  using  the  concept  of  pipelining.  In  the  following,  we  shall  first 
explain  pipelining  then  discuss  multiple-instruction  issue. 

10.1.1 

Instruction  Pipelines  and  Branch  Delays 

Practically  every  processor,  be  it  a  high-performance  supercomputer  or  a  stan 
instruction  pipeline.  W i th  an  instruction  pipeline,  a 
dard  machine,  uses  an 
new  instruction  can  be  fetched  every  clock  while  preceding  instructions  are  still 
going  through  the  pipeline.  Shown  in  Fig.  10.1  is  a  simple  5-stage  instruction 
pipeline:  it  first  fetches  the  instruction  (IF),  decodes  it  (ID),  executes  t he  op 
eration  (EX),  accesses  the  memory  (MEM),  and  writes  back  the  result  (WB). 
The  figure  shows  how  instructions  i,  i  +  1,  i  +  2,  i +  3,  and  i  + 4  can  execute  at 
the  same  time.  Each  row  corresponds  to  a  clock  tick,  and  each  column  in  the 
figure  specifies  the  stage  each  instruction  occupies  at  each  clock  tick. 

If  the  result  from  an  instruction  is  available  by  the  time  the  succeeding  in 
struction  needs  the  data,  the  processor  can  issue  an  instruction  every  clock. 
Branch  instructions  are  especially  problematic  because  until  they  are  fetched, 
decoded  and  executed,  the  processor  does  not  know  which  instruction  will  ex 
ecute  next.  Many  processors  speculatively  fetch  and  decode  t he  immediately 
succeeding  instructions  in  case  a  branch  is  not  taken.  When  a  branch  is  found 
to  be  taken,  t he  instruction  pipeline  is  emptied  and  t he  branch  target  is  fetched. 

1We  shall  refer  to  a  clock  "tick"  or  clock  cycle  simply  as  a  "clock,"  when  the  intent  is 

clear. 

10.1. 

PROCESSOR  ARCHITECTURES 

709 

i  +  1 

i  +  2 

i  +  3 

i  +  4 

IF 
ID 
EX 
M EM 
WB 

IF 
1. 
ID 
2. 
EX 
3. 
4.  M EM 
5.  WB 
6. 
7. 
8. 
9. 

IF 
ID 
EX 
M EM 
WB 

IF 
ID 
EX 
M EM 
WB 

IF 
ID 
EX 
M EM 
WB 

Figure  10.1:  Five  consecutive  instructions  in  a  5-stage  instruction  pipeline 

Thus,  taken  branches  introduce  a  delay  in  t he  fetch  of  the  branch  target  and 
introduce  "hiccups"  in  the  instruction  pipeline.  Advanced  processors  use  hard 
ware  to  predict  the  outcomes  of  branches  based  on  their  execution  history  and 
to  prefetch  from  the  predicted  target  locations.  Branch  delays  are  nonetheless 
observed  if  branches  are  mispredicted. 

10.1.2  Pipelined  Execution 

Some  instructions  take  several  clocks  to  execute.  One  common  example  is  the 
memory-load  operation.  Even  when  a  memory  access  hits  in  the  cache,  it  usu 
ally  takes  several  clocks  for  the  cache  to  return  the  data.  We  say  t h at  the 
execution  of  an  instruction  is  pipelined  if  succeeding  instructions  not  dependent 
on  the  result  are  allowed  to  proceed.  Thus,  even  if  a  processor  can  issue  only 
one  operation  per  clock,  several  operations  might  be  in  their  execution  stages 
If  the  deepest  execution  pipeline  has  n  stages,  potentially 
at  the  same  time. 
n  operations  can  be  "in  flight"  at  the  same  time.  Note  t h at  not  all  instruc 
tions  are  fully  pipelined.  While  floating-point  adds  and  multiplies  often  are 
fully  pipelined,  floating-point  divides,  being  more  complex  and  less  frequently 
executed,  often  are  not. 

Most  general-purpose  processors  dynamically  detect  dependences  between 
consecutive  instructions  and  automatically  stall  the  execution  of  instructions  if 
their  operands  are  not  available.  Some  processors,  especially  those  embedded 
in  hand-held  devices,  leave  the  dependence  checking  to  the  software  in  order  to 
keep  the  hardware  simple  and  power  consumption  low.  In  this  case,  the  compiler 
is  responsible for  inserting  "no-op"  instructions  in  the  code  if necessary  to  assure 
t h at  the  results  are  available  when  needed. 

710 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

10.1.3  Multiple  Instruction  Issue 

By  issuing  several  operations  per  clock,  processors  can  keep  even  more  opera 
tions  in  flight.  T he  largest  number  of  operations  t h at  can  be  executed  simul 
taneously  can  be  computed  by  multiplying  the  instruction  issue  width  by  the 
average  number  of  stages  in  the  execution  pipeline. 

Like  pipelining,  parallelism  on  multiple-issue  machines  can  be  managed  ei 
ther  by  software  or  hardware.  Machines  t h at  rely  on  software  to  manage  their 
parallelism  are  known  as  VLIW  (Very-Long-Instruction-Word)  machines,  while 
those  t h at  manage  their  parallelism  with  hardware  are  known  as  superscalar 
machines.  VLIW  machines,  as  their  name  implies,  have  wider  t h an  normal 
instruction  words  t h at  encode  the  operations  to  be  issued  in  a  single  clock. 
The  compiler  decides  which  operations  are  to  be  issued  in  parallel  and  encodes 
the  information  in  the  machine  code  explicitly.  Superscalar  machines,  on  t he 
other  hand,  have  a  regular  instruction  set  with  an  ordinary  sequential-execution 
semantics.  Superscalar  machines  automatically  detect  dependences  among  in 
structions  and  issue  t h em  as  their  operands  become  available.  Some  processors 
include  b o th  VLIW  and  superscalar  functionality. 

Simple  hardware  schedulers  execute  instructions  in  the  order  in  which  they 
are  fetched. 
If  a  scheduler  comes  across  a  dependent  instruction,  it  and  all 
instructions  t h at  follow  must  wait  until  the  dependences  are  resolved  (i.e.,  the 
needed  results  are  available).  Such  machines  obviously  can  benefit  from  having 
a  static  scheduler  t h at  places  independent  operations  next  to  each  other  in  the 
order  of  execution. 

More  sophisticated  schedulers  can  execute  instructions  "out  of  order."  Op 
erations  are  independently  stalled  and  not  allowed  to  execute  until  all  the  values 
they  depend  on  have  been  produced.  Even  these  schedulers  benefit  from  static 
scheduling,  because  hardware  schedulers  have  only  a  limited  space  in  which  to 
buffer  operations  t h at  must  be  stalled.  Static  scheduling  can  place  independent 
operations  close  together  to  allow  better  hardware  utilization.  More  impor 
tantly,  regardless  how  sophisticated  a  dynamic  scheduler  is,  it  cannot  execute 
instructions  it  has  not  fetched.  W h en  the  processor  has  to  take  an  unexpected 
branch,  it  can  only  find  parallelism  among  the  newly  fetched  instructions.  T he 
compiler  can  enhance  the  performance  of  the  dynamic  scheduler  by  ensuring 
t h at  these  newly  fetched  instructions  can  execute  in  parallel. 

10.2  Code-Scheduling  Constraints 

Code  scheduling  is  a  form  of  program  optimization  t h at  applies  to  t he  machine 
code  t h at  is  produced  by  the  code  generator.  Code  scheduling  is  subject  to 
three  kinds  of  constraints: 

1.  Control-dependence  constraints.  All  the  operations  executed  in  the  origi 

nal  program  must  be  executed  in  t he  optimized  one. 

10.2.  CODE-SCHEDULING  CONSTRAINTS 

711 

2.  Data-dependence  constraints.  T he  operations  in  t he  optimized  program 
must  produce  the  same  results  as  t he  corresponding  ones  in  t he  original 
program. 

3.  Resource  constraints.  T he  schedule  must  not  oversubscribe  the  resources 

on  t he  machine. 

These  scheduling  constraints  guarantee  t h at  the  optimized  program  pro 
duces  the  same  results  as  the  original.  However,  because  code  scheduling 
changes  the  order  in  which  the  operations  execute,  the  state  of  the  memory 
at  any  one  point  may  not  match  any  of  t he  memory  states  in  a  sequential  ex 
ecution.  This  situation  is  a  problem  if  a  program's  execution  is  interrupted 
by,  for  example,  a  thrown  exception  or  a  user-inserted  breakpoint.  Optimized 
programs  are  therefore  harder  to  debug.  Note  t h at  this  problem  is  not  specific 
to  code  scheduling  but  applies  to  all  other  optimizations,  including  partial-
redundancy  elimination  (Section  9.5)  and  register  allocation  (Section  8.8). 

10.2.1  Data  Dependence 

It  is  easy  to  see  t h at  if  we  change  the  execution  order  of two  operations  t h at  do 
not  touch  any  of  the  same  variables,  we  cannot  possibly  affect  their  results.  In 
fact,  even  if  these  two  operations  read  the  same  variable,  we  can  still  permute 
their  execution.  Only  if  an  operation  writes  to  a  variable  read  or  written  by 
another  can  changing  their  execution  order  alter  their  results.  Such  pairs  of 
operations  are  said  to  share  a  data  dependence,  and  their  relative  execution 
order  must  be  preserved.  There  are  three  flavors  of  d a ta  dependence: 

1.  True  dependence:  read  after  write.  If  a  write  is  followed  by  a  read  of  the 
same  location,  t he  read  depends  on  t he  value  written;  such  a  dependence 
is  known  as  a  true  dependence. 

2.  Antidependence:  write  after  read. 

If  a  read  is  followed  by  a  write  to  the 
same  location,  we  say  t h at  there  is  an  antidependence  from  the  read  to 
the  write.  T he  write  does  not  depend  on  the  read  per  se,  but  if  the  write 
happens  before  t he  read,  then  the  read  operation  will  pick  up  t he  wrong 
value.  Antidependence  is  a  byproduct  of  imperative  programming,  where 
the  same  memory  locations  are  used  to  store  different  values.  It  is  not  a 
"true"  dependence  and  potentially  can  be  eliminated  by  storing  the  values 
in  different  locations. 

3.  Output  dependence:  write  after  write.  Two  writes  to  the  same  location 
share an  output  dependence.  If the  dependence  is  violated,  the  value  of the 
memory  location  written  will  have  the  wrong  value  after  both  operations 
are  performed. 

Antidependence  and  output  dependences  are  referred  to  as  storage-related  de 
pendences.  These  are  not  "true"  dependences  and  can  be  eliminated  by  using 

712 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

different  locations  to  store  different  values.  Note  t h at  d a ta  dependences  apply 
to  both  memory  accesses  and  register  accesses. 

10.2.2  Finding  Dependences  Among  Memory  Accesses 

To  check  if two  memory  accesses  share  a  d a ta  dependence,  we  only  need  to  tell 
if they  can  refer  to  the  same  location;  we  do  not  need  to  know  which  location  is 
being  accessed.  For  example,  we  can  tell  t h at  the  two  accesses  *p  and  O p ) +4 
cannot  refer  to  t he  same  location,  even  though  we  may  not  know  what  p  points 
to.  D a ta  dependence  is  generally  undecidable  at  compile  time.  T he  compiler 
must  assume  t h at  operations  may  refer  to  the  same  location  unless  it  can  prove 
otherwise. 

E x a m p le  1 0 . 1:  Given  the  code  sequence 

1) 
2) 
3) 

a 
*p 
x 

= 
= 
= 

1; 
2; 
a; 

unless  the  compiler  knows  t h at  p  cannot  possibly  point  to  a,  it  must  conclude 
t h at  the  three  operations  need  to  execute  serially.  There  is  an  output  depen 
dence  flowing  from  statement  (1)  to  statement  (2),  and  there  are  two  t r ue 
dependences  flowing  from  statements  (1)  and  (2)  to  statement  (3). 

• 

Data-dependence  analysis  is  highly  sensitive  to  the  programming  language 
used  in  the  program.  For  type-unsafe  languages  like  C  and  C + +,  where  a 
pointer  can  be  cast  to  point  to  any  kind  of  object,  sophisticated  analysis  is 
necessary  to  prove  independence  between  any  pair  of pointer-based  memory  ac 
cesses.  Even  local  or  global  scalar  variables  can  be  accessed  indirectly  unless  we 
can  prove  t h at  their  addresses  have  not  been  stored  anywhere  by  any  instruc 
tion  in  t he  program.  In  type-safe  languages  like  Java,  objects  of  different  types 
are  necessarily  distinct  from  each  other.  Similarly,  local  primitive  variables  on 
the  stack  cannot  be  aliased  with  accesses  through  other  names. 

A  correct  discovery  of  d a ta  dependences  requires  a  number  of different  forms 
of  analysis.  We  shall  focus  on  t he  major  questions  t h at  must  be  resolved  if  the 
compiler  is  to  detect  all  the  dependences  t h at  exist  in  a  program,  and  how  to 
use  this  information  in  code  scheduling.  Later  chapters  show  how  these  analyses 
are  performed. 

A r r ay  D a t a - D e p e n d e n ce  A n a l y s is 

Array  d a ta  dependence  is  the  problem  of  disambiguating  between  t he  values  of 
indexes  in  array-element  accesses.  For  example,  the  loop 

f or  (i  =  0; 

i++) 
A [ 2 * i]  =  A[2*i+1]  ; 

i  <  n; 

10.2. 

CODE-SCHEDULING 

CONSTRAINTS 

713 

copies  odd  elements  in  the  array  A  to  the  even  elements  just  preceding  them. 
Because  all  the  read  and  written  locations  in  the  loop  are  distinct  from  each 
other,  there  are  no  dependences  between  the  accesses,  and  all  the  iterations  in 
the  loop  can  execute  in  parallel.  Array  data-dependence  analysis,  often  referred 
to  simply  as  data-dependence  analysis,  is  very  important  for  the  optimization 
of  numerical  applications.  This  topic  will  be  discussed  in  detail  in  Section  11.6. 

P o i n t e r - A l i as  A n a l y s is 

We  say  t h at  two  pointers  are  aliased  if  they  can  refer  to  the  same  object. 
Pointer-alias  analysis  is  difficult  because  there  are  many  potentially  aliased 
pointers  in  a  program,  and  they  can  each  point  to  an  unbounded  number  of 
dynamic  objects  over  time.  To  get  any  precision,  pointer-alias  analysis  must  be 
applied  across  all  the  functions  in  a  program.  This  topic  is  discussed  starting 
in  Section  12.4. 

I n t e r p r o c e d u r al  A n a l y s is 

For  languages  t h at  pass  parameters  by  reference,  interprocedural  analysis  is 
needed  to  determine  if  the  same  variable  is  passed  as  two  or  more  different 
arguments.  Such  aliases  can  create  dependences  between  seemingly  distinct 
parameters.  Similarly,  global  variables  can  be  used  as  parameters  and  thus 
create  dependences  between  parameter  accesses  and  global  variable  accesses. 
Interprocedural  analysis,  discussed  in  Chapter  12,  is  necessary  to  determine 
these  aliases. 

10.2.3  Tradeoff  Between  Register  Usage  and  Parallelism 

In  this  chapter  we  shall  assume  t h at  the  machine-independent  intermediate  rep 
resentation  of  the  source  program  uses  an  unbounded  number  of pseudoregisters 
to  represent  variables  t h at  can  be  allocated  to  registers.  These  variables  include 
scalar  variables  in  the  source  program  t h at  cannot  be  referred  to  by  any  other 
names,  as  well  as  temporary  variables  t h at  are  generated  by  t he  compiler  to 
hold  the  partial  results  in  expressions.  Unlike  memory  locations,  registers  are 
uniquely  named.  Thus  precise  data-dependence  constraints  can  be  generated 
for  register  accesses  easily. 

T he  unbounded  number  of  pseudoregisters  used  in  the  intermediate  repre 
sentation  must  eventually  be  mapped  to  the  small  number  of  physical  registers 
available  on  the  target  machine.  Mapping  several  pseudoregisters  to  the  same 
physical  register  has  t he  unfortunate  side  effect  of  creating  artificial  storage 
dependences  t h at  constrain  instruction-level  parallelism.  Conversely,  executing 
instructions  in  parallel  creates  t he  need  for  more  storage  to  hold  the  values  being 
computed  simultaneously.  Thus,  the  goal  of minimizing  the  number  of registers 
used  conflicts  directly  with  the  goal  of  maximizing  instruction-level  parallelism. 
Examples  10.2  and  10.3  below  illustrate  this  classic  trade-off  between  storage 
and  parallelism. 

714 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

Hardware  Register  Renaming 

Instruction-level  parallelism  was  first  used  in  computer  architectures  as  a 
means  to  speed  up  ordinary  sequential  machine  code.  Compilers  at  t he 
time  were  not  aware  of the  instruction-level  parallelism  in  the  machine  and 
were  designed  to  optimize  the  use  of registers.  They  deliberately  reordered 
instructions  to  minimize  the  number  of registers  used,  and  as  a  result,  also 
minimized  the  amount  of  parallelism  available.  Example  10.3  illustrates 
how  minimizing  register  usage  in  the  computation  of  expression  trees  also 
limits  its  parallelism. 

There  was  so  little  parallelism  left  in  the  sequential  code  t h at  com 

puter  architects  invented  the  concept  of  hardware  register  renaming  to 
undo  the  effects  of  register  optimization  in  compilers.  Hardware  register 
renaming  dynamically  changes  the  assignment  of  registers  as  t he  program 
runs.  It  interprets  the  machine  code,  stores  values  intended  for  the  same 
register  in  different  internal  registers,  and  updates  all  their  uses  to  refer 
to  the  right  registers  accordingly. 

Since  the  artificial  register-dependence  constraints  were  introduced 
by  the  compiler  in  t he  first  place,  they  can  be  eliminated  by  using  a 
register-allocation  algorithm  t h at  is  cognizant  of  instruction-level  paral 
lelism.  Hardware  register  renaming  is  still  useful  in  t he  case  when  a  ma 
chine's  instruction  set  can  only  refer  to  a  small  number  of  registers.  This 
capability  allows  an  implementation  of  t he  architecture  to  m ap  t he  small 
number  of  architectural  registers  in  the  code  to  a  much  larger  number  of 
internal  registers  dynamically. 

E x a m p le  1 0 . 2:  T he  code  below  copies  the  values  of  variables  in  locations  a 
and  c  to  variables  in  locations  b  and  d,  respectively,  using  pseudoregisters  tl 
and t2. 

LD  t l,  a 
ST  b, 
tl 
LD t2,  c 
ST  d,  t2 

tl  =  a 
// 
//  b 
=  tl 
//  t2  =  c 
//  d  =  t2 

If  all  the  memory  locations  accessed  are  known  to  be  distinct  from  each  other, 
then  t he  copies  can  proceed  in  parallel.  However,  if tl  and t2  are  assigned  t he 
same  register  so  as  to  minimize  the  number  of  registers  used,  the  copies  are 
necessarily  serialized. 

• 

E x a m p le  1 0 . 3: 
Traditional  register-allocation  techniques  aim  to  minimize 
the  number  of  registers  used  when  performing  a  computation.  Consider  t he 
expression 

10.2. 

CODE-SCHEDULING 

CONSTRAINTS 

715 

+ 

c 

d 

e 

a 

b 

Figure  10.2:  Expression  tree  in  Example  10.3 

(a  +  b)  +  c  +  (d  +  e) 

shown  as  a  syntax  tree  in  Fig.  10.2.  It  is  possible  to  perform  this  computation 
using  three  registers,  as  illustrated  by  the  machine  code  in  Fig.  10.3. 

r l, 

LD  r l,  a 
LD  r 2,  b 
ADD  r l, 
LD  r 2,  c 
ADD  r l, 
LD  r 2,  d 
LD  r 3,  e 
ADD  r 2,  r 2, 
r l, 
ADD  r l, 

r l, 

// rl  =  a 
//  r2  =  b 
// rl  =  r l + r2 
// r2  =  c 
// rl  =  r l + r2 
// r2  =  d 
// r3  =  e 
// r2  =  r 2 + r3 
// rl  =  r l + r2 

r2 

r2 

r3 
r2 

Figure  10.3:  Machine  code  for  expression  of  Fig.  10.2 

T he  reuse  of  registers,  however,  serializes  the  computation.  T he  only  oper 

ations  allowed  to  execute  in  parallel  are  the  loads  of  the  values  in  locations a 
and  b,  and  t he  loads  of t he  values  in  locations  d  and e.  It  t h us  takes  a  total  of 
7  steps  to  complete  the  computation  in  parallel. 

Had  we  used  different  registers  for  every  partial  sum,  the  expression  could 
be  evaluated  in  4  steps,  which  is  t he  height  of  t he  expression  tree  in  Fig.  10.2. 
T he  parallel  computation  is  suggested  by  Fig.  10.4. 

• 

r2  =  b 
r7  =  r 4 + r5 

r3  =  c  |  r4  =  d  |  r5  =  e 

rl  =  a 
r6  =  r l + r2 
r8  =  r 6 + r3 
r9  =  r 8 + r7 

Figure  10.4:  Parallel  evaluation  of  the  expression  of  Fig.  10.2 

716 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

10.2.4  Phase  Ordering  Between  Register  Allocation  and 

Code  Scheduling 

If  registers  are  allocated  before  scheduling,  the  resulting  code  tends  to  have 
many  storage  dependences  t h at  limit  code  scheduling.  On  the  other  hand,  if 
code  is  scheduled  before  register  allocation,  the  schedule  created  may  require 
so  many  registers  t h at  register  spilling  (storing  the  contents  of  a  register  in 
a  memory  location,  so  the  register  can  be  used  for  some  other  purpose)  may 
negate  the  advantages  of  instruction-level  parallelism.  Should  a  compiler  allo 
cate  registers  first  before  it  schedules  the  code?  Or  should  it  be  the  other  way 
round?  Or,  do  we  need  to  address  these  two  problems  at  the  same  time? 

To  answer  the  questions  above,  we  must  consider  the  characteristics  of  the 
programs  being  compiled.  Many  nonnumeric  applications  do  not  have  t h at 
much  available  parallelism.  It  suffices  to  dedicate  a  small  number  of  registers 
for  holding  temporary  results  in  expressions.  We  can  first  apply  a  coloring 
algorithm,  as  in  Section  8.8.4,  to  allocate  registers  for  all  t he  nontemporary 
variables,  then  schedule  the  code,  and  finally  assign  registers  to  the  t e m p o r a ry 
variables. 

This  approach  does  not  work  for  numeric  applications  where  there  are  many 
more  large  expressions.  We  can  use  a  hierarchical  approach  where  code  is  op 
Instructions  are  first 
timized  inside  out,  starting  with  the  innermost  loops. 
scheduled  assuming  t h at  every  pseudoregister  will  be  allocated  its  own  physical 
register.  Register  allocation  is  applied  after  scheduling  and  spill  code  is  added 
where  necessary,  and  the  code  is  then  rescheduled.  This  process  is  repeated  for 
the  code  in  the  outer  loops.  When  several  inner  loops  are  considered  together 
in  a  common  outer  loop,  the  same  variable  may  have  been  assigned  different 
registers.  We  can  change  the  register  assignment  to  avoid  having  to  copy  t he 
values  from  one  register  to  another. 
In  Section  10.5,  we  shall  discuss  t he  in 
teraction  between  register  allocation  and  scheduling  further  in  the  context  of  a 
specific  scheduling  algorithm. 

10.2.5  Control  Dependence 

Scheduling  operations  within  a  basic  block  is  relatively  easy  because  all  the 
instructions  are  guaranteed  to  execute  once  control  flow  reaches  the  beginning 
of t he  block.  Instructions  in  a  basic  block  can  be  reordered  arbitrarily,  as  long  as 
all  the  d a ta  dependences  are  satisfied.  Unfortunately,  basic  blocks,  especially  in 
nonnumeric  programs,  are  typically  very  small;  on  average,  there  are  only  about 
five  instructions  in  a  basic  block.  In  addition,  operations  in  the  same  block  are 
often  highly  related  and  thus  have  little  parallelism.  Exploiting  parallelism 
across  basic  blocks  is  therefore  crucial. 

An  optimized  program  must  execute  all  the  operations  in  t he  original  pro 
gram.  It  can  execute  more  instructions  t h an  t he  original,  as  long  as  t he  extra 
instructions  do  not  change  what  the  program  does.  Why  would  executing  extra 
If  we  know  t h at  an  instruction 
instructions  speed  up  a  program's  execution? 

10.2. 

CODE-SCHEDULING 

CONSTRAINTS 

717 

is  likely  to  be  executed,  and  an  idle  resource  is  available  to  perform  t he  opera 
tion  "for  free,"  we  can  execute  the  instruction  speculatively.  T he  program  runs 
faster  when  the  speculation  turns  out  to  be  correct. 

An  instruction  n 

is  said  to  be  control-dependent  on  instruction  i2 

if  the 
outcome  of  i2  determines  whether  h  is  to  be  executed.  The  notion  of  control 
dependence  corresponds  to  the  concept  of  nesting  levels  in  block-structured 
programs.  Specifically,  in  the  if-else  statement 

if  (c)  s i;  e l se  s 2; 

si  and  s2  are  control  dependent  on  c.  Similarly,  in  the  while-statement 

w h i le  (c)  s; 

the  body  s  is  control  dependent  on  c. 

E x a m p le  1 0. 4:  In  the  code  fragment 

if  (a  >  t) 

b  =  a*a; 

d  =  a+c; 

the  statements b  =  a*a  and  d  =  a+c  have  no  d a ta  dependence  with  any  other 
part  of the  fragment.  T he  statement b  =  a*a  depends  on  the  comparison  a  >  t. 
T he  statement  d  =  a+c,  however,  does  not  depend  on  the  comparison  and  can 
be  executed  any  time.  Assuming  t h at  the  multiplication  a  *  a  does  not  cause 
any  side  effects,  it  can  be  performed  speculatively,  as  long  as  b  is  written  only 
• 
after  a  is  found  to  be  greater  t h an  t. 

10.2.6 

Speculative  Execution  Support 

Memory  loads  are  one  type  of instruction  t h at  can  benefit  greatly  from  specula 
tive  execution.  Memory  loads  are  quite  common,  of course.  They  have  relatively 
long  execution  latencies,  addresses  used  in  the  loads  are  commonly  available  in 
advance,  and  the  result  can  be  stored  in  a  new  temporary  variable  without 
destroying  the  value  of  any  other  variable.  Unfortunately,  memory  loads  can 
raise  exceptions  if  their  addresses  are  illegal,  so  speculatively  accessing  illegal 
addresses  may  cause  a  correct  program  to  halt  unexpectedly.  Besides,  mispre 
dicted  memory  loads  can  cause  extra  cache  misses  and  page  faults,  which  are 
extremely  costly. 

E x a m p le  1 0.5  :  In  the  fragment 

if 

(p 

!=  n u l l) 

q  =  * P; 

dereferencing  p  speculatively  will  cause  this  correct  program  to  halt  in  error  if 
p  is  n u l l. 

• 

Many  high-performance  processors  provide  special  features  to  support  spec 

ulative  memory  accesses.  We  mention  the  most  important  ones  next. 

718 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

P r e f e t c h i ng 

The  prefetch  instruction  was  invented  to  bring  d a ta  from  memory  to  the  cache 
before  it  is  used.  A  prefetch  instruction  indicates  to  t he  processor  t h at  the 
If  the 
program  is  likely  to  use  a  particular  memory  word  in  the  near  future. 
location  specified  is  invalid  or  if  accessing  it  causes  a  page  fault,  the  processor 
can  simply  ignore  the  operation.  Otherwise,  the  processor  will  bring  t he  d a ta 
from  memory  to  the  cache  if  it  is  not  already  there. 

P o i s on  B i ts 

Another  architectural  feature  called  poison  bits  was  invented  to  allow  specu 
lative  load  of  d a ta  from  memory  into  the  register  file.  Each  register  on  the 
machine  is  augmented  with  a  poison  bit. 
If  illegal  memory  is  accessed  or  the 
accessed  page  is  not  in  memory,  the  processor  does  not  raise  the  exception  im 
mediately  but  instead  just  sets  the  poison  bit  of  the  destination  register.  An 
exception  is  raised  only  if the  contents  of the  register  with  a  marked  poison  bit 
are  used. 

P r e d i c a t ed  E x e c u t i on 

Because  branches  are  expensive,  and  mispredicted  branches  are  even  more  so 
(see  Section 10.1),  predicated  instructions  were  invented  to  reduce  the  number 
of  branches  in  a  program.  A  predicated  instruction  is  like  a  normal  instruction 
but  has  an  extra  predicate  operand  to  guard  its  execution;  t he  instruction  is 
executed  only  if  the  predicate  is  found  to  be  true. 

As  an  example,  a  conditional  move  instruction CMOVZ  R2,R3,R1  has  the 
semantics  t h at  the  contents  of  register R3  are  moved  to  register R2  only  if 
register Rl  is  zero.  Code  such  as 

if 

(a  ==  0) 

b  =  c+d; 

can  be  implemented  with  two  machine  instructions,  assuming  t h at  a,  b,  c,  and 
d are allocated to registers Rl, R2, R4, R5,  respectively,  as follows: 

ADD 
R3,  R4,  R5 
CMOVZ R2,  R3,  Rl 

This  conversion  replaces  a  series  of  instructions  sharing  a  control  dependence 
with  instructions  sharing  only  d a ta  dependences.  These  instructions  can  then 
be  combined  with  adjacent  basic  blocks  to  create  a  larger  basic  block.  More 
importantly,  with  this  code,  the  processor  does  not  have  a  chance  to  mispredict, 
thus  guaranteeing  t h at  the  instruction  pipeline  will  r un  smoothly. 

Predicated  execution  does  come  with  a  cost.  Predicated  instructions  are 
fetched  and  decoded,  even  though  they  may  not  be  executed  in  t he  end.  Static 
schedulers  must  reserve  all  the  resources  needed  for  their  execution  and  ensure 

10.2. 

CODE-SCHEDULING 

CONSTRAINTS 

719 

Dynamically  Scheduled  Machines 

T he  instruction  set  of a statically  scheduled  machine  explicitly  defines  what 
can  execute  in  parallel.  However,  recall  from  Section  10.1.2  t h at  some  ma 
chine  architectures  allow  the  decision  to  be  made  at  run  time  about  what 
can  be  executed  in  parallel.  W i th  dynamic  scheduling,  the  same  machine 
code  can  be  run  on  different  members  of  t he  same  family  (machines  t h at 
implement  the  same  instruction  set)  t h at  have  varying  amounts  of parallel-
execution  support.  In  fact,  machine-code  compatibility  is  one  of t he  major 
advantages  of  dynamically  scheduled  machines. 

Static  schedulers,  implemented  in  the  compiler  by  software,  can  help 
dynamic  schedulers  (implemented  in  the  machine's  hardware)  better  utilize 
machine  resources.  To  build  a  static  scheduler  for  a  dynamically  sched 
uled  machine,  we  can  use  almost  the  same  scheduling  algorithm  as  for 
statically  scheduled  machines  except  t h at  n o - op  instructions  left  in  t he 
schedule  need  not  be  generated  explicitly.  The  m a t t er  is  discussed  further 
in  Section  10.4.7. 

t h at  all  the  potential  d a ta  dependences  are  satisfied.  Predicated  execution 
should  not  be  used  aggressively  unless  the  machine  has  many  more  resources 
t h an  can  possibly  be  used  otherwise. 

10.2.7  A  Basic  Machine  Model 

Many  machines  can  be  represented  using  the  following  simple  model.  A  machine 
M  =  {R,T),  consists  of: 

1.  A  set  of  operation  types  T,  such  as  loads,  stores,  arithmetic  operations, 

and  so  on. 

2.  A  vector  R  =  [n,  r2,...  ]  representing  hardware  resources,  where  r«  is  the 
number  of  units  available  of  the  ith  kind  of  resource.  Examples  of  typical 
resource  types  include:  memory  access  units,  ALU's,  and  floating-point 
functional  units. 

Each  operation  has  a  set  of  input  operands,  a  set  of  output  operands,  and  a 
resource  requirement.  Associated  with  each  input  operand  is  an  input  latency 
indicating  when  the  input  value  must  be  available  (relative  to  the  start  of  the 
operation).  Typical  input  operands  have  zero  latency,  meaning  t h at  the  values 
are  needed  immediately,  at  the  clock  when  t he  operation  is  issued.  Similarly, 
associated  with  each  output  operand  is  an  output  latency,  which  indicates  when 
the  result  is  available,  relative  to  the  start  of  the  operation. 

Resource  usage  for  each  machine  operation  type  t  is  modeled  by  a  two-
the 

dimensional  resource-reservation 

T he  width  of  t he 

table,  RTt. 

table 

is 

720 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

number  of  kinds  of  resources  in  the  machine,  and  its  length  is  t he  duration 
over  which  resources  are  used  by  the  operation.  Entry  RTt[i,j]  is  t he  number 
of  units  of  the  j th  resource  used  by  an  operation  of  type  t,  i  clocks  after  it  is 
issued.  For  notational  simplicity,  we  assume  RTt[i,j]  =  0  if  i  refers  to  a  nonex 
istent  entry  in  the  table  (i.e.,  i  is  greater  t h an  the  number  of  clocks  it  takes 
to  execute  the  operation).  Of  course,  for  any  t,  i,  and  j,  RTt[i,j]  must  be  less 
t h an  or  equal  to  R[j],  the  number  of  resources  of  type  j  t h at  the  machine  has. 
Typical  machine  operations  occupy  only  one  unit  of  resource  at  the  time 
an  operation  is  issued.  Some  operations  may  use  more  t h an  one  functional 
unit.  For  example,  a  multiply-and-add  operation  may  use  a  multiplier  in  the 
first  clock  and  an  adder  in  the  second.  Some  operations,  such  as  a  divide,  may 
need  to  occupy  a  resource  for  several  clocks.  Fully  pipelined  operations  are 
those  that  can  be  issued  every  clock,  even  though  their  results  are  not  available 
until  some  number  of  clocks  later.  We  need  not  model  the  resources  of  every 
stage  of  a  pipeline  explicitly;  one  single  unit  to  represent  the  first  stage  will  do. 
Any  operation  occupying  the  first  stage  of  a  pipeline  is  guaranteed  the  right  to 
proceed  to  subsequent  stages  in  subsequent  clocks. 

1) 
2) 
3) 
4) 
5) 
6) 

a 
c 
b 
d 
c 
a 

= 
= 
= 
= 
= 
= 

b 
d 
c 
a 
d 
b 

Figure  10.5:  A  sequence  of  assignments  exhibiting  d a ta  dependences 

10.2.8  Exercises  for  Section  10.2 

E x e r c i se  1 0 . 2 . 1:  The  assignments  in  Fig.  10.5  have  certain  dependences.  For 
each  of t he  following  pairs  of statements,  classify  t he  dependence  as  (i)  t r ue  de 
pendence,  (n)  antidependence,  (Hi)  output  dependence,  or  (iv)  no  dependence 
(i.e.,  t he  instructions  can  appear  in  either  order): 

a)  Statements  (1)  and  (4). 

b)  Statements  (3)  and  (5). 

c)  Statements  (1)  and  (6). 

d)  Statements  (3)  and  (6). 

e)  Statements  (4)  and  (6). 

E x e r c i se  1 0 . 2 . 2:  Evaluate  the  expression  ((u+v)  +  (w+x))  +  (y+z)  exactly  as 
parenthesized  (i.e.,  do  not  use  the  commutative or associative laws  to  reorder t he 

10.3. 

BASIC-BLOCK  SCHEDULING 

721 

additions).  Give  register-level  machine  code  to  provide  the  maximum  possible 
parallelism. 

E x e r c i se  1 0 . 2 .3  :  Repeat  Exercise  10.2.2  for  the  following  expressions: 

a)  (u  +  (v  +  (w  +  x))^j  +  (y  +  z). 

b)  (u  +  (v  +  w))  +  (x  +  {y  +  z)). 

If  instead  of  maximizing  the  parallelism,  we  minimized  the  number  of  registers, 
how  many  steps  would  the  computation  take?  How  many  steps  do  we  save  by 
using  maximal  parallelism? 

E x e r c i se  1 0 . 2. 4:  The  expression  of  Exercise  10.2.2  can  be  executed  by  the 
sequence  of  instructions  shown  in  Fig.  10.6.  If  we  have  as  much  parallelism  as 
we  need,  how  many  steps  are  needed  to  execute  the  instructions? 

1) 
2) 
3) 
4) 
5) 
6) 
7) 
8) 
9) 
10) 

11) 

x 

r l, 

LD  r l,  u 
LD  r 2,  v 
ADD  r l, 
LD  r 2,  w 
LD  r 3, 
ADD  r 2,  r 2, 
ADD  r l, 
r l, 
LD  r 2,  y 
LD  r 3,  z 
ADD  r 2,  r 2, 
r l, 
ADD  r l, 

// 
// 
// 
// 
// 
// 
// 
// 
// 
// 
// 

rl  =  u 
r2  =  V 
rl  =  rl  +  r2 
r2  =  w 
r3  =  X 
r2  =  r2  +  r3 
rl  =  rl  +  r2 
r2  =  y 
r3  =  z 
r2  =  r2  +  r3 
rl  =  rl  +  r2 

r2 

r3 
r2 

r3 
r2 

Figure  10.6:  Minimal-register  implementation  of  an  arithmetic  expression 

!  E x e r c i se  1 0 . 2 . 5:  Translate  the  code  fragment  discussed  in  Example  10.4, 
using  t he  CM0VZ  conditional  copy  instruction  of  Section  10.2.6.  W h at  are  the 
d a ta  dependences  in  your  machine  code? 

10.3  Basic-Block  Scheduling 

We  are  now  ready  to  start  talking  about  code-scheduling  algorithms.  We  start 
with  the  easiest  problem:  scheduling  operations  in  a  basic  block  consisting  of 
machine  instructions.  Solving  this  problem  optimally  is  NP-complete.  But  in 
practice,  a  typical  basic  block  has  only  a  small  number  of  highly  constrained 
operations,  so  simple  scheduling  techniques  suffice.  We  shall  introduce  a  simple 
but  highly  effective  algorithm,  called  list  scheduling,  for  this  problem. 

722 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

10.3.1  Data-Dependence  Graphs 

We  represent  each  basic  block  of  machine  instructions  by  a  data-dependence 
graph,  G  =  (N,E),  having  a  set  of  nodes  iV  representing  the  operations  in  t he 
machine  instructions  in  the  block  and  a  set  of  directed  edges  E  representing 
the  data-dependence  constraints  among  the  operations.  The  nodes  and  edges 
of  G  are  constructed  as  follows: 

1.  Each  operation  n  in  N  has  a  resource-reservation  table  RTn,  whose  value 
is  simply  the  resource-reservation  table  associated  with  t he  operation  t y pe 
of  n. 

2.  Each  edge  e  in  E  is  labeled  with  delay  de  indicating  t h at  the  destination 
node  must  be  issued  no  earlier  t h an  de  clocks  after  the  source  node  is 
issued.  Suppose  operation  n±  is  followed  by  operation  n2,  and  the  same 
location  is  accessed  by  both,  with  latencies  l\  and  l2  respectively.  T h at 
is,  the  location's  value  is  produced  l\  clocks  after  t he  first  instruction 
begins,  and  the  value  is  needed  by  the  second  instruction  l2  clocks  after 
t h at  instruction  begins  (note  —  \  and  l2  = 0  is  typical).  Then,  there  is 
an  edge  n\  -»  n2  in  E  labeled  with  delay  l\  —  l2. 

E x a m p le  1 0 . 6:  Consider  a  simple  machine  t h at  can  execute  two  operations 
every  clock.  T he  first  must  be  either  a  branch  operation  or  an  ALU  operation 
of  the  form: 

OP dst,  srcl,  src2 

The  second  must  be  a  load  or  store  operation  of  the  form: 

LD dst,  addr 
ST addr,  src 

T he  load  operation  (LD)  is  fully  pipelined  and  takes  two  clocks.  However, 
a  load  can  be  followed  immediately  by  a  store  ST  t h at  writes  to  the  memory 
location  read.  All  other  operations  complete  in  one  clock. 

Shown  in  Fig. 10.7  is  the  dependence  graph  of  an  example  of  a  basic  block 
and  its  resources requirement.  We might  imagine t h at Rl  is  a stack pointer,  used 
to  access  d a ta  on  the  stack  with  offsets  such  as 0  or 12.  The  first  instruction 
loads  register R2,  and  the  value  loaded  is  not  available  until  two  clocks  later. 
This  observation  explains  the  label 2  on  the  edges  from  t he  first  instruction  to 
the  second  and  fifth  instructions,  each  of which  needs  the  value  of R2.  Similarly, 
there  is  a  delay  of 2  on  the  edge  from  the  third  instruction  to  the  fourth;  t he 
value  loaded  into R3  is  needed  by  the  fourth  instruction,  and  not  available  until 
two  clocks  after  t he  third  begins. 

Since  we  do  not  know  how  the  values  of Rl  and R7  relate,  we  have to  consider 
the possibility t h at an address like 8 (Rl)  is the same as t he address 0 (R7).  T h at 

10.3. 

BASIC-BLOCK  SCHEDULING 

723 

resource-
reservation 
tables 

alu  mem 

data 
dependences 

LD 

r 2,  0 ( r 1) 

• 

ST 

4 ( r 1 ) , r2 

LD 

r 3,  8 ( r 1) 

A DD 

r3 

, r 3 , r4 

K  A DD  R3 

, r 3 , r2 

ST 

1 2 ( r 1 ) , r3 

I1 
I* 
I* 

ST 

0 ( r 7 ) , r7 

Figure  10.7:  Data-dependence  graph  for  Example  10.6 

is,  the  last  instruction  may  be  storing  into  t he  same  address  t h at  the  third 
instruction  loads  from.  T he  machine  model  we  are  using  allows  us  to  store  into 
a  location  one  clock  after  we  load  from  t h at  location,  even  though  t he  value  to 
be  loaded  will  not  appear  in  a  register  until  one  clock  later.  This  observation 
explains  the  label  1  on  the  edge  from  t he  third  instruction  to  the  last.  T he 
same  reasoning  explains  the  edges  and  labels  from  the  first  instruction  to  the 
last.  T he  other  edges  with  label  1  are  explained  by  a  dependence  or  possible 
dependence  conditioned  on  the  value  of  R7. 

• 

10.3.2  List  Scheduling  of  Basic  Blocks 

T he  simplest  approach  to  scheduling  basic  blocks  involves  visiting  each  node  of 
t he  data-dependence  graph  in  "prioritized  topological  order."  Since  there  can 
be  no  cycles  in  a  data-dependence  graph,  there  is  always  at  least  one  topological 
order  for  the  nodes.  However,  among  the  possible  topological  orders,  some  may 
be  preferable  to  others.  We  discuss  in  Section  10.3.3  some  of  the  strategies  for 

724 

CHAPTER  10. 

INSTRUCTION-LEVEL  PARALLELISM 

Pictorial  Resource-Reservation  Tables 

It  is  frequently  useful  to  visualize  a  resource-reservation  table  for  an  oper 
ation  by  a  grid  of solid  and  open  squares.  Each  column  corresponds  to  one 
of  the  resources  of  the  machine,  and  each  row  corresponds  to  one  of  t he 
clocks  during  which  the  operation  executes.  Assuming  t h at  the  operation 
never  needs  more  t h an  one  unit  of  any  one  resource,  we  may  represent  l's 
In  addition,  if  t he  operation 
by  solid  squares,  and  O's  by  open  squares. 
is  fully  pipelined,  then  we  only  need  to  indicate  the  resources  used  at  t he 
first  row,  and  the  resource-reservation  table  becomes  a  single  row. 

This  representation is  used,  for  instance,  in  Example  10.6.  In  Fig.  10.7 
we  see  resource-reservation  tables  as  rows.  The  two  addition  operations 
require  the  "alu"  resource,  while  the  loads  and  stores  require  the  "mem" 
resource. 

picking  a  topological  order,  but  for  the  moment,  we  just  assume  t h at  there  is 
some  algorithm  for  picking  a  preferred  order. 

The  list-scheduling  algorithm  we  shall  describe  next  visits  the  nodes  in  the 
chosen  prioritized  topological  order.  T he  nodes  may  or  may  not  wind  up  being 
scheduled  in  the  same  order  as  they  are  visited.  But  t he  instructions  are  placed 
in  the  schedule  as  early  as  possible,  so  there  is  a  tendency  for  instructions  to 
be  scheduled  in  approximately  the  order  visited. 

In  more  detail,  t he  algorithm  computes  t he  earliest  time  slot  in  which  each 
node  can  be  executed,  according  to  its  data-dependence  constraints  with  the 
previously  scheduled  nodes.  Next,  the  resources  needed  by  the  node  are  checked 
against  a  resource-reservation  table  t h at  collects  all  the  resources  committed  so 
far.  T he  node  is  scheduled  in  the  earliest  time  slot  t h at  has  sufficient  resources. 

A l g o r i t hm  1 0 . 7:  List  scheduling  a  basic  block. 

I N P U T:  A  machine-resource  vector  R  — 
. ],  where  r«  is  the  number 
of  units  available  of  the  ith  kind  of  resource,  and  a  data-dependence  graph 
G  —  (N, E).  Each  operation  n  in  N  is  labeled  with  its  resource-reservation 
table  RTn;  each  edge  e  =  ni  —>  n2  in  E  is  labeled  with  de  indicating  t h at  n2 
must  execute  no  earlier  t h an  de  clocks  after  m. 

[ r i, r 2 ,

.

.

O U T P U T:  A  schedule  S  t h at  maps  the  operations  in  N  into  time  slots  in  which 
the  operations  can  be  initiated  satisfying  all  the  d a ta  and  resources  constraints. 

M E T H O D:  Execute  the  program  in  Fig.  10.8.  A  discussion  of what  the  "prior 
itized  topological  order"  might  be  follows  in  Section  10.3.3. 

• 

10.3. 

BASIC-BLOCK  SCHEDULING 

725 

RT  =  an  empty  reservation  table; 
for  (each  n  in  N  in  prioritized  topological  order)  { 

s  =  maxe=p_>n 

in  E{S{P)  +de); 

/*  Find  t he  earliest  time  this  instruction  could  begin, 

given  when  its  predecessors  started.  */ 

w h i le  (there  exists  i  such  t h at  RT[s  + 

+  RTn[i]  >  R) 

s  =  s  +  1; 

/*  Delay  the  instruction  further  until  the  needed 

resources  are  available.  */ 

S(n)  =  s; 
for  (all  i) 

RT[s  +  i]  =  RT[s  +  i]  +  RTn\i] 

} 

Figure  10.8:  A  list  scheduling  algorithm 

10.3.3  Prioritized  Topological  Orders 

List  scheduling  does  not  backtrack;  it  schedules  each  node  once  and  only  once. 
It  uses  a  heuristic  priority  function  to  choose  among  t he  nodes  t h at  are  ready 
to  be  scheduled  next.  Here  are  some  observations  about  possible  prioritized 
orderings  of  t he  nodes: 

•  Without  resource  constraints,  the  shortest  schedule  is  given  by  the  critical 
path,  t he  longest  p a th  through  t he  data-dependence  graph.  A  metric 
useful  as  a  priority  function  is  the  height  of the  node,  which  is  the  length 
of  a  longest  p a th  in  the  graph  originating  from  the  node. 

•  On  the  other  hand,  if  all  operations  are  independent,  then  the  length 
of  t he  schedule  is  constrained  by  t he  resources  available.  T he  critical 
resource  is  the  one  with  the  largest  ratio  of  uses  to  the  number  of  units 
of  t h at  resource  available.  Operations  using  more  critical  resources  may 
be  given  higher  priority. 

•  Finally,  we  can  use  the  source  ordering  to  break  ties  between  operations; 
the  operation  t h at  shows  up  earlier  in  the  source  program  should  be  sched 
uled  first. 

E x a m p le  1 0.8  :  For  the  data-dependence  graph  in  Fig.  10.7,  the  critical  path, 
including  the  time  to  execute  the  last  instruction,  is  6  clocks.  T h at  is,  the 
critical  p a th  is  the  last  five  nodes,  from  the  load  of  R3  to  the  store  of  R7.  T he 
total  of  the  delays  on  the  edges  along  this  p a th  is  5,  to  which  we  add  1  for  the 
clock  needed  for  the  last  instruction. 

Using  t he  height  as  the  priority  function,  Algorithm  10.7  finds  an  optimal 
schedule  as  shown  in  Fig.  10.9.  Notice  t h at  we  schedule  t he  load  of  R3  first, 
since  it  has  the  greatest  height.  The  add  of  R3  and  R4  has  the  resources  to  be 

726 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

schedule 

resource-
reservation 
table 

alu  mem 

LD  R 3 , 8 ( R 1) 

LD  R 2 , 0 ( R 1) 

ADD  R 3 , R 3 , R4 

ADD  R 3 , R 3 , R2 

ST  4 ( R 1 ) , R2 

ST  1 2 ( R 1 ) , R3 

ST  0 ( R 7 ) , R7 

Figure  10.9:  Result  of  applying  list  scheduling  to  t he  example  in  Fig.  10.7 

scheduled  at  the  second  clock,  but  the  delay  of  2  for  a  load  forces  us  to  wait 
until  the  third  clock  to  schedule  this  add.  T h at  is,  we  cannot  be  sure  t h at  R3 
will  have  its  needed  value  until  the  beginning  of  clock  3. 

• 

LD  R l,  a 
LD  R2,  b 
SUB  R l,  R l,  R2 

LD  R l,  a 
1)  LD  R l,  a 
LD  R2,  b 
LD  R2,  b 
2) 
SUB  R3,  R l,  R2 
SUB  R3,  R l,  R2 
3) 
4)  ADD  R2,  R l,  R2  ADD  R2,  R l,  R2  ADD  R4,  R l,  R2 
5) 
6) 

ST  a,  R3 
ST  b,  R2 

ST  a,  R3 
ST  b,  R4 

ST  a,  Rl 
ST  b,  R2 

(a) 

(b) 

(c) 

Figure  10.10:  Machine  code  for  Exercise  10.3.1 

10.3.4  Exercises  for  Section  10.3 

E x e r c i se  1 0 . 3 . 1:  For  each  of t he  code  fragments  of Fig.  10.10,  draw  the  data-
dependence  graph. 

E x e r c i se  1 0 . 3 . 2:  Assume  a  machine  with  one  ALU  resource  (for  t he  ADD 
and  SUB  operations)  and  one  M EM  resource  (for  the  LD  and  ST  operations). 
Assume  t h at  all  operations  require  one  clock,  except  for  the  LD,  which  requires 
two.  However,  as  in  Example  10.6,  a  ST  on  the  same  memory  location  can 
commence  one  clock  after  a  LD  on  t h at  location  commences.  Find  a  shortest 
schedule  for  each  of  the  fragments  in  Fig.  10.10. 

10.4. 

GLOBAL 

CODE  SCHEDULING 

727 

E x e r c i se  1 0 . 3 . 3:  Repeat  Exercise  10.3.2  assuming: 

i.  T he  machine  has  one  ALU  resource  and  two  M EM  resources. 

ii.  T he  machine  has  two  ALU  resources  and  one  M EM  resource. 

Hi.  T he  machine  has  two  ALU  resources  and  two  M EM  resources. 

1] 

3; 

6; 
7' 

LD  R l,  a 

ST  b,  Rl 
LD  R2,  c 
ST  c,  Rl 

LD  R l,  d 
ST  d,  R2 
ST  a,  Rl 

Figure  10.11:  Machine  code  for  Exercise  10.3.4 

E x e r c i se  1 0 . 3 .4:  Assuming  the  machine  model  of  Example  10.6  (as  in  Exer 
cise  10.3.2): 

a)  Draw  the  d a ta  dependence  graph  for  the  code  of  Fig.  10.11. 

b)  W h at  are  all  the  critical  paths  in  your  graph  from  part  (a)? 

!  c)  Assuming  unlimited  M EM  resources,  what  are  all  the  possible  schedules 

for  the  seven  instructions? 

10.4  Global  Code  Scheduling 

For  a  machine  with  a  moderate  amount  of  instruction-level  parallelism,  sched 
ules  created  by  compacting  individual  basic  blocks  tend  to  leave  many  resources 
idle.  In  order  to  make  better  use  of  machine  resources,  it  is  necessary  to  con 
sider  code-generation  strategies  t h at  move  instructions  from  one  basic  block 
to  another.  Strategies  t h at  consider  more  t h an  one  basic  block  at  a  time  are 
referred  to  as  global  scheduling  algorithms.  To  do  global  scheduling  correctly, 
we  must  consider  not  only  d a ta  dependences  but  also  control  dependences.  We 
must  ensure  t h at 

1.  All  instructions  in  the  original  program  are  executed  in  the  optimized 

program,  and 

2.  While  the  optimized  program  may  execute  extra  instructions  specula 

tively,  these  instructions  must  not  have  any  unwanted  side  effects. 

728 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

10.4.1  Primitive  Code  Motion 

Let  us  first  study  the  issues  involved  in  moving  operations  around  by  way  of  a 
simple  example. 

E x a m p le  1 0 . 9:  Suppose  we  have  a  machine  t h at  can  execute  any  two  oper 
ations  in  a  single  clock.  Every  operation  executes  with  a  delay  of  one  clock, 
except  for  the  load  operation,  which  has  a  latency  of two  clocks.  For  simplicity, 
we  assume  t h at  all  memory  accesses  in  the  example  are  valid  and  will  hit  in  t he 
cache.  Figure  10.12(a)  shows  a  simple  flow  graph  with  three  basic  blocks.  The 
code  is  expanded  into  machine  operations  in  Figure  10.12(b).  All  the  instruc 
tions  in  each  basic  block  must  execute  serially  because  of  d a ta  dependences;  in 
fact,  a  no-op  instruction  has  to  be  inserted  in  every  basic  block. 

Assume  t h at  the  addresses  of variables  a,  b,  c,  d,  and  e  are  distinct  and  t h at 
those  addresses  are  stored  in  registers  Rl  through R5,  respectively.  The  com 
putations  from  different  basic  blocks  therefore  share  no  d a ta  dependences.  We 
observe  t h at  all  the  operations  in  block  B3  are  executed  regardless  of  whether 
the  branch  is  taken,  and  can  therefore  be  executed  in  parallel  with  operations 
from  block  B\.  We  cannot  move  operations  from  B\  down  to  B3,  because  they 
are  needed  to  determine  the  outcome  of  the  branch. 

Operations  in  block  B2  are  control-dependent  on  the  test  in  block  B\.  We 
can  perform  the  load  from  B2  speculatively  in  block  B\  for  free  and  shave  two 
clocks  from  the  execution  time  whenever  the  branch  is  taken. 

Stores  should  not  be  performed  speculatively  because  they  overwrite  t he 
old  value  in  a  memory  location. 
It  is  possible,  however,  to  delay  a  store  op 
eration.  We  cannot  simply  place  the  store  operation  from  block  B2  in  block 
B3,  because  it  should  only  be  executed  if  the  flow  of  control  passes  through 
block  B2.  However,  we  can  place  the  store  operation  in  a  duplicated  copy  of 
B3.  Figure  10.12(c)  shows  such  an  optimized  schedule.  The  optimized  code 
executes  in  4  clocks,  which  is  t he  same  as  t he  time  it  takes  to  execute  B3  alone. 
• 

Example  10.9  shows  t h at  it  is  possible  to  move  operations  up  and  down 
an  execution  p a t h.  Every  pair  of  basic  blocks  in  this  example  has  a  different 
"dominance  relation,"  and  thus  the  considerations  of when  and  how  instructions 
can  be  moved  between  each  pair  are  different.  As  discussed  in  Section  9.6.1, 
a  block  B  is  said  to  dominate  block  B'  if  every  p a th  from  the  entry  of  the 
control-flow  graph  to  B'  goes  through  B.  Similarly,  a  block  B  postdominates 
block  B'  if  every  p a th  from  B'  to  the  exit  of  the  graph  goes  through  B.  When 
B  dominates  B'  and  B'  postdominates  B,  we  say  t h at  B  and  B'  are  control 
equivalent,  meaning  t h at  one  is  executed  when  and  only  when  the  other  is.  For 
t he  example  in  Fig.  10.12,  assuming  Bx  is  the  entry  and  B3  the  exit, 

1.  B\  and  B3  are  control  equivalent:  Bx  dominates  B3  and  B3  postdominates 

Bi, 

2.  Bi  dominates  B2  but  B2  does  not  postdominate  B\,  and 

10.4. 

GLOBAL  CODE  SCHEDULING 

729 

if 

( a = = 0) 

g o to  L 

c  =  b 

L: 

U 

e  =  d +d 

(a)  Source program 

R 6 , 0 ( R 1) 

LD 
n op 
BEQZ  R 6 ,L 

LD 
n op 
ST 

R 7 , 0 ( R 2) 

0 ( R 3 ) , R7 

L: 

LD  R 8 , 0 ( R 4) 
n op 
ADD  R 8 , R 8 , R8 
ST 

0 ( R 5 ) , R8 

(b)  Locally  scheduled machine  code 

R 6 , 0 ( R 1 ),  LD  R 8 , 0 ( R 4) 
R 7 , 0 ( R 2) 

LD 
LD 
ADD  R 8 , R 8 , R 8,  BEQZ  R 6 ,L 

ST  0 ( R 5 ) , R8 

ST  0 ( R 5 ) , R 8,  ST  0 ( R 3 ) , R7 

(c)  Globally  scheduled machine  code 

Figure  10.12:  Flow  graphs  before  and  after  global  scheduling  in  Example  10.9 

730 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

3.  B2  does  not  dominate  B3  but  B3  postdominates  B2. 

It  is  also  possible  for  a  pair  of blocks  along  a  p a th  to  share  neither  a  dominance 
nor  postdominance  relation. 

10.4.2  Upward  Code  Motion 

We  now  examine  carefully  what  it  means  to  move  an  operation  up  a  p a t h. 
Suppose  we  wish  to  move  an  operation  from  block  src  up  a  control-flow  p a th  to 
block  dst.  We  assume  t h at  such  a  move  does  not  violate  any  d a ta  dependences 
and  t h at  it  makes  paths  through  dst  and  src  run  faster. 
If  dst  dominates  src, 
and  src  postdominates  dst,  then  t he  operation  moved  is  executed  once  and  only 
once,  when  it  should. 

If  src  d o es  n ot  p o s t d o m i n a te  dst 

Then  there  exists  a  p a th  t h at  passes  through  dst  t h at  does  not  reach  src.  An 
extra  operation  would  have  been  executed  in  this  case.  This  code  motion  is 
illegal  unless  the  operation  moved  has  no  unwanted  side  effects.  If  t he  moved 
operation  executes  "for  free"  (i.e.,  it  uses  only  resources  t h at  otherwise  would 
It  is  beneficial  only  if  the  control  flow 
be  idle),  then  this  move  has  no  cost. 
reaches  src. 

If  dst  d o es  n ot  d o m i n a te  src 

Then  there  exists  a  p a th  t h at  reaches  src  without  first  going  through  dst.  We 
need  to  insert  copies  of  the  moved  operation  along  such  paths.  We  know  how 
to  achieve  exactly  t h at  from  our  discussion  of  partial  redundancy  elimination 
in  Section  9.5-  We  place  copies  of  the  operation  along  basic  blocks  t h at  form  a 
cut  set  separating  t he  entry  block  from  src.  At  each  place  where  the  operation 
is  inserted,  the  following  constraints  must  be  satisfied: 

1.  T he  operands  of t he  operation  must  hold  the  same  values  as  in  the  original, 

2.  The  result  does  not  overwrite  a  value  t h at  is  still  needed,  and 

3.  It  itself  is  not  subsequently  overwritten  befpre  reaching  src. 

These  copies  render  the  original  instruction  in  src  fully  redundant,  and  it  thus 
can  be  eliminated. 

We  refer  to  the  extra  copies  of  the  operation  as  compensation  code.  As  dis 
cussed  in  Section  9.5,  basic  blocks  can  be  inserted  along  critical  edges  to  create 
places  for  holding  such  copies.  The  compensation  code  can  potentially  make 
some  paths  run  slower.  Thus,  this  code  motion  improves  program  execution 
only  if  the  optimized  paths  are  executed  more  frequently  t h an  t he  nonopti-
mized  ones. 

10.4. 

GLOBAL  CODE  SCHEDULING 

731 

10.4.3  Downward  Code  Motion 

Suppose  we  are  interested  in  moving  an  operation  from  block  src  down  a  control-
flow  p a th  to  block  dst.  We  can  reason  about  such  code  motion  in  the  same  way 
as  above. 

If  src  d o es  n ot  d o m i n a te  dst 

T h en  there  exists  a  p a th  t h at  reaches  dst  without  first  visiting  src.  Again,  an 
extra  operation  will  be  executed  in  this  case.  Unfortunately,  downward  code 
motion  is  often  applied  to  writes,  which  have  the  side  effects  of  overwriting  old 
values.  We  can  get  around  this  problem  by  replicating  the  basic  blocks  along 
t he  paths  from  src  to  dst,  and  placing  the  operation  only  in  the  new  copy  of 
dst.  Another  approach,  if  available,  is  to  use  predicated  instructions.  We  guard 
the  operation  moved  with  the  predicate  t h at  guards  the  src  block.  Note  t h at 
the  predicated  instruction  must  be  scheduled  only  in  a  block  dominated  by 
t he  computation  of the  predicate,  because  the  predicate  would  not  be  available 
otherwise. 

If  dst  d o es  n ot  p o s t d o m i n a te  src 

As  in  the  discussion  above,  compensation  code  needs  to  be  inserted  so  t h at  the 
operation  moved  is  executed  on  all  paths  not  visiting  dst.  This  transformation 
is  again  analogous  to  partial  redundancy  elimination,  except  t h at  the  copies  are 
placed  below  the  src  block  in  a  cut  set  t h at  separates  src  from  the  exit. 

S u m m a ry  of  U p w a rd  a nd  D o w n w a rd  C o de  M o t i on 

From  this  discussion,  we  see  t h at  there  is  a  range  of  possible  global  code  mo 
tions  which  vary  in  terms  of benefit,  cost,  and  implementation  complexity.  Fig 
ure  10.13  shows  a  summary  of these  various  code  motions;  t he  lines  correspond 
to  t he  following  four  cases: 

up:  src  postdom  dst 
down:  src  dom  dst 
yes 
no 
yes 
no 

dst  dom  src 
dst  postdom  src 
yes 
yes 
no 
no 

1 
2 
3 
4 

speculation 
code  dup. 
no 
yes 
no 
yes 

compensation 
code 
no 
no 
yes 
yes 

Figure  10.13:  Summary  of  code  motions 

1.  Moving  instructions  between  control-equivalent  blocks  is  simplest  and 
most  cost  effective.  No  extra  operations  are  ever  executed  and  no  com 
pensation  code  is  needed. 

732 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

2.  E x t ra  operations  may  be  executed  if  the  source  does  not  postdominate 
(dominate)  the  destination  in  upward  (downward)  code  motion.  This 
code  motion  is  beneficial  if  the  extra  operations  can  be  executed  for  free, 
and  the  p a th  passing  through  the  source  block  is  executed. 

3.  Compensation  code  is  needed  if  the  destination  does  not  dominate  (post-
dominate)  the  source  in  upward  (downward)  code  motion.  The  paths  with 
the  compensation  code  may  be  slowed  down,  so  it  is  important  t h at  the 
optimized  paths  are  more  frequently  executed. 

4.  The  last  case  combines  the  disadvantages  of  the  second  and  third  case: 
extra  operations  may  be  executed  and  compensation  code  is  needed. 

10.4.4  Updating  Data  Dependences 

As  illustrated  by  Example  10.10  below,  code  motion  can  change  the  data-
dependence  relations  between  operations.  Thus  d a ta  dependences  must  be 
updated  after  each  code  movement. 

E x a m p le  1 0 . 10  :  For  the  flow  graph  shown  in  Fig.  10.14,  either  assignment  to 
x  can  be  moved  up  to  the  top  block,  since  all  the  dependences  in  the  original 
program  are  preserved  with  this  transformation.  However,  once  we  have  moved 
one  assignment  up,  we  cannot  move  the  other.  More  specifically,  we  see  t h at 
variable  x  is  not  live  on  exit  in  the  top  block  before  the  code  motion,  but  it  is 
live  after  the  motion.  If  a  variable  is  live  at  a  program  point,  then  we  cannot 
move  speculative  definitions  to  the  variable  above  t h at  program  point. 

• 

Figure  10.14:  Example  illustrating  the  change  in  d a ta  dependences  due  to  code 
motion. 

10.4.5  Global  Scheduling  Algorithms 

We  saw  in  the  last  section  t h at  code  motion  can  benefit  some  paths  while 
hurting  t he  performance  of  others.  The  good  news  is  t h at  instructions  are  not 
all  created  equal.  In  fact,  it  is  well  established  t h at  over  90%  of  a  program's 
execution  time  is  spent  on  less  t h an  10%  of  the  code.  Thus,  we  should  aim  to 

10.4. 

GLOBAL  CODE  SCHEDULING 

733 

make  the  frequently  executed  paths  run  faster  while  possibly  making  the  less 
frequent  paths  run  slower. 

There  are  a  number  of  techniques  a  compiler  can  use  to  estimate  execution 
frequencies.  It  is  reasonable  to  assume  t h at  instructions  in  the  innermost  loops 
are  executed  more  often  t h an  code  in  outer  loops,  and  t h at  branches  t h at  go 
backward  are  more  likely  to  be  taken  t h an  not  taken.  Also,  branch  statements 
found  to  guard  program  exits  or  exception-handling  routines  are  unlikely  to  be 
taken.  T he  best  frequency  estimates,  however,  come  from  dynamic  profiling.  In 
this  technique,  programs  are  instrumented  to  record  the  outcomes  of conditional 
branches  as  they  run.  T he  programs  are  then  run  on  representative  inputs  to 
determine  how  they  are  likely  to  behave  in  general.  The  results  obtained  from 
this  technique  have  been  found  to  be  quite  accurate.  Such  information  can  be 
fed  back  to  t he  compiler  to  use  in  its  optimizations. 

R e g i o n - B a s ed  S c h e d u l i ng 

We  now  describe  a  straightforward  global  scheduler  t h at  supports  the  two  eas 
iest  forms  of  code  motion: 

1.  Moving  operations  up  to  control-equivalent  basic  blocks,  and 

2.  Moving  operations  speculatively  up  one  branch  to  a  dominating  predeces 

sor. 

Recall  from  Section  9.7.1  t h at  a  region  is  a  subset  of a  control-flow  graph  t h at 
can  be  reached  only  through  one  entry  block.  We  may  represent  any  procedure 
as  a  hierarchy  of regions.  The  entire  procedure  constitutes  the  top-level  region, 
nested  in  it  are  subregions  representing  the  natural  loops  in  t he  function.  We 
assume  t h at  the  control-flow  graph  is  reducible. 

A l g o r i t hm  1 0 . 1 1:  Region-based  scheduling. 

I N P U T:  A  control-flow  graph  and  a  machine-resource  description. 

O U T P U T:  A  schedule  S  mapping  each  instruction  to  a  basic  block  and  a  time 
slot. 

M E T H O D:  Execute  the  program  in  Fig.  10.15.  Some  shorthand  terminology 
should  be  apparent:  ControlEquiv(B) 
is  the  set  of  blocks  t h at  are  control-
equivalent  to  block  B,  and  DominatedSucc  applied  to  a  set  of  blocks  is  the  set 
of  blocks  t h at  are  successors  of  at  least  one  block  in  the  set  and  are  dominated 
by  all. 

Code  scheduling  in  Algorithm  10.11  proceeds  from  the  innermost  regions 
to  t he  outermost.  W h en  scheduling  a  region,  each  nested  subregion  is  t r e a t ed 
as  a  black  box;  instructions  are  not  allowed  to  move  in  or  out  of  a  subregion. 
They  can,  however,  move  around  a  subregion,  provided  their  d a ta  and  control 
dependences  are  satisfied. 

734 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

for  (each  region  R  in  topological  order,  so  t h at  inner  regions 

are  processed  before  outer  regions)  { 

compute  d a ta  dependences; 
for  (each  basic  block  B  of  R  in  prioritized  topological  order)  { 

CandBlocks  =  ControlEquiv(B)  U 
DominatedSucc(ControlEquiv(B)); 

Candlnsts  —  ready  instructions  in  CandBlocks; 
for  (t  =  0 , 1 , . ..  until  all  instructions  from  B  are  scheduled)  { 

for  (each  instruction  n  in  Candlnsts  in  priority  order) 

if  (n  has  no  resource  conflicts  at  time  t)  { 

(B,t); 

S(n)  = 
u p d a te  resource  commitments; 
u p d a te  d a ta  dependences; 

} 

u p d a te  Candlnsts; 

} 

} 

} 

Figure  10.15:  A  region-based  global  scheduling  algorithm 

All  control  and  dependence  edges  flowing  back  to  the  header  of t he  region  are 
ignored,  so  t he  resulting  control-flow  and  data-dependence  graphs  are  acyclic. 
The  basic  blocks  in  each  region  are  visited  in  topological  order.  This  ordering 
guarantees  t h at  a  basic  block  is  not  scheduled  until  all  t he  instructions  it  de 
pends  on  have  been  scheduled.  Instructions  to  be  scheduled  in  a  basic  block  B 
are  drawn  from  all  the  blocks  t h at  are  control-equivalent  to  B  (including  B), 
as  well  as  their  immediate  successors  t h at  are  dominated  by  B. 

A  list-scheduling  algorithm  is  used  to  create  the  schedule  for  each  basic 
block.  T he  algorithm  keeps  a  list  of  candidate  instructions,  Candlnsts,  which 
contains  all  the  instructions  in  t he  candidate  blocks  whose  predecessors  all  have 
been  scheduled.  It  creates  t he  schedule  clock-by-clock.  For  each  clock,  it  checks 
each  instruction  from  t he  Candlnsts  in  priority  order  and  schedules  it  in  t h at 
clock  if  resources  permit.  Algorithm  10.11  then  updates  Candlnsts  and  repeats 
the  process,  until  all  instructions  from  B  are  scheduled. 

T he  priority  order  of  instructions  in  Candlnsts  uses  a  priority  function  sim 
ilar  to  t h at  discussed  in  Section  10.3.  We  make  one  important  modification, 
however.  We  give  instructions  from  blocks  t h at  are  control  equivalent  to  B 
higher  priority  t h an  those  from  the  successor  blocks.  T he  reason  is  t h at  in 
structions  in  the  latter  category  are  only  speculatively  executed  in  block  B. 
• 

10.4. 

GLOBAL  CODE  SCHEDULING 

735 

L o op  U n r o l l i ng 

In  region-based  scheduling,  the  boundary  of a  loop  iteration  is  a  barrier  to  code 
motion.  Operations  from  one  iteration  cannot  overlap  with  those  from  another. 
One  simple  but  highly  effective  technique  to  mitigate  this  problem  is  to  unroll 
t he  loop  a  small  number  of  times  before  code  scheduling.  A  for-loop  such  as 

for  (i  =  0;  i  <  N;  i++)  { 

S(i); 

} 

can  be  written  as  in  Fig.  10.16(a).  Similarly,  a  repeat-loop  such  as 

repeat 

S; 

until C; 

can  be  written  as  in  Fig.  10.16(b).  Unrolling  creates  more  instructions  in  the 
loop  body,  permitting  global  scheduling  algorithms  to  find  more  parallelism. 

for  (i = 0;  i+4 < N;  i+=4)  { 

S(i); 

S ( i+ 1 ); 

S ( i+ 2 ); 

S ( i+ 3 ); 

} 
for  (  ;  i  < N;  i++)  { 

(a)  Unrolling  a  for-loop. 

S(i); 

} 

repeat  { 

S; 

if  (C)  break; 

S; 

if  (C)  break; 

S; 

if  (C)  break; 

S; 
}  until  C; 

(b)  Unrolling  a  repeat-loop. 

Figure  10.16:  Unrolled  loops 

736 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

N e i g h b o r h o od  C o m p a c t i on 

Algorithm  10.11  only  supports  the  first  two  forms  of  code  motion  described  in 
Section  10.4.1.  Code  motions  t h at  require  the  introduction  of  compensation 
code  can  sometimes  be  useful.  One  way  to  support  such  code  motions  is  to 
follow  the  region-based  scheduling  with  a  simple  pass. 
In  this  pass,  we  can 
examine  each  pair  of  basic  blocks  t h at  are  executed  one  after  the  other,  and 
check  if  any  operation  can  be  moved  up  or  down  between  them  to  improve 
If  such  a  pair  is  found,  we  check  if  the 
the  execution  time  of  those  blocks. 
instruction  to  be  moved  needs  to  be  duplicated  along  other  paths.  T he  code 
motion  is  made  if  it  results  in  an  expected  net  gain. 

This  simple  extension  can  be  quite  effective  in  improving  the  performance  of 
loops.  For  instance,  it  can  move  an  operation  at  the  beginning  of  one  iteration 
to  the  end  of  the  preceding  iteration,  while  also  moving  the  operation  from  the 
first  iteration  out  of  the  loop.  This  optimization  is  particularly  attractive  for 
tight  loops,  which  are  loops  t h at  execute  only  a  few  instructions  per  iteration. 
However,  t he  impact  of  this  technique  is  limited  by  t he  fact  t h at  each  code-
motion  decision  is  made  locally  and  independently. 

10.4.6  Advanced  Code  Motion  Techniques 

If  our  target  machine  is  statically  scheduled  and  has  plenty  of  instruction-level 
parallelism,  we  may  need  a  more  aggressive  algorithm.  Here  is  a  high-level 
description  of  further  extensions: 

1.  To  facilitate  the  extensions  below,  we  can  add  new  basic  blocks  along 
control-flow edges  originating  from  blocks  with  more t h an  one  predecessor. 
These  basic  blocks  will  be  eliminated  at  t he  end  of code  scheduling  if they 
are  empty.  A  useful  heuristic  is  to  move  instructions  out  of  a  basic  block 
t h at  is  nearly  empty,  so  t h at  t he  block  can  be  eliminated  completely. 

2.  In  Algorithm  10.11,  the  code  to  be  executed  in  each  basic  block  is  sched 

uled  once  and  for  all  as  each  block  is  visited.  This  simple  approach  suffices 
because  the  algorithm  can  only  move  operations  up  to  dominating  blocks. 
To  allow  motions  t h at  require  the  addition  of compensation  code,  we  take 
a  slightly  different  approach.  When  we  visit  block  B,  we  only  schedule 
instructions  from  B  and  all  its  control-equivalent  blocks.  We  first  t ry  to 
place  these  instructions  in  predecessor  blocks,  which  have  already  been 
visited  and  for  which  a  partial  schedule  already  exists.  We  try  to  find 
a  destination  block  t h at  would  lead  to  an  improvement  on  a  frequently 
executed  p a th  and  then  place  copies  of  t he  instruction  on  other  paths  to 
guarantee  correctness.  If  t he  instructions  cannot  be  moved  up,  they  are 
scheduled  in  the  current  basic  block  as  before. 

3.  Implementing  downward  code  motion  is  harder  in  an  algorithm  t h at  visits 
basic  blocks  in  topological  order,  since  the  target  blocks  have  yet  to  be 

10.4. 

GLOBAL  CODE  SCHEDULING 

737 

scheduled.  However,  there  are  relatively  fewer  opportunities  for  such  code 
motion  anyway.  We  move  all  operations  t h at 

(a)  can  be  moved,  and 

(b)  cannot  be  executed  for  free  in  their  native  block. 

This  simple  strategy  works  well  if  the  target  machine  is  rich  with  many 
unused  hardware  resources. 

10.4.7 

Interaction  with  Dynamic  Schedulers 

A  dynamic  scheduler  has  the  advantage  t h at  it  can  create  new  schedules  ac 
cording  to  the  run-time  conditions,  without  having  to  encode  all  these  possible 
schedules  ahead  of time.  If a  target  machine  has  a  dynamic  scheduler,  the  static 
scheduler's  primary  function  is  to  ensure  t h at  instructions  with  high  latency  are 
fetched  early  so  t h at  the  dynamic  scheduler  can  issue  t h em  as  early  as  possible. 
Cache  misses  are  a  class  of  unpredictable  events  t h at  can  make  a  big  differ 
ence  to  the  performance  of  a  program.  If  data-prefetch  instructions  are  avail 
able,  the  static  scheduler  can  help  the  dynamic  scheduler  significantly  by  placing 
these  prefetch  instructions  early  enough  t h at  the  d a ta  will  be  in  the  cache  by 
the  time  they  are  needed.  If  prefetch  instructions  are  not  available,  it  is  useful 
for  a  compiler  to  estimate  which  operations  are  likely  to  miss  and  try  to  issue 
t h em  early. 

If  dynamic  scheduling  is  not  available  on  the  target  machine,  the  static 
scheduler  must  be  conservative  and  separate  every  data-dependent  pair  of  op 
erations  by  t he  minimum  delay.  If dynamic  scheduling  is  available,  however,  t he 
compiler  only  needs  to  place  the  data-dependent  operations  in  the  correct  order 
to  ensure  program  correctness.  For  best  performance,  t he  compiler  should  as 
sign  long  delays  to  dependences  t h at  are  likely  to  occur  and  short  ones  to  those 
t h at  are  not  likely. 

Branch  misprediction  is  an  important  cause  of loss  in  performance.  Because 
of the  long  misprediction  penalty,  instructions  on  rarely  executed  paths  can  still 
have  a  significant  effect  on  the  total  execution  time.  Higher  priority  should  be 
given  to  such  instructions  to  reduce  the  cost  of  misprediction. 

10.4.8  Exercises  for  Section  10.4 

E x e r c i se  1 0. 4. 1:  Show  how  to  unroll  the  generic  while-loop 

w h i le 

(C) 

S; 

!  E x e r c i se  1 0. 4. 2:  Consider  the  code  fragment: 

(x  ==  0)  a  =  b; 

if 
e l se  a  =  c; 
d  =  a; 

738 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

Assume  a  machine  t h at  uses  the  delay  model  of  Example  10.6  (loads  take  two 
clocks,  all  other  instructions  take  one  clock).  Also  assume  t h at  t he  machine 
can  execute  any  two  instructions  at  once.  Find  a  shortest  possible  execution 
of  this  fragment.  Do  not  forget  to  consider  which  register  is  best  used  for  each 
of  the  copy  steps.  Also,  remember  to  exploit  the  information  given  by  register 
descriptors  as  was  described  in  Section  8.6,  to  avoid  unnecessary  loads  and 
stores. 

10.5  Software  Pipelining 

As  discussed  in  the  introduction  of  this  chapter,  numerical  applications  tend 
to  have  much  parallelism.  In  particular,  they  often  have  loops  whose  iterations 
are  completely  independent  of one  another.  These  loops,  known  as  do-all loops, 
are  particularly  attractive  from  a  parallelization  perspective  because  their  iter 
ations  can  be  executed  in  parallel  to  achieve  a  speed-up  linear  in  the  number 
of  iterations  in  the  loop.  Do-all  loops  with  many  iterations  have  enough  par 
allelism  to  saturate  all  the  resources  on  a  processor.  It  is  up  to  the  scheduler 
to  take  full  advantage  of the  available  parallelism.  This  section  describes  an  al-
gorithnij  known  as  software  pipelining,  t h at  schedules  an  entire  loop  at  a  time, 
taking  full  advantage  of  the  parallelism  across  iterations. 

10.5.1 

Introduction 

We  shall  use  the  do-all  loop  in  Example  10.12  throughout  this  section  to  explain 
software  pipelining.  We  first  show  t h at  scheduling  across  iterations  is  of  great 
importance,  because  there  is  relatively  little  parallelism  among  operations  in 
a  single  iteration.  Next,  we  show  t h at  loop  unrolling  improves  performance 
by  overlapping  the  computation  of  unrolled  iterations.  However,  the  boundary 
of  the  unrolled  loop  still  poses  as  a  barrier  to  code  motion,  and  unrolling  still 
leaves  a  lot  of performance  "on  t he  table."  The  technique  of software  pipelining, 
on  the  other  hand,  overlaps  a  number  of  consecutive  iterations  continually  until 
it  runs  out  of  iterations.  This  technique  allows  software  pipelining  to  produce 
highly  efficient  and  compact  code. 

E x a m p le  1 0 . 12  :  Here  is  a  typical  do-all  loop: 

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

D[i]  = A[i]*B[i]  + c; 

Iterations  in  t he  above  loop  write  to  different  memory  locations,  which  are 
themselves  distinct  from  any  of  the  locations  read.  Therefore,  there  are  no 
memory  dependences  between  t he  iterations,  and  all  iterations  can  proceed  in 
parallel. 

We  adopt  the  following  model  as  our  target  machine  throughout  this  section. 

In  this  model 

10.5.  SOFTWARE 

PIPELINING 

739 

•  The  machine  can  issue  in  a  single  clock:  one  load,  one  store,  one  arithmetic 

operation,  and  one  branch  operation. 

•  T he  machine  has  a  loop-back  operation  of  the  form 

BL R,  L 

which  decrements  register  R  and,  unless  the  result  is 0,  branches  to  loca 
tion  L. 

•  Memory  operations  have  an  auto-increment  addressing  mode,  denoted  by 
++  after  the  register.  The  register  is  automatically  incremented  to  point 
to  the  next  consecutive  address  after  each  access. 

•  T he  arithmetic  operations  are  fully  pipelined;  they  can  be  initiated  every 
clock  but  their  results  are  not  available  until  2  clocks  later.  All  other 
instructions  have  a  single-clock  latency. 

If  iterations  are  scheduled  one  at  a  time,  the  best  schedule  we  can  get  on 
our  machine  model  is  shown  in  Fig. 10.17.  Some  assumptions  about  the  layout 
of the  d a ta  also  also  indicated  in  t h at  figure:  registers Rl, R2,  and R3  hold  the 
addresses  of the  beginnings  of arrays  A,  B,  and  D,  register R4  holds  the  constant 
c,  and  register RIO  holds  the  value  n — 1,  which  has  been  computed  outside  the 
loop.  T he  computation  is  mostly  serial,  taking  a  total  of 7  clocks;  only  t he 
• 
loop-back  instruction  is  overlapped  with  the  last  operation  in  the  iteration. 

// 

// 

// 

Rl,  R2,  R3 = &A,  &B,  &D 
R4 
RIO 

=  c 
=  n-1 

L: 

LD  R5,  0(R1++) 
LD  R6,  0(R2++) 
MUL R7,  R5,  R6 
nop 
ADD R8,  R7,  R4 
nop 

ST  0(R3++),  R8 

BL  RIO,  L 

Figure  10.17:  Locally  scheduled  code  for  Example  10.12 

In  general,  we  get  better  hardware  utilization  by  unrolling  several  iterations 
of  a  loop.  However,  doing  so  also  increases  the  code  size,  which  in  t u rn  can 
have  a  negative  impact  on  overall  performance.  Thus,  we  have  to  compromise, 
picking  a  number  of times  to  unroll  a  loop  t h at  gets  most  of the  performance  im 
provement,  yet  doesn't  expand t he  code  t oo  much.  T he  next  example  illustrates 
the  tradeoff. 

740 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

E x a m p le  1 0 . 1 3:  While  hardly  any  parallelism  can  be  found  in  each  iteration 
of the  loop  in  Example  10.12,  there  is  plenty  of parallelism  across  t he  iterations. 
Loop  unrolling  places  several  iterations  of  the  loop  in  one  large  basic  block, 
and  a  simple  list-scheduling  algorithm  can  be  used  to  schedule  the  operations 
to  execute  in  parallel. 
If  we  unroll  the  loop  in  our  example  four  times  and 
apply  Algorithm  10.7  to  the  code,  we  can  get  the  schedule  shown  in  Fig.  10.18. 
(For  simplicity,  we  ignore  the  details  of  register  allocation  for  now).  The  loop 
executes  in  13  clocks,  or  one  iteration  every  3.25  clocks. 

A  loop  unrolled  k  times  takes  at  least  2ft  +  5  clocks,  achieving  a  throughput 
of  one  iteration  every  2  +  5/k  clocks.  Thus,  the  more  iterations  we  unroll,  t he 
faster  the  loop  runs.  As  n  -»  oo,  a  fully  unrolled  loop  can  execute  on  average  an 
iteration  every  two  clocks.  However,  the  more  iterations  we  unroll,  the  larger 
the  code  gets.  We  certainly  cannot  afford  to  unroll  all  the  iterations  in  a  loop. 
Unrolling  t he  loop  4  times  produces  code  with  13  instructions,  or  163%  of  t he 
optimum;  unrolling  the  loop  8  times  produces  code  with  21  instructions,  or 
131%  of  the  optimum.  Conversely,  if  we  wish  to  operate  at,  say,  only  110%  of 
the  optimum,  we  need  to  unroll  the  loop  25  times,  which  would  result  in  code 
with  55  instructions. 

• 

10.5.2 

Software  Pipelining  of  Loops 

Software  pipelining  provides  a  convenient  way  of  getting  optimal  resource  usage 
and  compact  code  at  t he  same  time.  Let  us  illustrate  the  idea  with  our  running 
example. 

E x a m p le  1 0 . 1 4:  In  Fig.  10.19  is  the  code  from  Example  10.12  unrolled  five 
times.  (Again  we  leave  out  t he  consideration  of register  usage.)  Shown  in  row  i 
are  all  the  operations  issued  at  clock  i;  shown  in  column  j  are  all  t he  operations 
from  iteration  j.  Note  t h at  every  iteration  has  the  same  schedule  relative  to  its 
beginning,  and  also  note  t h at  every  iteration  is  initiated  two  clocks  after  the 
preceding  one.  It  is  easy  to  see  t h at  this  schedule  satisfies  all  t he  resource  and 
data-dependence  constraints. 

We  observe  t h at  the  operations  executed  at  clocks  7  and  8  are  the  same 
as  those  executed  at  clocks  9  and  10.  Clocks  7  and  8  execute  operations  from 
the  first  four  iterations  in  t he  original  program.  Clocks  9  and  10  also  execute 
In  fact,  we 
operations  from  four  iterations,  this  time  from  iterations  2  to  5. 
can  keep  executing  this  same  pair  of  multi-operation  instructions  to  get  t he 
effect  of  retiring  the  oldest  iteration  and  adding  a  new  one,  until  we  run  out  of 
iterations. 

Such  dynamic  behavior  can  be  encoded  succinctly  with  t he  code  shown  in 
Fig.  10.20,  if  we  assume  t h at  the  loop  has  at  least  4  iterations.  Each  row  in 
the  figure  corresponds  to  one  machine  instruction.  Lines  7  and  8  form  a  2-clock 
loop,  which  is  executed  n  -  3  times,  where  n  is  the  number  of  iterations  in  the 
original  loop. 

• 

10.5. 

SOFTWARE  PIPELINING 

741 

L:  LD 
LD 

LD 

MUL  LD 

MUL  LD 
LD 

ADD 

ADD 

LD 

ST 

MUL  LD 

ST 

MUL 

ADD 

ADD 

ST 

ST 

BL  (L) 

Figure  10.18:  Unrolled  code  for  Example  10.12 

Clock 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 

J  =  2 

i  =  3 

i  =  4 

j  = 

3  =  1 
LD 

LD 

MUL 

ADD 

LD 

LD 

MUL 

LD 

LD 

MUL 

ST 

ADD 

ST 

ADD 

LD 
LD 
MUL 

LD 

LD 
MUL 

ST 

ADD 

ST 

ADD 

ST 

Figure  10.19:  Five  unrolled  iterations  of  the  code  in  Example  10.12 

742 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

1) 
2) 
3) 
4) 
5) 
6) 
7)  L: 

8) 
9) 
10) 

11) 
12) 

13) 
14) 

LD 
LD 

MUL  LD 
LD 
MUL 

ADD 

ST 

ADD 

LD 

LD 

MUL 

ST 

ADD 

LD 

LD 

MUL 

BL  (L) 

ST 

ADD 

ST 

Figure  10.20:  Software-pipelined  code  for  Example  10.12 

T he  technique  described  above  is  called  software  pipelining,  because  it  is  the 
software  analog  of  a  technique  used  for  scheduling  hardware  pipelines.  We  can 
think  of  the  schedule  executed  by  each  iteration  in  this  example  as  an  8-stage 
pipeline.  A  new  iteration  can  be  started  on  t he  pipeline  every  2  clocks.  At 
the  beginning,  there  is  only  one  iteration  in  the  pipeline.  As  the  first  iteration 
proceeds  to  stage three,  the  second  iteration  starts  to  execute  in  t he  first  pipeline 
stage. 

By  clock  7,  the  pipeline  is  fully  filled  with  t he  first  four  iterations.  In  the 
steady  state,  four  consecutive  iterations  are  executing  at  the  same  time.  A  new 
iteration  is  started  as  the  oldest  iteration  in  t he  pipeline  retires.  W h en  we  run 
out  of  iterations,  the  pipeline  drains,  and  all  the  iterations  in  the  pipeline  run 
to  completion.  The  sequence  of  instructions  used  to  fill  t he  pipeline,  lines  1 
through  6  in  our  example,  is  called  the  prolog;  lines  7  and  8  are  t he  steady  state; 
and  the  sequence  of  instructions  used  to  drain  the  pipeline,  lines  9  through  14, 
is  called  the  epilog. 

For  this  example,  we  know  t h at  the  loop  cannot  be  run  at  a  r a te  faster 
t h an  2  clocks  per  iteration,  since  t he  machine  can  only  issue  one  read  every 
clock,  and  there  are  two  reads  in  each  iteration.  T he  software-pipelined  loop 
above  executes  in  2n  +  6  clocks,  where  n  is  the  number  of  iterations  in  the 
original  loop.  As  n 
oo,  the  throughput  of  the  loop  approaches  t he  rate  of 
one  iteration  every  two  clocks.  Thus,  software  scheduling,  unlike  unrolling,  can 
potentially  encode  the  optimal  schedule  with  a  very  compact  code  sequence. 

Note  t h at  the  schedule  adopted  for  each  individual  iteration  is  not  the 
shortest  possible.  Comparison  with  the  locally  optimized  schedule  shown  in 
Fig.  10.17  shows  t h at  a  delay  is  introduced  before  the ADD  operation.  T he  delay 
is  placed  strategically  so  t h at  the  schedule  can  be  initiated  every  two  clocks 
without  resource  conflicts.  Had  we  stuck  with  t he  locally  compacted  schedule, 

10.5. 

SOFTWARE  PIPELINING 

743 

the  initiation  interval  would  have  to  be  lengthened  to  4  clocks  to  avoid  resource 
conflicts,  and  the  throughput  rate  would  be  halved.  This  example  illustrates 
an  important  principle  in  pipeline  scheduling: 
the  schedule  must  be  chosen 
carefully  in  order  to  optimize  the  throughput.  A  locally  compacted  schedule, 
while  minimizing  t he  time  to  complete  an  iteration,  may  result  in  suboptimal 
throughput  when  pipelined. 

10.5.3  Register  Allocation  and  Code  Generation 

Let  us  begin  by  discussing  register  allocation  for  the  software-pipelined  loop  in 
Example  10.14. 

E x a m p le  1 0 . 1 5: 
In  Example 10.14,  the  result  of  the  multiply  operation  in 
t he  first  iteration  is  produced  at  clock 3  and  used  at  clock 6.  Between  these 
clock  cycles,  a  new  result  is  generated  by  the  multiply  operation  in  the  second 
iteration  at  clock  5;  this  value  is  used  at  clock  8.  T he  results  from  these  two 
iterations  must  be  held  in  different  registers  to  prevent  them  from  interfering 
with  each  other.  Since  interference  occurs  only  between  adjacent  pairs  of  itera 
tions,  it  can  be  avoided  with  the  use  of  two  registers,  one  for  the  odd  iterations 
and  one  for  t he  even  iterations.  Since  t he  code  for  odd  iterations  is  different 
from  t h at  for  the  even  iterations,  the  size  of  the  steady-state  loop  is  doubled. 
This  code  can  be  used  to  execute  any  loop  t h at  has  an  odd  number  of iterations 
greater  t h an  or  equal  to  5. 

if  (N  >=  5) 

N2  =  3  +  2  *  floor((N-3)/2); 

else 

N2  =  0; 

for  (i = 0;  i  < N2;  i++) 

D[i]  = A [ i ]* B[i]  + c; 

for  (i = N2;  i  < N;  i++) 

D[i]  = A [ i ]* B[i]  + c; 

Figure 10.21:  Source-level  unrolling  of the  loop  from  Example 10.12 

To  handle  loops  t h at  have  fewer  t h an  5  iterations  and  loops  with  an  even 
number  of  iterations,  we  generate  the  code  whose  source-level  equivalent  is 
shown  in  Fig. 10.21.  T he  first  loop  is  pipelined,  as  seen  in  the  machine-level 
equivalent  of Fig. 10.22.  T he  second  loop  of Fig. 10.21  need  not  be  optimized, 
since  it  can  iterate  at  most  four  times. 

• 

10.5.4  Do-Across  Loops 

Software  pipelining  can  also  be  applied  to  loops  whose  iterations  share  d a ta 
dependences.  Such  loops  are  known  as  do-across  loops. 

744 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

1. 
2. 
3. 
4. 
5. 
6. 
7. 
8. 
9. 
10. 
11. 
12. 
13. 
14. 
15. 
16. 

LD  R5,0(R1++) 
LD  R6,0(R2++) 

LD R5,0(R1++)  MUL R7,R5,R6 
LD  R6,0(R2++) 

LD R5,0(R1++)  MUL  R9,R5,R6 
LD R6,0(R2++)  ADD  R8,R7,R4 
LD R5,0(R1++)  MUL  R7,R5,R6 
LD R6,0(R2++)  ADD  R8,R9,R4 
LD R5,0(R1++)  MUL  R9,R5,R6 
LD R6,0(R2++)  ADD  R8,R7,R4 
MUL  R7,R5,R6 
ADD  R8,R9,R4 

L: 

ST 

0(R3++),R8 

ST 

0(R3++),R8  BL  R10,L 

ST 

0(R3++),R8 

ADD  R8,R7,R4 

ST 

0(R3++)5R8 

ST 

0(R3++),R8 

Figure  10.22:  Code  after  software  pipelining  and  register  allocation  in  Exam 
ple  10.15 

E x a m p le  1 0 . 1 6:  T he  code 

for  (i = 0;  i  <  n;  i++)  { 
sum = sum + A[i] ; 
B[i] = A[i] * b; 

} 

has  a  d a ta  dependence  between  consecutive  iterations,  because  the  previous 
value of sum is  added to  A[i]  to  create a new value of sum.  It  is  possible to execute 
the  summation  in  0(logn)  time  if  the  machine  can  deliver  sufficient  parallelism, 
but  for  the  sake  of  this  discussion,  we  simply  assume  t h at  all  the  sequential 
dependences  must  be  obeyed,  and  t h at  the  additions  must  be  performed  in  the 
original  sequential  order.  Because  our  assumed  machine  model  takes  two  clocks 
to  complete  an ADD,  the  loop  cannot  execute  faster  t h an  one  iteration  every  two 
clocks.  Giving  the  machine  more  adders  or  multipliers  will  not  make  this  loop 
run  any  faster.  The  throughput  of  do-across  loops  like  this  one  is  limited  by 
t he  chain  of  dependences  across  iterations. 

T he  best  locally  compacted  schedule  for  each  iteration  is  shown  in  Fig. 
10.23(a),  and  the  software-pipelined  code  is  in  Fig. 10.23(b).  This  software-
pipelined  loop  starts  an  iteration  every  two  clocks,  and  thus  operates  at  the 
optimal  rate. 

• 

10.5. 

SOFTWARE  PIPELINING 

745 

//  Rl  = &A;  R2  = &B 

//  R3  =  sum 

//  R4  = b 

//  RIO  =  n-1 

L:  LD R5,  0(R1++) 
MUL R6,  R5,  R4 
ADD R3,  R3,  R4 

ST R6,  0(R2++) 

BL RIO,  L 

(a)  The  best  locally  compacted  schedule. 

//  Rl  = &A;  R2  = &B 

//  R3  =  sum 

//  R4 = b 

//  RIO  =  n-2 

LD R5,  0(R1++) 
MUL R6,  R5,  R4 
L:  ADD R3,  R3,  R4 

ST R6,  0(R2++) 

LD R5,  0(R1++) 

MUL R6,  R5,  R4  BL RIO,  L 
ADD R3,  R3,  R4 
ST R6,  0(R2++) 

(b)  The  software-pipelined  version. 

Figure  10.23:  Software-pipelining  of  a  do-across  loop 

10.5.5  Goals  and  Constraints  of  Software  Pipelining 

T he  primary  goal  of  software  pipelining  is  to  maximize  the  throughput  of  a 
long-running  loop.  A  secondary  goal  is  to  keep  t he  size  of  t he  code  generated 
In  other  words,  the  software-pipelined  loop  should  have  a 
reasonably  small. 
small  steady  state  of  the  pipeline.  We  can  achieve  a  small  steady  state  by 
requiring  t h at  the  relative  schedule  of  each  iteration  be  the  same,  and  t h at  the 
iterations  be  initiated  at  a  constant  interval.  Since  the  throughput  of the  loop  is 
simply  the  inverse  of  the  initiation  interval,  t he  objective  of  software  pipelining 
is  to  minimize  this  interval. 

A  software-pipeline  schedule  for  a  data-dependence  graph  G  —  (N,  E)  can 

be  specified  by 

1.  An  initiation  interval  T  and 

2. A  relative  schedule  5"  t h at  specifies,  for  each  operation,  when  t h at  opera 
tion  is  executed  relative  to  the  start  of  the  iteration  to  which  it  belongs. 

746 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

Thus,  an  operation  n  in  the  ith  iteration,  counting  from  0,  is  executed  at  clock 
i  x  T+S(n).  Like  all  the  other  scheduling  problems,  software  pipelining  has  two 
kinds  of  constraints:  resources  and  d a ta  dependences.  We  discuss  each  kind  in 
detail  below. 

M o d u l ar  R e s o u r ce  R e s e r v a t i on 

Let  a  machine's  resources  be  represented  by  R  =  [ri,r2,  •. . ],  where  ri  is  the 
number  of  units  of  the  ith  kind  of  resource  available.  If  an  iteration  of  a  loop 
requires  ni  units  of resource  i,  then  the  average  initiation  interval  of a  pipelined 
loop  is  at  least  m.axi(rii/ri)  clock  cycles.  Software  pipelining  requires  t h at  t he 
initiation  intervals  between  any  pair  of  iterations  have  a  constant  value.  Thus, 
the  initiation  interval  must  have  at  least  maxi\ni/ri]  clocks.  If  max^(rii/ri)  is 
less  t h an  1,  it  is  useful  to  unroll  the  source  code  a  small  number  of times. 

E x a m p le  1 0 . 1 7:  Let  us  return  to  our  software-pipelined  loop  shown  in  Fig. 
10.20.  Recall  t h at  the  target  machine  can  issue  one  load,  one  arithmetic  op 
eration,  one  store,  and  one  loop-back  branch  per  clock.  Since  t he  loop  has 
two  loads,  two  arithmetic  operations,  and  one  store  operation,  t he  minimum 
initiation  interval  based  on  resource  constraints  is  2  clocks. 

Iteration  1 
Ld  AluSt 

Time 

Iteration  3 
Ld  AluSt 

Iteration  2 
Ld  AluSt 

I 

i 

Steady  state 
Ld  AluSt 

Iteration  4 
Ld  AluSt 

m 
k 

m 

Figure  10.24:  Resource  requirements  of  four  consecutive  iterations  from  t he 
code  in  Example  10.13 

Figure  10.24  shows  t he  resource  requirements  of  four  consecutive  iterations 
across  time.  More  resources  are  used  as  more  iterations  get  initiated,  culmi-

10.5. 

SOFTWARE  PIPELINING 

747 

nating  in  maximum  resource  commitment  in  the  steady  state.  Let  RT  be  the 
resource-reservation table  representing  t he  commitment  of one  iteration,  and  let 
RTS  represent  the  commitment  of  the  steady  state.  RTS  combines  the  commit 
ment  from  four  consecutive  iterations  started  T  clocks  apart.  The  commitment 
of  row  0  in  t he  table  RT$  corresponds  to  t he  sum  of t he  resources  committed  in 
RT[0],  RT[2],  RT[4],  and  RT[6].  Similarly,  the  commitment  of  row  1  in  the  ta 
ble  corresponds  to  the  sum  of  the  resources  committed  in  RT[1],  RT[3],  RT[h], 
and  RT[7].  T h at  is,  the  resources  committed  in  the  ith  row  in  the  steady  state 
are  given  by 

RTs[i}  = 

Y, 

RTW-

{t  |  (t  mod  2)=i} 

We  refer  to  the  resource-reservation  table  representing  the  steady  state  as  the 
table  of  the  pipelined 
modular  resource-reservation 

loop. 

To  check  if  the  software-pipeline  schedule  has  any  resource  conflicts,  we  can 
simply  check t he  commitment  of t he  modular  resource-reservation table.  Surely, 
if the  commitment  in  the  steady  state  can  be  satisfied,  so  can  the  commitments 
in  the  prolog  and  epilog,  the  portions  of  code  before  and  after  the  steady-state 
loop. 

• 

In  general,  given  an  initiation  interval  T  and  a  resource-reservation  table  of 
an  iteration  RT,  the  pipelined  schedule  has  no  resource  conflicts  on  a  machine 
with  resource  vector  R  if  and  only  if  RTs[i]  <  R  for  a l l*  =  0 , 1 , . ..  , T  —  1. 

D a t a - D e p e n d e n ce  C o n s t r a i n ts 

D a ta  dependences  in  software  pipelining  are  different  from  those  we  have  en 
countered  so  far  because  they  can  form  cycles.  An  operation  may  depend  on 
the  result  of  the  same  operation  from  a  previous  iteration.  It  is  no  longer  ade 
quate  to  label  a  dependence  edge  by  just  the  delay;  we  also  need  to  distinguish 
between  instances  of  the  same  operation  in  different  iterations.  We  label  a  de 
pendence  edge  ni  -»•  n2  with  label  (8,  d)  if  operation  n2  in  iteration  i  must  be 
delayed  by  at  least  d  clocks  after  the  execution  of operation  n\  in  iteration  i — 8. 
Let  S,  a  function  from  the  nodes  of  the  data-dependence  graph  to  integers,  be 
the  software  pipeline  schedule,  and  let  T  be  the  initiation  interval  target.  Then 

(SxT) 

+ 

S(n2)~S(ni)>d. 

T he  iteration  difference,  8,  must  be  nonnegative.  Moreover,  given  a  cycle  of 
data-dependence  edges,  at  least  one  of  the  edges  has  a  positive  iteration  differ 
ence. 

E x a m p le  1 0 . 1 8:  Consider  the  following  loop,  and  suppose  we  do  not  know 
the  values  of p  and  q: 

for  (i  =  0;  i  <  n;  i++) 
*(p++)  =  *(q++)  + c; 

748 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

We  must  assume  t h at  any  pair  of  *(p++)  and  *(q++)  accesses  may  refer  to 
the  same  memory  location.  Thus,  all  the  reads  and  writes  must  execute  in 
the  original  sequential  order.  Assuming  t h at  t he  target  machine  has  the  same 
characteristics  as  t h at  described  in  Example  10.13,  the  data-dependence  edges 
for  this  code  are  as  shown  in  Fig.  10.25.  Note,  however,  t h at  we  ignore  the 
loop-control  instructions  t h at  would  have  to  be  present,  either  computing  and 
testing  i,  or  doing  the  test  based  on  the  value  of  Rl  or  R2. 

• 

//  R l,  R2  =  q,  p 
//  R3  =  c 

LD  R 4 , 0 ( R 1 + +) 

r< 0, l> 

r 

< 1 , 1> 

ADD  R5  , R 4 , R3 

< 0 , 2> 

ST  0 ( R 2 + + ) , R5 

l2 

l3 

Figure  10.25:  Data-dependence  graph  for  Example  10.18 

The  iteration  difference  between  related  operations  can  be  greater  t h an  one, 

as  shown  in  the  following  example: 

f or  (i  =  2; 

i  <  n; 

i + +) 

A [ i]  =  B [ i]  +  A [ i - 2] 

Here  the  value  written  in  iteration  i  is  used  two  iterations later.  T he  dependence 
edge  between  the  store  of  A[i]  and  the  load  of  A[i  —  2]  thus  has  a  difference  of 
2  iterations. 

The  presence  of  data-dependence  cycles  in  a  loop  imposes  yet  another  limit 
on  its  execution  throughput.  For  example,  the  data-dependence  cycle  in  Fig. 
10.25  imposes  a  delay  of  4  clock  ticks  between  load  operations  from  consecutive 
iterations.  T h at  is,  loops  cannot  execute  at  a  r a te  faster  t h an  one  iteration 
every  4  clocks. 

The  initiation  interval  of  a  pipelined  loop  is  no  smaller  t h an 

m ax 
c  a  c y c le  in  G 

Yje  in  c de 

X^e 

in  c  ^e 

clocks. 

In  summary,  the  initiation  interval  of  each  software-pipelined  loop  is  bound 
ed  by  the  resource  usage  in  each  iteration.  Namely,  t he  initiation  interval  must 
be  no  smaller  t h an  the  ratio  of  units  needed  of  each  resource  and  t he  units 

10.5. 

SOFTWARE  PIPELINING 

749 

available  on  the  machine.  In  addition,  if the  loops  have  data-dependence  cycles, 
then  the  initiation  interval  is  further  constrained  by  the  sum  of  the  delays  in 
t he  cycle  divided  by  the  sum  of  the  iteration  differences.  T he  largest  of  these 
quantities  defines  a  lower  bound  on  the  initiation  interval. 

10.5.6  A  Software-Pipelining  Algorithm 

The  goal  of  software  pipelining  is  to  find  a  schedule  with  the  smallest  possible 
initiation  interval.  The  problem  is  NP-complete,  and  can  be  formulated  as  an 
integer-linear-programming  problem.  We  have  shown  t h at  if  we  know  what  the 
minimum  initiation  interval  is,  the  scheduling  algorithm  can  avoid  resource  con 
flicts  by  using  the  modular  resource-reservation  table  in  placing  each  operation. 
But  we  do  not  know  what  the  minimum  initiation  interval  is  until  we  can  find 
a  schedule.  How  do  we  resolve  this  circularity? 

We  know  t h at  the  initiation  interval  must  be  greater  t h an  t he  bound  com 
puted  from  a  loop's  resource  requirement  and  dependence  cycles  as  discussed 
above.  If  we  can  find  a  schedule  meeting  this  bound,  we  have  found  t he  opti 
mal  schedule.  If  we  fail  to  find  such  a  schedule,  we  can  try  again  with  larger 
initiation  intervals  until  a  schedule  is  found.  Note  t h at  if heuristics,  rather  t h an 
exhaustive  search,  are  used,  this  process  may  not  find  the  optimal  schedule. 

Whether  we  can  find  a  schedule  near  the  lower  bound  depends  on  properties 
of  the  data-dependence  graph  and  the  architecture  of  the  target  machine.  We 
can  easily  find  t he  optimal  schedule  if  t he  dependence  graph  is  acyclic  and 
if  every  machine  instruction  needs  only  one  unit  of  one  resource. 
It  is  also 
easy  to  find  a  schedule  close  to  t he  lower  bound  if  there  are  more  hardware 
resources  t h an  can  be  used  by  graphs  with  dependence  cycles.  For  such  cases, 
it  is  advisable  to  start  with  t he  lower  bound  as  the  initial  initiation-interval 
target,  then  keep  increasing  the  target  by  just  one  clock  with  each  scheduling 
a t t e m p t.  Another  possibility  is  to  find  the  initiation  interval  using  a  binary 
search.  We  can  use  as  an  upper  bound  on  the  initiation  interval  the  length  of 
t he  schedule  for  one  iteration  produced  by  list  scheduling. 

10.5.7  Scheduling  Acyclic  Data-Dependence  Graphs 

For  simplicity,  we  assume  for  now  t h at  the  loop  to  be  software  pipelined  contains 
only  one  basic  block.  This  assumption  will  be  relaxed  in  Section  10.5.11. 

A l g o r i t hm  1 0 . 1 9:  Software  pipelining  an  acyclic  dependence  graph. 

I N P U T:  A  machine-resource  vector  R  =  [ n , r2, . . . ],  where  ^  is  the  number 
of  units  available  of  the  ith  kind  of  resource,  and  a  data-dependence  graph 
G  =  (N,E).  Each  operation  n  in  N  is  labeled  with  its  resource-reservation 
table  RTn;  each  edge  e  =  m 
n2  in  E  is  labeled  with  {Se,de)  indicating  t h at 
n2  must  execute  no  earlier  t h an  de  clocks  after  node  ni  from  the  Seth  preceding 
iteration. 

O U T P U T:  A  software-pipelined  schedule  S  and  an  initiation  interval  T. 

750 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

M E T H O D:  Execute  the  program  in  Fig.  10.26. 

• 

main()  { 

IQ  =  max 

j 

--

-
rj 

for  (T  =  To, T0  +  1 , . ..  ,  until  all  nodes  in  N  are  scheduled)  { 
RT  =  an  empty  reservation  table  with  T  rows; 
for  (each  n  in  N  in  prioritized  topological  order)  { 

s0  =  m a xe= p ^„ 
for  (s  =  s0, so  +  1,  •  •  •  , s0  +  T  -  1) 

in  E(S(P)  +  de); 

if  (NodeScheduled(RT,  T,  n,  s)  break; 

if  (n  cannot  be  scheduled  in  RT)  break; 

} 

} 

} 

NodeScheduled(RT,  T,  n,  s)  { 

RT'  =  RT; 
for  (each  row  i  in  RTn) 

RT'[(s  +  i)  m od  T]  -  i2T'[(s  +  i)  m od  T]  +  RTn\i]; 

if  (for  a l H,  ET'(«)  <  R)  { 
RT  =  i£T'; 
5 ( n)  =  s; 
r e t u rn  t r u e; 

} 
e l se  r e t u rn  false; 

} 

Figure  10.26:  Software-pipelining  algorithm  for  acyclic  graphs 

Algorithm  10.19  software  pipelines  acyclic  data-dependence  graphs.  The 

algorithm  first  finds  a  bound  on  the  initiation  interval,  To,  based  on  the  re 
source  requirements  of  the  operations  in  t he  graph. 
It  then  a t t e m p ts  to  find 
a  software-pipelined  schedule  starting  with  To  as  the  target  initiation  interval. 
T he  algorithm  repeats  with  increasingly  larger  initiation  intervals  if  it  fails  to 
find  a  schedule. 

T he  algorithm  uses  a  list-scheduling  approach  in  each  a t t e m p t. 

It  uses  a 
modular  resource-reservation  RT  to  keep  track  of  t he  resource  commitment  in 
t he  steady  state.  Operations  are  scheduled  in  topological  order  so  t h at  the 
d a ta  dependences  can  always  be  satisfied  by  delaying  operations.  To  schedule 
an  operation,  it  first  finds  a  lower  bound  so  according  to  t he  data-dependence 
constraints. 
It  then  invokes  NodeScheduled  to  check  for  possible  resource  con 
flicts  in  t he  steady  state.  If  there  is  a  resource  conflict,  the  algorithm  tries  to 
schedule  the  operation  in  the  next  clock.  If t he  operation  is  found  to  conflict  for 

10.5. 

SOFTWARE  PIPELINING 

751 

T  consecutive  clocks,  because  of  the  modular  nature  of  resource-conflict  detec 
tion,  further  a t t e m p ts  are  guaranteed  to  be  futile.  At  t h at  point,  the  algorithm 
considers  the  a t t e m pt  a  failure,  and  another  initiation  interval  is  tried. 

The  heuristics  of scheduling  operations  as  soon  as  possible  tends  to  minimize 
t he  length  of  t he  schedule  for  an  iteration.  Scheduling  an  instruction  as  early 
as  possible,  however,  can  lengthen  the  lifetimes  of some  variables.  For  example, 
loads  of  d a ta  tend  to  be  scheduled  early,  sometimes  long  before  they  are  used. 
One  simple  heuristic  is  to  schedule  t he  dependence  graph  backwards  because 
there  are  usually  more  loads  t h an  stores. 

10.5.8  Scheduling  Cyclic  Dependence  Graphs 

Dependence  cycles  complicate  software  pipelining  significantly.  W h en  schedul 
ing  operations  in  an  acyclic  graph  in  topological  order,  d a ta  dependences  with 
scheduled  operations  can  impose  only  a  lower  bound  on  t he  placement  of  each 
operation.  As  a  result,  it  is  always  possible  to  satisfy  the  data-dependence  con 
straints  by  delaying  operations.  T he  concept  of  "topological  order"  does  not 
apply  to  cyclic  graphs.  In  fact,  given  a  pair  of  operations  sharing  a  cycle,  plac 
ing  one  operation  will  impose  both  a  lower  and  upper  bound  on  the  placement 
of  t he  second. 

Let  ni  and  n2  be  two  operations  in  a  dependence  cycle,  5  be  a  software-
pipeline  schedule,  and  T  be  the  initiation  interval  for  the  schedule.  A  depen 
dence  edge  m 
imposes  the  following  constraint  on 
S(ni) 

-»•  n2  with  label  (6i,di) 

S(n2): 

and 

(S1 

xT)  +  S(n2)-S(ni) 

> d i. 

Similarly,  a  dependence  edge  ( n i , n2)  with  label  (52,d2)  imposes  constraint 

(S2xT) 

+ 

S(m)-S(n2)>d2. 

Thus 

S(ni)  +dx~  (51  x  T)  <  S(n2)  <  S(ni)  ~d2  +  {d2  x  T). 

A  strongly  connected  component  (SCC)  in  a  graph  is  a  set  of  nodes  where 

every  node  in  the  component  can  be  reached  by  every  other  node  in  the  compo 
nent.  Scheduling  one  node  in  an  SCC  will  bound  the  time  of  every  other  node 
in  the  component  b o th  from  above  and  from  below.  Transitively,  if  there  exists 
a  p a th  p  leading  from  n\  to  n2,  then 

e 

in  p 

(10.1) 

Observe  t h at 

752 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

•  Around  any  cycle,  the  sum  of  the  S's  must  be  positive. 

If  it  were  0  or 
negative,  then  it  would  say  t h at  an  operation  in  the  cycle  either  had  to 
precede  itself  or  be  executed  at  the  same  clock  for  all  iterations. 

•  The  schedule  of operations  within  an  iteration  is  the  same  for  all  iterations; 
t h at  requirement  is  essentially  t he  meaning  of  a  "software  pipeline."  As 
a  result,  the  sum  of  the  delays  (second  components  of  edge  labels  in  a 
data-dependence  graph)  around  a  cycle  is  a  lower  bound  on  t he  initiation 
interval  T. 

When  we  combine  these  two  points,  we  see  t h at  for  any  feasible  initiation  inter 
val  T,  the  value  of  t he  right  side  of  Equation  (10.1)  must  be  negative  or  zero. 
As  a  result,  the  strongest  constraints  on  the  placement  of  nodes  is  obtained 
from  the  simple  paths  —  those  paths  t h at  contain  no  cycles. 

Thus,  for  each  feasible  T,  computing  the  transitive  effect  of  d a ta  depen 
dences  on  each  pair  of  nodes  is  equivalent  to  finding  the  length  of  the  longest 
simple  p a th  from  the  first  node  to  the  second.  Moreover,  since  cycles  cannot 
increase  the  length  of  a  p a t h,  we  can  use  a  simple  dynamic-programming  al 
gorithm  to  find  t he  longest  paths  without  the  "simple-path"  requirement,  and 
be  sure  t h at  the  resulting  lengths  will  also  be  the  lengths  of  the  longest  simple 
paths  (see  Exercise  10.5.7). 

Figure  10.27:  Dependence  graph  and  resource  requirement  in  Example  10.20 

E x a m p le  1 0 . 20  :  Figure  10.27  shows  a  data-dependence  graph  with  four  nodes 
a, b, c, d.  Attached  to  each  node  is  its  resource-reservation  table;  attached  to 
each  edge  is  its  iteration  difference  and  delay.  Assume  for  this  example  t h at  t he 
target  machine  has  one  unit  of each  kind  of resource.  Since  there  are  three  uses 
of the  first  resource  and  two  of the  second,  the  initiation  interval  must  be  no  less 
t h an  3  clocks.  There are two  SCC's in  this  graph:  t he  first  is  a trivial  component 
consisting  of t he  node a  alone,  and  the  second  consists  of nodes  6, c,  and d.  T he 
longest  cycle, b, c, d, b,  has  a  total  delay  of 3  clocks  connecting  nodes  t h at  are 
1  iteration  apart.  Thus,  the  lower  bound  on  the  initiation  interval  provided  by 
data-dependence  cycle  constraints  is  also  3  clocks. 

10.5. 

SOFTWARE  PIPELINING 

753 

Placing  any  of  6,  c,  or  d  in  a  schedule  constrains  all  t he  other  nodes  in  the 
component.  Let  T  be  the  initiation  interval.  Figure  10.28  shows  the  transitive 
dependences.  P a rt  (a)  shows  the  delay  and  t he  iteration  difference  5,  for  each 
edge.  T he  delay  is  represented  directly,  but  S  is  represented  by  "adding"  to  the 
delay  the  value  —  ST. 

Figure  10.28(b)  shows  the  length  of  the  longest  simple  p a th  between  two 
nodes,  when  such  a  p a th  exists;  its  entries  are  the  sums  of the  expressions  given 
by  Fig.  10.28(a),  for  each  edge  along  the  p a t h.  Then,  in  (c)  and  (d),  we  see  the 
expressions  of  (b)  with  the  two  relevant  values  of T,  t h at  is,  3  and  4,  substituted 
for  T.  T he  difference  between  t he  schedule  of  two  nodes  S ( n2)  -  5 ( n i)  must 
be  no  less  t h an  the  value  given  in  entry  ( n i, n2)  in  each  of the  tables  (c)  or  (d), 
depending  on  t he  value  of  T  chosen. 

For  instance,  consider  the  entry  in  Fig.  10.28  for  the  longest  (simple)  p a th 
from  c  to  6,  which  is  2  —  T.  The  longest  simple  p a th  from  c  to  b  is  c  ->•  d  ->•  b. 
The  total  delay  is  2  along this  path,  and  the  sum  of the  5's  is  1,  representing t he 
fact  t h at  the  iteration  number  must  increase  by  1.  Since  T  is  the  time  by  which 
each  iteration  follows  the  previous,  the  clock  at  which  b  must  be  scheduled  is 
at  least  2  —  T  clocks  after  the  clock  at  which  c  is  scheduled.  Since  T  is  at  least 
3,  we  are  really  saying  t h at  b  may  be  scheduled  T  —  2  clocks  before  c,  or  later 
t h an  t h at  clock,  but  not  earlier. 

Notice  t h at  considering  nonsimple  paths  from  c  to  b  does  not  produce  a 
stronger constraint.  We  can  add to the  p a th  c  —>  d  -»  b any number of iterations 
of  t he  cycle  involving  d  and  b.  If  we  add  k  such  cycles,  we  get  a  p a th  length 
of  2  —  T  +  k(3  —  T ),  since  the  total  delay  along  the  p a th  is  3,  and  the  sum  of 
t he  5's  is  1.  Since  T  >  3,  this  length  can  never  exceed  2  — T;  i.e.,  the  strongest 
lower  bound  on  the  clock  of  b  relative  to  the  clock  of  c  is  2  —  T,  the  bound  we 
get  by  considering  the  longest  simple  p a t h. 

For  example,  from  entries  (6, c)  and  (c, 6),  we  see  t h at 

T h at  is, 

If  T  =  3, 

S(c)-S(b) 
5 ( 6 ) - 5 ( c) 

> 

1 

> 

2-T. 

S{b)  +  1  <  5(c)  <  S(b)  -2  +  T. 

5(6)  +  1  <  5(c)  <  5(6)  +  1. 

P ut  equivalently,  c  must  be  scheduled  one  clock  after  6.  If  T  =  4,  however, 

5(6)  +  1  <  5(c)  <  5(6)  +  2. 

T h at  is,  c  is  scheduled  one  or  two  clocks  after  6. 

Given  the  all-points  longest  p a th  information,  we  can  easily  compute  the 
range  where  it  is  legal  to  place  a  node  due  to  d a ta  dependences.  We  see  t h at 
there  is  no  slack  in  t he  case  when  T  =  3,  and  the  slack  increases  as  T  increases. 
• 

754 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

a

b

ed 

a

b

ed 

a 

b 

c 

d 

a 

b 

c 

d 

2 

l-T 

1 

2 

1 

(a) Original edges. 

a

b

ed 

2 

-1 

-2 

3 

1 

-1 

4 

2 

1 

a 

b 

c 

d 

a 

b 

c 

d 

3 

1 

2 

2-T 

l-T 

2-T 

4 

2 

1 

(b) Longest simple paths. 

a

b

ed 

2 

-2 

-3 

3 

1 

-2 

4 

2 

1 

(c) Longest simple paths (T=3). 

(d) Longest simple paths (T=4). 

Figure  10.28:  Transitive  dependences  in  Example  10.20 

A l g o r i t hm  1 0 . 2 1:  Software  pipelining. 

I N P U T:  A  machine-resource  vector  R  =  [ri,r2:...],  where  r«  is  the  number 
of  units  available  of  the  ith  kind  of  resource,  and  a  data-dependence  graph 
G  =  (N,E).  Each  operation  n  in  N  is  labeled  with  its  resource-reservation 
table  RTn]  each  edge  e  =  ri\  ->  n2  in  E  is  labeled  with  (Se,de)  indicating  t h at 
n2  must  execute  no  earlier  t h an  de  clocks  after  node  n\  from  the  5eth  preceding 
iteration. 

O U T P U T:  A  software-pipelined  schedule  S  and  an  initiation  interval  T. 

M E T H O D:  Execute  the  program  in  Fig.  10.29. 

• 

Algorithm  10.21  has  a high-level  structure  similar  to  t h at  of Algorithm  10.19, 
which  only  handles  acyclic  graphs.  The  minimum  initiation  interval  in  this  case 
is  bounded  not  just  by  resource  requirements,  but  also  by  the  data-dependence 
cycles  in  the  graph.  The  graph  is  scheduled  one  strongly  connected  component 
at  a  time.  By  treating  each  strongly  connected  component  as  a  unit,  edges  be 
tween  strongly  connected  components  necessarily  form  an  acyclic  graph.  While 
the  top-level  loop  in  Algorithm  10.19  schedules  nodes  in  the  graph  in  topological 
order,  the  top-level  loop  in  Algorithm  10.21  schedules  strongly  connected  com 
ponents  in  topological  order.  As  before,  if the  algorithm  fails  to  schedule  all  the 
components,  then  a  larger  initiation  interval  is  tried.  Note  t h at  Algorithm  10.21 
behaves  exactly  like  Algorithm  10.19  if  given  an  acyclic  data-dependence  graph. 
Algorithm  10.21  computes  two  more  sets  of  edges:  E'  is  the  set  of  all  edges 
whose  iteration  difference  is  0,  E*  is  the  all-points  longest-path  edges.  T h at  is, 

10.5.  SOFTWARE  PIPELINING 

755 

mainQ  { 

E'  =  {e\e  in  E,Se  =  0}; 

To  =  m ax  (  max 

3 

En,iRTn(hJ) 

max 
c  a c y c l e in  G 

Z^e 

in  c  ^' 

in  c  ^e 

for  (T  =  T0, T0  +  1 , . ..  or  until  all  SCC's  in  G  are  scheduled)  { 

RT  —  an  empty  reservation  table  with  T  rows; 
E* 
for  (each  SCC  C  in  G  in  prioritized  topological  order)  { 

AUPairsLongestPath(G,T); 

= 

for  (all  n  in  C) 

S0(n)  =  m a xe = p_ >n  jn  E*,p  s c h e d u l ed  (S(p)  +  de)\ 

first  =  some  n  such  t h at  so(n)  is  a  minimum; 
so  =  s0(first); 
for  (s  =  So;  s  <  s0  +  T;  s  =  s  +  1) 

if  (SccScheduled 

(RT,T,C,  first,  s))  break; 

if  (C  cannot  be  scheduled  in  RT)  break; 

} 

} 

} 

SccScheduled(RT,  T,  c,  first,  s)  { 

RT'  =  RT; 
if  (not  NodeScheduled  (RT',T,  first,  s))  r e t u rn 
for  (each  remaining  n  in  c  in  prioritized 

false; 

topological  order  of  edges  in  E')  { 

in  E*,n' 

sl  —  ma xe = n' _m 
Su  =  m i ne = n_ ^ .n' 
for  (s  =  s/;  <  m i n ( su,  s;  +  T  -  1);  s  =  s  +  1) 
break; 

if  NodeScheduled(RT',T,n,s) 

in  c , n'  s c h e d u l ed  S(fl')  +  de  —  (8e  X  T ); 
in  c , n'  s c h e d u l ed  S(fl')  —  de  +  ((5e  X  T ); 

in  E*,n' 

if  (n  cannot  be  scheduled  in  RT')  r e t u rn  false; 

} 
RT  =  RT'; 
r e t u rn  true; 

} 

Figure  10.29:  A  software-pipelining  algorithm  for  cyclic  dependence  graphs 

756 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

for  each  pair  of nodes  (p, n ),  there  is  an  edge  e  in  E*  whose  associated  distance 
de  is  the  length  of the  longest  simple  p a th  from  pton,  provided  t h at  there  is  at 
least  one  p a th  from  p  to  n.  E*  is  computed  for  each  value  of  T,  the  initiation-
interval  target.  It  is  also  possible  to  perform  this  computation  just  once  with 
a  symbolic  value  of  T  and  then  substitute  for  T  in  each  iteration,  as  we  did  in 
Example  10.20. 

Algorithm  10.21  uses  backtracking.  If  it  fails  to  schedule  a  SCC,  it  tries  to 
reschedule  the  entire  SCC  a  clock  later.  These  scheduling  a t t e m p ts  continue  for 
up  to  T  clocks.  Backtracking  is  important  because,  as  shown  in  Example  10.20, 
the  placement  of  the  first  node  in  an  SCC  can  fully  dictate  the  schedule  of  all 
other  nodes.  If  the  schedule  happens  not  to  fit  with  the  schedule  created  thus 
far,  the  a t t e m pt  fails. 

To  schedule  a  SCC,  the  algorithm  determines  the  earliest  time  each  node 
in  the  component  can  be  scheduled  satisfying  the  transitive  d a ta  dependences 
in  E*. 
It  then  picks  the  one  with  the  earliest  start  time  as  the  first  node 
to  schedule.  The  algorithm  then  invokes  SccScheduled  to  try  to  schedule  the 
component  at  t he  earliest  start  time.  T he  algorithm  makes  at  most  T  a t t e m p ts 
with  successively  greater  start  times.  If it  fails,  then  t he  algorithm  tries  another 
initiation  interval. 

The  SccScheduled  algorithm  resembles  Algorithm  10.19,  but  has  three  major 

differences. 

1.  T he  goal  of  SccScheduled is  to  schedule  t he  strongly  connected  component 
at  the  given  time  slot  s.  If  the  first  node  of  the  strongly  connected  com 
ponent  cannot  be  scheduled  at  s,  SccScheduled  returns  false.  T he  main 
function  can  invoke  SccScheduled  again  with  a  later  time  slot  if  t h at  is 
desired. 

2.  The  nodes  in  the  strongly  connected  component  are  scheduled  in  topolog 
ical  order,  based  on  the  edges  in  E'.  Because  the  iteration  differences  on 
all  the  edges  in  E'  are  0,  these  edges  do  not  cross  any  iteration  boundaries 
and  cannot  form  cycles.  (Edges  t h at  cross  iteration  boundaries  are  known 
as  loop  carried).  Only  loop-carried  dependences  place  upper  bounds  on 
where  operations  can  be  scheduled.  So,  this  scheduling  order,  along  with 
the  strategy  of  scheduling  each  operation  as  early  as  possible,  maximizes 
the  ranges  in  which  subsequent  nodes  can  be  scheduled. 

3.  For  strongly  connected  components,  dependences  impose  b o th  a  lower  and 
upper  bound  on  the  range  in  which  a  node  can  be  scheduled.  SccSched 
uled  computes  these  ranges  and  uses  t h em  to  further  limit  the  scheduling 
a t t e m p t s. 

E x a m p le  1 0 . 22  :  Let  us  apply  Algorithm  10.21  to  the  cyclic  data-dependence 
graph  in  Example  10.20.  The  algorithm  first  computes  t h at  the  bound  on  the 
initiation  interval  for  this  example  is  3  clocks.  We  note  t h at  it  is  not  possible 
to  meet  this  lower  bound.  When  the  initiation  interval  T  is  3,  t he  transitive 

10.5. 

SOFTWARE  PIPELINING 

757 

dependences  in  Fig.  10.28  dictate  t h at  S(d)  -  S(b)  =  2.  Scheduling  nodes  b 
and  d  two  clocks  apart  will  produce  a  conflict  in  a  modular  resource-reservation 
table  of  length  3. 

A t t e m pt 

Initiation 
Interval 

Node 

Range 

Schedule 

Modular 
Resource 
Reservation 

1 

2 

3 

T  =  3 

T  =  3 

T  =  3 

4 

T  =  4 

5 

6 

T  =  4 

T  =  4 

a 
6 
c 
a 

c 
d 
a 
b 
c 
d 

a 
b 
c 
d 

a 
b 
c 
d 

a 
b 
c 
d 

(0,oo) 
(2,oo) 
(3,3) 
(0,oo) 
(2,oo) 
(4,4) 
(5,5) 
(0,oo) 
(2,oo) 
(5,5) 
(6,6) 

(0,oo) 
(2,oo) 
(3,4) 
(4,5) 

(0,oo) 
(2,oo) 
(4,5) 
(5,5) 

(0,oo) 
(2,oo) 
(5,6) 
(6,7) 

0 
2 

0 
3 
4 

0 
4 
5 

0 
2 
3 

0 
3 
5 

0 
4 
5 
6 

5i 

Figure  10.30:  Behavior  of  Algorithm  10.21  on  Example  10.20 

Figure  10.30  shows  how  Algorithm  10.21  behaves  with  this  example.  It  first 
tries  to  find  a  schedule  with  a  3-clock  initiation  interval.  The  a t t e m pt  starts  by 
scheduling  nodes  a  and  b  as  early  as  possible.  However,  once  node  b  is  placed  in 
clock  2,  node  c  can  only  be  placed  at  clock  3,  which  conflicts  with  t he  resource 
usage  of  node  a.  T h at  is,  a  and  c  both  need  the  first  resource  at  clocks  t h at 
have  a  remainder  of  0  modulo  3. 

The  algorithm  backtracks  and  tries  to  schedule  the  strongly  connected  com 
ponent  {6, c, d}  a  clock  later.  This  time  node  b  is  scheduled  at  clock  3,  and  node 
c  is  scheduled  successfully  at  clock  4.  Node  d,  however,  cannot  be  scheduled  in 

758 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

clock  5.  T h at  is,  both  b  and  d  need  the  second  resource  at  clocks  t h at  have  a 
remainder  of  0  modulo  3.  Note  t h at  it  is  just  a  coincidence  t h at  the  two  con 
flicts  discovered  so  far  are  at  clocks  with  a  remainder  of 0  modulo  3;  t he  conflict 
might  have  occurred  at  clocks  with  remainder  1  or  2  in  another  example. 

The  algorithm  repeats  by  delaying  the  start  of  t he  SCC  {b,c,  d]  by  one 
more  clock.  But,  as  discussed  earlier,  this  SCC  can  never  be  scheduled  with  an 
initiation  interval  of  3  clocks,  so  the  a t t e m pt  is  bound  to  fail.  At  this  point, 
the  algorithm  gives  up  and  tries  to  find  a  schedule  with  an  initiation  interval 
of  4  clocks.  The  algorithm  eventually  finds  the  optimal  schedule  on  its  sixth 
a t t e m p t. 

• 

10.5.9 

Improvements  to  the  Pipelining  Algorithms 

Algorithm  10.21  is  a  rather  simple  algorithm,  although  it  has  been  found  to 
work  well  on  actual  machine  targets.  The  important  elements  in  this  algorithm 
are 

1.  T he  use  of  a  modular  resource-reservation  table  to  check  for  resource 

conflicts  in  the  steady  state. 

2.  The  need  to  compute  the  transitive  dependence  relations  to  find  the  legal 
range  in  which  a  node  can  be  scheduled  in  t he  presence  of  dependence 
cycles. 

3.  Backtracking  is  useful,  and  nodes  on  critical  cycles  (cycles  t h at  place  t he 
highest  lower  bound  on  the  initiation  interval  T)  must  be  rescheduled 
together  because  there  is  no  slack  between  them. 

There  are  many  ways  to  improve  Algorithm  10.21.  For  instance,  the  al 
gorithm  takes  a  while  to  realize  t h at  a  3-clock  initiation  interval  is  infeasible 
for  the  simple  Example  10.22.  We  can  schedule  the  strongly  connected  com 
ponents  independently  first  to  determine  if  the  initiation  interval  is  feasible  for 
each  component. 

We  can  also  modify  t he  order  in  which  t he  nodes  are  scheduled.  The  order 
used  in  Algorithm  10.21  has  a  few  disadvantages.  First,  because  nontrivial 
SCC's  are harder to  schedule,  it  is  desirable to  schedule t h em  first.  Second,  some 
of t he  registers  may  have  unnecessarily  long  lifetimes.  It  is  desirable  to  pull  the 
definitions  closer  to  the  uses.  One  possibility  is  to  start  with  scheduling  strongly 
connected  components  with  critical  cycles  first,  then  extend  the  schedule  on 
both  ends. 

10.5.10  Modular  Variable  Expansion 

A  scalar  variable  is  said  to  be  privatizable  in  a  loop  if  its  live  range  falls  within 
an  iteration  of the  loop.  In  other  words,  a  privatizable  variable  must  not  be  live 
upon  either  entry  or  exit  of any  iteration.  These  variables  are  so  named  because 

10.5. 

SOFTWARE  PIPELINING 

759 

Are  There  Alternatives  to  Heuristics? 

We  can  formulate 
t he  problem  of  simultaneously  finding  an  optimal 
software  pipeline  schedule  and  register  assignment  as  an  integer-linear-
programming  problem.  While  many  integer  linear  programs  can  be  solved 
quickly,  some  of  t h em  can  take  an  exorbitant  amount  of  time.  To  use  an 
integer-linear-programming  solver  in  a  compiler,  we  must  be  able  to  abort 
t he  procedure  if  it  does  not  complete  within  some  preset  limit. 

Such  an  approach  has  been  tried  on  a  target  machine  (the  SGI  R8000) 
empirically,  and  it  was  found  t h at  the  solver  could  find  the  optimal  solution 
for  a  large  percentage  of  the  programs  in  the  experiment  within  a  reason 
able  amount  of  time. 
It  turned  out  t h at  the  schedules  produced  using  a 
heuristic  approach  were  also  close  to  optimal.  The  results  suggest  t h a t, 
at  least  for  t h at  machine,  it  does  not  make  sense  to  use  the  integer-linear-
programming  approach,  especially  from  a  software  engineering  perspec 
tive.  Because  t he  integer-linear  solver  may  not  finish,  it  is  still  necessary 
to  implement  some  kind  of  a  heuristic  scheduler  in  t he  compiler.  Once 
such  a  heuristic  scheduler  is  in  place,  there  is  little  incentive  to  implement 
a  scheduler  based  on  integer  programming  techniques  as  well. 

different  processors  executing  different  iterations  in  a  loop  can  have  their  own 
private  copies  and  thus  not  interfere  with  one  another. 

Variable  expansion  refers  to  t he  transformation  of  converting  a  privatizable 

scalar  variable  into  an  array  and  having  the  ith  iteration  of  the  loop  read  and 
write  the  ith  element.  This  transformation  eliminates  the  antidependence  con 
straints  between  reads  in  one  iteration  and  writes  in  the  subsequent  iterations, 
as  well  as  output  dependences  between  writes  from  different  iterations. 
If  all 
loop-carried  dependences  can  be  eliminated,  all  the  iterations  in  the  loop  can 
be  executed  in  parallel. 

Eliminating  loop-carried  dependences,  and  thus  eliminating  cycles  in  t he 
data-dependence  graph,  can  greatly  improve  the  effectiveness  of  software  pipe 
lining.  As  illustrated  by  Example  10.15,  we  need  not  expand  a  privatizable 
variable  fully  by  the  number  of  iterations  in  the  loop.  Only  a  small  number  of 
iterations  can  be  executing  at  a  time,  and  privatizable  variables  may  simultane 
ously  be  live  in  an  even  smaller  number  of iterations.  T he  same  storage  can  thus 
be  reused  to  hold  variables  with  nonoverlapping  lifetimes.  More  specifically,  if 
the  lifetime  of  a  register  is  I  clocks,  and  the  initiation  interval  is  T,  then  only 
Q  =  I TI  values  can  be  live  at  any  one  point.  We  can  allocate  q  registers  to  the 
variable,  with  the  variable  in  the  ith  iteration  using  the  (i  mod  q)th  register. 
We  refer  to  this  transformation  as  modular  variable  expansion. 

A l g o r i t hm  1 0 . 23  :  Software  pipelining  with  modular  variable  expansion. 

I N P U T:  A  data-dependence  graph  and  a  machine-resource  description. 

760 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

O U T P U T:  Two  loops,  one  software  pipelined  and  one  unpipelined. 

M E T H O D: 

1.  Remove  the  loop-carried  antidependences  and  output  dependences  asso 

ciated  with  privatizable  variables  from  the  data-dependence  graph. 

2.  Software-pipeline  the  resulting  dependence  graph  using  Algorithm  10.21. 
Let  T  be  the  initiation  interval  for  which  a  schedule  is  found,  and  L  be 
the  length  of  the  schedule  for  one  iteration. 

3.  From  the  resulting  schedule,  compute  qv,  the  minimum  number  of  regis 

ters  needed  by  each  privatizable  variable  v.  Let  Q  =  m a xw  qv. 

4.  Generate  two  loops:  a  software-pipelined  loop  and  an  unpipelined  loop. 

The  software-pipelined  loop  has 

copies  of  the  iterations,  placed  T  clocks  apart.  It  has  a  prolog  with 

+  Q -1 

IT 

f 

-  1)T 

instructions,  a  steady  state  with  QT  instructions,  and  an  epilog  of  L  —  T 
instructions.  Insert  a  loop-back  instruction  t h at  branches  from  the  b o t t om 
of  t he  steady  state  to  t he  top  of  t he  steady  state. 

T he  number  of  registers  assigned  to  privatizable  variable  v  is 

Qv 

qv 
Q 

if  Q  mod  qv 
otherwise 

0 

T he  variable  v  in  iteration  i  uses  the  (i  mod  q'^th  register  assigned. 

Let  n  be  the  variable  representing  the  number  of  iterations  in  the  source 
loop.  The  software-pipelined  loop  is  executed  if 

n  > 

' L~ 

T 

+ 

Q-1. 

T he  number  of  times  the  loop-back  branch  is  taken  is 

ni 

Q 

Thus,  the  number  of  source  iterations  executed  by  the  software-pipelined 
loop  is 

ri2 

-  1  +  Qnx 

0 

if  n  >  \%\  +  Q  -  1 
otherwise 

The  number  of iterations  executed  by  the  unpipelined  loop  is  n3  =  n - n2. 

10.5. 

SOFTWARE  PIPELINING 

761 

• 

E x a m p le  1 0 . 2 4:  For  the  software-pipelined  loop  in  Fig.  10.22,  L  =  8,  T  —  2, 
and  Q  =  2.  T he  software-pipelined  loop  has  7  copies  of the  iterations,  with  the 
prolog,  steady  state,  and  epilog  having  6,  4,  and  6  instructions,  respectively. 
Let  n  be  the  number  of  iterations  in  the  source  loop.  The  software-pipelined 
loop  is  executed  if  n  >  5,  in  which  case  the  loop-back  branch  is  taken 

n — 3 
2 

times,  and  the  software-pipelined  loop  is  responsible  for 

of  the  iterations  in  the  source  loop. 

• 

Modular  expansion  increases  the  size  of  the  steady  state  by  a  factor  of 
Q.  Despite  this  increase,  the  code  generated  by  Algorithm  10.23  is  still  fairly 
compact.  In  the  worst  case,  the  software-pipelined  loop  would  take  three  times 
as  many  instructions  as  t h at  of the  schedule  for  one  iteration.  Roughly,  together 
with  the  extra  loop  generated  to  handle  the  left-over  iterations,  the  total  code 
size  is  about  four  times  the  original.  This  technique  is  usually  applied  to  tight 
inner  loops,  so  this  increase  is  reasonable. 

Algorithm  10.23  minimizes  code  expansion  at  the  expense  of  using  more 
registers.  We  can  reduce  register  usage  by  generating  more  code.  We  can  use 
the  minimum  qv  registers  for  each  variable  v  if  we  use  a  steady  state  with 

T  x  LCMvqv 

instructions.  Here,  LCMV  represents  the  operation  of  taking  the  least  common 
multiple  of  all  the  qv's,  as  v  ranges  over  all  the  privatizable  variables  (i.e.,  the 
smallest  integer  t h at  is  an  integer  multiple  of  all  the  (fo's).  Unfortunately,  the 
least  common  multiple  can  be  quite  large  even  for  a  few  small  <^'s. 

10.5.11  Conditional  Statements 

If  predicated  instructions  are  available,  we  can  convert  control-dependent  in 
structions  into  predicated  ones.  Predicated  instructions  can  be  software-pipe 
lined  like  any  other  operations.  However,  if  there  is  a  large  amount  of  data-
dependent  control  flow  within  the  loop  body,  scheduling  techniques  described 
in  Section  10.4  may  be  more  appropriate. 

If  a  machine  does  not  have  predicated  instructions,  we  can  use  the  concept 
of  hierarchical  reduction,  described  below,  to  handle  a  small  amount  of  data-
dependent  control  flow.  Like  Algorithm  10.11,  in  hierarchical  reduction  the 
control  constructs  in  the  loop  are  scheduled  inside-out,  starting  with  the  most 

762 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

deeply  nested  structures.  As  each  construct  is  scheduled,  the  entire  construct  is 
reduced  to  a  single  node  representing  all  the  scheduling  constraints  of  its  com 
ponents  with  respect  to  the  other  parts  of  the  program.  This  node  can  then  be 
scheduled  as  if  it  were  a  simple  node  within  the  surrounding  control  construct. 
The  scheduling  process  is  complete  when  t he  entire  program  is  reduced  to  a 
single  node. 

In  the  case  of  a  conditional  statement  with  "then"  and  "else"  branches,  we 

schedule  each  of  the  branches  independently.  Then: 

1.  The  constraints  of  the  entire  conditional  statement  are  conservatively 

taken  to  be  the  union  of  the  constraints  from  both  branches. 

2.  Its  resource  usage  is  the  maximum  of  the  resources  used  in  each  branch. 

3.  Its  precedence  constraints  are  the  union  of those  in  each  branch,  obtained 

by  pretending  t h at  both  branches  are  executed. 

This  node  can  then  be  scheduled  like  any  other  node.  Two  sets  of  code,  cor 
responding  tp  t he  two  branches,  are  generated.  Any  code  scheduled  in  parallel 
with  the  conditional  statement  is  duplicated  in  both  branches.  If  multiple  con 
ditional  statements  are  overlapped,  separate  code  must  be  generated  for  each 
combination  of  branches  executed  in  parallel. 

10.5.12  Hardware  Support  for  Software  Pipelining 

Specialized  hardware  support  has  been  proposed  for  minimizing  the  size  of 
software-pipelined  code.  The  rotating  register  file  in  the  Itanium  architecture  is 
one  such  example.  A  rotating  register  file  has  a  base  register,  which  is  added  to 
the  register  number  specified  in  the  code  to  derive  the  actual  register  accessed. 
We  can  get  different  iterations  in  a  loop  to  use  different  registers  simply  by 
changing  the  contents  of  the  base  register  at  the  boundary  of  each  iteration. 
The  Itanium  architecture  also  has  extensive  predicated  instruction  support.  Not 
only  can  predication  be  used  to  convert  control  dependence  to  d a ta  dependence 
but  it  also  can  be  used  to  avoid  generating  the  prologs  and  epilogs.  T he  body 
of  a  software-pipelined  loop  contains  a  superset  of  the  instructions  issued  in  the 
prolog  and  epilog.  We  can  simply  generate  the  code  for  t he  steady  state  and 
use  predication  appropriately  to  suppress  the  extra  operations  to  get  the  effects 
of  having  a  prolog  and  an  epilog. 

While  Itanium's  hardware  support  improves  t he  density  of  software-pipe 
lined  code,  we  must  also  realize  t h at  the  support  is  not  cheap.  Since  software 
pipelining  is  a  technique  intended  for  tight  innermost  loops,  pipelined  loops  tend 
to  be  small  anyway.  Specialized  support  for  software  pipelining  is  warranted 
principally  for  machines  t h at  are  intended  to  execute  many  software-pipelined 
loops  and  in  situations  where  it  is  very  important  to  minimize  code  size. 

10.5. 

SOFTWARE  PIPELINING 

763 

1) 
2) 
3) 
4) 
5) 
6) 
7) 
8) 

L:  LD  Rl,  a(R9) 
ST  b(R9),  Rl 

LD  R2,  c(R9) 

ADD R3,  Rl,  R2 

ST  c(R9),  R3 

SUB R4,  Rl,  R2 

ST  b(R9),  R4 

BL R9,  L 

Figure 10.31  Machine  code  for  Exercise 10.5.2 

10.5.13  Exercises  for  Section  10.5 

Exercise  1 0 . 5 . 1:  In  Example 10.20  we  showed  how  to  establish  the  bounds 
on  t he  relative  clocks  at  which  b  and  c  are  scheduled.  Compute  the  bounds  for 
each  of  five  other  pairs  of  nodes  (i)  for  general  T  (ii)  for  T = 3  (in)  for  T = 4. 

Exercise  1 0 . 5 .2 :  In Fig. 10.31  is the body of a loop.  Addresses such as a(R9) 
are  intended  to  be  memory  locations,  where  a  is  a constant,  and R9  is  the  register 
t h at  counts  iterations  through  the  loop.  You  may  assume  t h at  each  iteration 
of  the  loop  accesses  different  locations,  because R9  has  a  different  value.  Using 
t he  machine  model  of  Example 10.12,  schedule  the  loop  of  Fig. 10.31  in  the 
following  ways: 

a)  Keeping  each  iteration  as  tight  as  possible  (i.e.,  only  introduce  one  nop  af 
ter  each  arithmetic  operation),  unroll  the  loop  twice.  Schedule  the  second 
iteration  to  commence  at  the  earliest  possible  moment  without  violat 
ing  the  constraint  t h at  the  machine  can  only  do  one  load,  one  store,  one 
arithmetic  operation,  and  one  branch  at  any  clock. 

b)  Repeat  part  (a),  but  unroll  the  loop  three  times.  Again,  start  each  itera 

tion  as  soon  as  you  can,  subject  to  the  machine  constraints. 

!  c)  Construct  fully  pipelined  code  subject  to  the  machine  constraints.  In  this 
part,  you  can  introduce  extra  nop's  if  needed,  but  you  must  start  a  new 
iteration  every  two  clock  ticks. 

Exercise  1 0 . 5 . 3:  A  certain  loop  requires 5  loads,  7  stores,  and 8  arithmetic 
operations.  W h at  is  the  minimum  initiation  interval  for  a  software  pipelining 
of  this  loop  on  a  machine  t h at  executes  each  operation  in  one  clock  tick,  and 
has  resources  enough  to  do,  in  one  clock  tick: 

a)  3  loads, 4  stores,  and 5  arithmetic  operations. 

b)  3  loads, 3  stores,  and 3  arithmetic  operations. 

764 

CHAPTER 

10. 

INSTRUCTION-LEVEL 

PARALLELISM 

!  E x e r c i se  10.5.4:  Using  the  machine  model  of  Example  10.12,  Find  the  min 
imum  initiation  interval  and  a  uniform  schedule  for  the  iterations,  for  the  fol 
lowing  loop: 

f or  (i  =  1; 

i  <  n; 

i++)  { 

A [ i]  =  B [ i - 1]  +  1; 
B [ i]  =  A [ i - 1]  +  2; 

} 

Remember  t h at  the  counting  of  iterations  is  handled  by  auto-increment  of  reg 
isters,  and  no  operations  are  needed  solely  for  the  counting  associated  with  the 
for-loop. 

!  E x e r c i se  10.5.5  :  Prove  t h at  Algorithm  10.19,  in  the  special  case  where  every 
operation  requires  only  one  unit  of  one  resource,  can  always  find  a  software-
pipeline  schedule  meeting  the  lower  bound. 

!  E x e r c i se  10.5.6:  Suppose  we  have  a  cyclic  data-dependence  graph  with  nodes 
a,  b,  c,  and  d.  There  are  edges  from  a  to  b  and  from  c  to  d  with  label  (0,1) 
and  there  are  edges  from  b  to  c  and  from  d  to  a  with  label  (1,1).  There  are  no 
other  edges. 

a)  Draw  the  cyclic  dependence  graph. 

b)  Compute  the  table  of  longest  simple  paths  among  the  nodes. 

c)  Show  the  lengths  of  the  longest  simple  paths  if  the  initiation  interval  T  is 

2. 

d)  Repeat  (c)  if  T  =  3. 

e)  For  T  =  3,  what  are  the  constraints  on  the  relative  times  t h at  each  of  the 

instructions  represented  by  a,  b,  c,  and  d  may  be  scheduled? 

!  E x e r c i se  10.5.7:  Give  an  0 ( n3)  algorithm  to  find  the  length  of  the  longest 
simple  p a th  in  an  n-node  graph,  on  the  assumption  t h at  no  cycle  has  a  positive 
length.  Hint:  Adapt  Floyd's  algorithm  for  shortest  p a t hs  (see,  e.g.,  A.  V.  Aho 
and  J.  D.  Ullman,  Foundations  of  Computer  Science,  Computer  Science  Press, 
New  York,  1992). 

!!  E x e r c i se  10.5.8:  Suppose  we  have  a  machine  with  three  instruction  types, 
which  we'll  call  A,  B,  and  C.  All  instructions  require  one  clock  tick,  and  t he 
machine  can  execute  one  instruction  of each  type  at  each  clock.  Suppose  a  loop 
consists  of  six  instructions,  two  of  each  type.  Then  it  is  possible  to  execute 
the  loop  in  a  software  pipeline  with  an  initiation  interval  of  two.  However, 
some  sequences  of  the  six  instructions  require  insertion  of  one  delay,  and  some 
require  insertion  of  two  delays.  Of  the  90  possible  sequences  of  two  A's,  two 
B's  and  two  C's,  how  many  require  no  delay?  How  many  require  one  delay? 

10.6. 

SUMMARY  OF  CHAPTER  10 

765 

Hint:  There  is  symmetry  among  the  three  instruction  types  so  two  sequences 
t h at  can  be  transformed  into  one  another  by  permuting  the  names  A,  B,  and 
C  must  require  t he  same  number  of  delays.  For  example,  ABBCAC  must  be 
t he  same  as  BCCABA. 

10.6  Summary  of  Chapter  10 

4-  Architectural  Issues:  Optimized  code  scheduling  takes  advantage  of  fea 
tures  of  modern  computer  architectures.  Such  machines  often  allow  pipe 
lined  execution,  where  several  instructions  are  in  different  stages  of  exe 
cution  at  t he  same  time.  Some  machines  also  allow  several  instructions 
to  begin  execution  at  the  same  time. 

4-  Data  Dependences:  When  scheduling  instructions,  we  must  be  aware  of 
the  effect  instructions  have  on  each  memory  location  and  register.  True 
d a ta  dependences  occur  when  one  instruction  must  read  a  location  after 
another  has  written  it.  Antidependences  occur  when  there  is  a  write  after 
a  read,  and  output  dependences  occur  when  there  are  two  writes  to  the 
same  location. 

•  Eliminating  Dependences:  By  using  additional  locations  to  store  data, 
antidependences  and  output  dependences  can  be  eliminated.  Only  true 
dependences  cannot  be  eliminated  and  must  surely  be  respected  when  the 
code  is  scheduled. 

•  Data-Dependence  Graphs  for  Basic  Blocks:  These  graphs  represent 

the 

timing  constraints  among  the  statements  of  a  basic  block.  Nodes  corre 
spond  to  the  statements.  An  edge  from  n  to  m  labeled  d  says  t h at  the 
instruction  m  must  start  at  least  d  clock  cycles  after  instruction  n  starts. 

4-  Prioritized  Topological  Orders:  T he  data-dependence  graph  for  a  basic 
block  is  always  acyclic,  and  there  usually  are  many  topological  orders 
consistent  with  the  graph.  One  of  several  heuristics  can  be  used  to  select 
a  preferred  topological  order  for  a  given  graph,  e.g.,  choose  nodes  with 
the  longest  critical  p a th  first. 

•  List  Scheduling:  Given  a  prioritized  topological  order  for  a  data-depend 
ence  graph,  we  may  consider  the  nodes  in  t h at  order.  Schedule  each  node 
at  t he  earliest  clock  cycle  t h at  is  consistent  with  the  timing  constraints  im 
plied  by  t he  graph  edges,  the  schedules  of  all  previously  scheduled  nodes, 
and  the  resource  constraints  of  the  machine. 

• 

Interblock  Code  Motion:  Under  some  circumstances  it  is  possible  to  move 
statements  from  the  block  in  which  they  appear  to  a  predecessor  or  suc 
cessor  block.  The  advantage  is  t h at  there  may  be  opportunities  to  execute 
instructions  in  parallel  at  the  new  location  t h at  do  not  exist  at  the  orig 
If  there  is  not  a  dominance  relation  between  the  old  and 
inal  location. 

766 

CHAPTER 

10. 

INSTRUCTION-LEVEL  PARALLELISM 

new  locations,  it  may  be  necessary  to  insert  compensation  code  along 
certain  paths,  in  order  to  make  sure  t h at  exactly  the  same  sequence  of 
instructions  is  executed,  regardless  of  the  flow  of  control. 

•  Do-All  Loops:  A  do-all  loop  has  no  dependences  across  iterations,  so  any 

iterations  may  be  executed  in  parallel. 

4-  Software  Pipelining  of  Do-All  Loops:  Software  pipelining  is  a  technique 
for  exploiting  the  ability  of  a  machine  to  execute  several  instructions  at 
once.  We  schedule  iterations  of  the  loop  to  begin  at  small  intervals,  per 
haps  placing  no-op  instructions  in  the  iterations  to  avoid  conflicts  between 
iterations  for  the  machine's  resources.  The  result  is  t h at  the  loop  can  be 
executed  quickly,  with  a  preamble,  a  coda,  and  (usually)  a  tiny  inner  loop. 

•  Do-Across  Loops:  Most  loops  have  d a ta  dependences  from  each  iteration 

to  later  iterations.  These  are  called  do-across  loops. 

•  Data-Dependence  Graphs  for  Do-Across  Loops:  To  represent  the  depen 
dences  among  instructions  of  a  do-across  loop  requires  t h at  the  edges  be 
labeled  by  a  pair  of  values:  the  required  delay  (as  for  graphs  representing 
basic  blocks)  and  the  number  of  iterations  t h at  elapse  between  t he  two 
instructions  t h at  have  a  dependence. 

•  List  Scheduling  of  Loops:  To  schedule  a  loop,  we  must  choose  the  one 
schedule  for  all  the  iterations,  and  also  choose  the  initiation  interval  at 
which  successive  iterations  commence.  The  algorithm  involves  deriving 
the  constraints  on  the  relative  schedules  of the  various  instructions  in  the 
loop  by  finding  the  length  of  the  longest  acyclic  paths  between  t he  two 
nodes.  These  lengths  have  the  initiation  interval  as  a  parameter,  and  thus 
put  a  lower  bound  on  t he  initiation  interval. 

10.7  References  for  Chapter  10 

For  a  more  in-depth  discussion  on  processor  architecture  and  design,  we  recom 
mend  Hennessy  and  Patterson  [5]. 

T he  concept  of  d a ta  dependence  was  first  discussed  in  Kuck,  Muraoka,  and 
Chen  [6]  and  Lamport  [8]  in  the  context  of  compiling  code  for  multiprocessors 
and  vector  machines. 

Instruction  scheduling  was  first  used  in  scheduling  horizontal  microcode 

([2,  3,  11,  and  12]).  Fisher's  work  on  microcode  compaction  led  him  to  pro 
pose  the  concept  of  a  VLIW  machine,  where  compilers  directly  can  control  the 
parallel  execution  of  operations  [3].  Gross  and  Hennessy  [4]  used  instruction 
scheduling  to  handle  the  delayed  branches  in  the  first  MIPS  RISC  instruction 
set.  This  chapter's  algorithm  is  based  on  Bernstein  and  Rodeh's  [1]  more  gen 
eral  treatment  of  scheduling  of  operations  for  machines  with  instruction-level 
parallelism. 

10.7. 

REFERENCES  FOR  CHAPTER  10 

767 

T he  basic  idea  behind  software  pipelining  was  first  developed  by  Patel  and 
Davidson  [9]  for  scheduling  hardware  pipelines.  Software  pipelining  was  first 
used  by  R au  and  Glaeser  [10]  to  compile  for  a  machine  with  specialized  hardware 
designed  to  support  software  pipelining.  T he  algorithm  described  here  is  based 
on  Lam  [7],  which  assumes  no  specialized  hardware  support. 

1.  Bernstein,  D.  and  M.  Rodeh,  "Global  instruction  scheduling  for  super 

scalar  machines,"  Proc.  ACM  SIGPLAN  1991  Conference  on  Program 
ming  Language  Design  and  Implementation,  pp.  241-255. 

2.  Dasgupta,  S.,  "The  organization  of  microprogram  stores,"  Computing 

Surveys  11:1  (1979),  pp.  39-65. 

3.  Fisher,  J.  A.,  "Trace  scheduling:  a  technique  for  global  microcode  com 
paction,"  IEEE  Trans,  on  Computers  C-30:7  (1981),  pp.  478-490. 

4.  Gross,  T.  R.  and  Hennessy,  J.  L.,  "Optimizing  delayed  branches,"  Proc. 
15th  Annual  Workshop  on  Microprogramming  (1982),  pp.  114-120. 

5.  Hennessy,  J.  L.  and  D.  A.  Patterson,  Computer  Architecture:  A  Quanti 
tative  Approach,  Third  Edition,  Morgan  Kaufman,  San  Francisco,  2003. 

6.  Kuck,  D.,  Y.  Muraoka,  and  S.  Chen,  "On  the  number  of  operations 
simultaneously  executable  in  Fortran-like  programs  and  their  resulting 
speedup," 
IEEE  Transactions  on  Computers  C-21:12  (1972),  pp.  1293¬ 
1310. 

7.  Lam,  M.  S.,  "Software  pipelining:  an  effective  scheduling  technique  for 
VLIW  machines,"  Proc.  ACM  SIGPLAN  1988  Conference  on  Program 
ming  Language  Design  and  Implementation,  pp.  318-328. 

8.  Lamport,  L.,  "The  parallel  execution  of  DO  loops,"  Comm.  ACM  17:2 

(1974),  pp.  83-93. 

9.  Patel,  J.  H.  and  E.  S.  Davidson,  "Improving  t he  throughput  of  a  pipeline 
by  insertion  of  delays,"  Proc.  Third  Annual  Symposium  on  Computer  Ar 
chitecture  (1976),  pp.  159-164. 

10.  Rau,  B.  R.  and  C.  D.  Glaeser,  "Some  scheduling  techniques  and  an 
easily  schedulable  horizontal  architecture  for  high  performance  scientific 
computing,"  Proc.  14th  Annual  Workshop  on  Microprogramming  (1981), 
pp.  183-198. 

11.  Tokoro,  M.,  E.  Tamura,  and  T.  Takizuka,  "Optimization  of  micropro 

grams,"  IEEE  Trans,  on  Computers  C - 3 0 .7  (1981),  pp.  491-504. 

12.  Wood,  G.,  "Global  optimization  of  microprograms  through  modular  con 

trol  constructs,"  Proc. 
(1979),  pp.  1-6. 

12th  Annual  Workshop 

in  Microprogramming 

Chapter  11 

Optimizing  for  Parallelism 
and  Locality 

This  chapter  shows  how  a  compiler  can  enhance  parallelism  and  locality  in  com 
putationally  intensive  programs  involving  arrays  to  speed  up  target  programs 
running  on  multiprocessor  systems.  Many  scientific,  engineering,  and  commer 
cial  applications  have  an  insatiable  need  for  computational  cycles.  Examples 
include  weather  prediction,  protein-folding  for  designing  drugs,  fluid-dynamics 
for  designing  aeropropulsion  systems,  and  q u a n t um  chromodynamics  for  study 
ing  the  strong  interactions  in  high-energy  physics. 

One  way  to  speed  up  a  computation  is  to  use  parallelism.  Unfortunately,  it 
is  not  easy  to  develop  software  t h at  can  take  advantage  of  parallel  machines. 
Dividing  t he  computation  into  units  t h at  can  execute  on  different  processors  in 
parallel  is  already  hard  enough;  yet  t h at  by  itself  does  not  guarantee  a  speedup. 
We  must  also  minimize  interprocessor  communication,  because  communication 
overhead  can  easily  make  the  parallel  code  run  even  slower  t h an  the  sequential 
execution! 

Minimizing  communication  can  be  thought  of  as  a  special  case  of  improving 
In  general,  we  say  t h at  a  program  has  good  d a ta 
a  program's  data  locality. 
locality  if  a  processor  often  accesses  the  same  d a ta  it  has  used  recently.  Surely 
if  a  processor  on  a  parallel  machine  has  good  locality,  it  does  not  peed  to  com 
municate  with  other  processors  frequently.  Thus,  parallelism  and  d a ta  locality 
need  to  be  considered  hand-in-hand.  D a ta  locality,  by  itself,  is  also  important 
for  the  performance  of  individual  processors.  M o d em  processors  have  one  or 
more  level  of  caches  in  t he  memory  hierarchy;  a  memory  access  can  take  tens  of 
machine  cycles  whereas  a  cache  hit  would  only  take  a  few  cycles.  If  a  program 
does  not  have  good  d a ta  locality  and  misses  in  the  cache  often,  its  performance 
will  suffer. 

Another  reason  why  parallelism  and  locality  are  treated  together  in  this  same 
chapter  is  t h at  they  share  the  same  theory.  If we  know  how  to  optimize  for  d a ta 
locality,  we  know  where  the  parallelism  is.  You  will  see  in  this  chapter  t h at  the 

769 

770 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

program  model  we  used  for  data-flow  analysis  in  Chapter  9  is  inadequate  for 
parallelization  and  locality  optimization.  The  reason  is  t h at  work  on  data-flow 
analysis  assumes  we  don't  distinguish  among  the  ways  a  given  statement  is 
reached,  and  in  fact  these  Chapter  9  techniques  take  advantage  of the  fact  t h at 
we  don't  distinguish  among  different  executions  of  t he  same  statement,  e.g.,  in 
a  loop.  To  parallelize  a  code,  we  need  to  reason  about  the  dependences  among 
different  dynamic  executions  of the  same  statement  to  determine  if they  can  be 
executed  on  different  processors  simultaneously. 

This  chapter  focuses  on  techniques  for  optimizing  the  class  of  numerical 
applications  t h at  use  arrays  as  d a ta  structures  and  access  t h em  with  simple 
regular  patterns.  More  specifically,  we  study  programs  t h at  have  affine  array 
accesses  with  respect  to  surrounding  loop  indexes.  For  example,  if  i  and  j  are 
the  index  variables  of  surrounding  loops,  then  Z[i][j]  and  Z[i][i  +  j]  axe  affine 
accesses.  A  function  of  one  or  more  variables,  ii,i2,... 
,in  is  affine  if  it  can 
be  expressed  as  a  sum  of  a  constant,  plus  constant  multiples  of  t he  variables, 
i.e.,  Co  +  c\X\  +  c2x2  +  •  •  •  +  cnxn,  where  Co,  c i , . ..  ,  cn  are  constants.  Affine 
functions  are  usually  known  as  linear  functions,  although  strictly  speaking, 
linear  functions  do  not  have  the  CQ  term. 

Here  is  a  simple  example  of  a  loop  in  this  domain: 

f or  (i  =  0; 

i  <  10; 

i++)  { 

Z [ i]  =  0; 

} 

Because  iterations  of  the  loop  write  to  different  locations,  different  processors 
can  execute  different  iterations  concurrently.  On  the  other  hand,  if  there  is 
another  statement  Z [ j]  =  1  being  executed,  we  need  to  worry  about  whether 
i  could  ever  be  the  same  as  j,  and  if  so,  in  which  order  do  we  execute  those 
instances  of  the  two  statements  t h at  share  a  common  value  of  the  array  index. 
Knowing  which  iterations  can  refer  to  the  same  memory  location  is  impor 
t a n t.  This  knowledge  lets  us  specify  the  d a ta  dependences  t h at  must  be  honored 
when  scheduling  code  for  both  uniprocessors  and  multiprocessors.  Our  objective 
is  to  find  a  schedule  t h at  honors  all  the  d a ta  dependences  such  t h at  operations 
t h at  access  the  same  location  and  cache  lines  are  performed  close  together  if 
possible,  and  on  the  same  processor  in  the  case  of  multiprocessors. 

The  theory  we  present  in  this  chapter  is  grounded  in  linear  algebra  and 
integer  programming  techniques.  We  model  iterations  in  an  n-deep  loop  nest 
as  an  n-dimensional  polyhedron,  whose  boundaries  are  specified  by  the  bounds 
of  the  loops  in  the  code.  Affine  functions  m ap  each  iteration  to  the  array 
locations  it  accesses.  We  can  use  integer  linear  programming  to  determine  if 
there  exist  two  iterations  t h at  can  refer  to  t he  same  location. 

The  set  of  code  transformations  we  discuss  here  fall  into  two  categories: 
the  polyhedra 
affine  partitioning  and  blocking.  Affine  partitioning  splits  up 
of  iterations  into  components,  to  be  executed  either  on  different  machines  or 
one-by-one  sequentially.  On  the  other  hand,  blocking  creates  a  hierarchy  of 
iterations.  Suppose  we  are  given  a  loop  t h at  sweeps  through  an  array  row-by-

11.1. 

BASIC  CONCEPTS 

771 

row.  We  may  instead  subdivide  the  array  into  blocks  and  visit  all  elements  in  a 
block  before  moving  to  the  next.  The  resulting  code  will  consist  of  outer  loops 
traversing  the  blocks,  and  then  inner  loops  to  sweep  the  elements  within  each 
block.  Linear  algebra  techniques  are  used  to  determine  b o th  the  best  affine 
partitions  and  t he  best  blocking  schemes. 

In  the  following,  we  first  start  with  an  overview  of  the  concepts  in  parallel 
computation  and  locality  optimization  in  Section  11.1.  Then,  Section  11.2  is 
an  extended  concrete  example  —  matrix  multiplication  —  t h at  shows  how  loop 
transformations  t h at  reorder  t he  computation  inside  a  loop  can  improve  b o th 
locality  and  the  effectiveness  of  parallelization. 

Sections  11.3  to  Sections  11.6  present  the  preliminary  information  necessary 
for  loop  transformations.  Section  11.3  shows  how  we  model  the  individual 
iterations  in  a  loop  nest;  Section  11.4  shows  how  we  model  array  index  functions 
t h at  m ap  each  loop  iteration  to  the  array  locations  accessed  by  the  iteration; 
Section  11.5  shows  how  to  determine  which  iterations  in  a  loop  refer  to  the  same 
array  location  or  the  same  cache  line  using  standard  linear  algebra  algorithms; 
and  Section  11.6  shows  how  to  find  all  t he  d a ta  dependences  among  array 
references  in  a  program. 

The  rest  of  the  chapter  applies  these  preliminaries  in  coming  up  with  the 
optimizations.  Section  11.7  first  looks  at  the  simpler  problem  of  finding  par 
allelism  t h at  requires  no  synchronization.  To  find  the  best  affine  partitioning, 
we  simply  find  the  solution  to  the  constraint  t h at  operations  t h at  share  a  d a ta 
dependence  must  be  assigned  to  the  same  processor. 

Well,  not  too  many  programs  can  be  parallelized  without  requiring  any 
synchronization.  Thus,  in  Sections  11.8  through  11.9.9,  we  consider  t he  general 
case  of  finding  parallelism  t h at  requires  synchronization.  We  introduce  the 
concept  of  pipelining,  show  how  to  find  the  affine  partitioning  t h at  maximizes 
t he  degree  of  pipelining  allowed  by  a  program.  We  show  how  to  optimize  for 
locality  in  Section  11.10.  Finally,  we  discuss  how  affine  transforms  are  useful 
for  optimizing  for  other  forms  of  parallelism. 

11.1  Basic  Concepts 

This  section  introduces  the  basic  concepts  related  to  parallelization  and  local 
ity  optimization. 
If  operations  can  be  executed  in  parallel,  they  also  can  be 
reordered  for  other  goals  such  as  locality.  Conversely,  if  d a ta  dependences  in 
a  program  dictate  t h at  instructions  in  a  program  must  execute  serially,  there 
is  obviously  no  parallelism,  nor  is  there  any  opportunity  to  reorder  instruc 
tions  to  improve  locality.  Thus  parallelization  analysis  also  finds  the  available 
opportunities  for  code  motion  to  improve  d a ta  locality. 

To  minimize  communication  in  parallel  code,  we  group  together  all  related 
operations  and  assign  them  to  the  same  processor.  The  resulting  code  must 
therefore  have  d a ta  locality.  One  crude  approach  to  getting  good  d a ta  locality 
on  a  uniprocessor  is  to  have  the  processor  execute  the  code  assigned  to  each 

772 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

processor  in  succession. 

In  this  introduction,  we  start  by  presenting  an  overview  of parallel  computer 
architectures.  We  then  show  the  basic  concepts  in  parallelization,  the  kind  of 
transformations  t h at  can  make  a  big  difference,  as  well  as  t he  concepts  useful 
for  parallelization.  We  then  discuss  how  similar  considerations  can  be  used  to 
optimize  locality.  Finally,  we  introduce  informally  the  mathematical  concepts 
used  in  this  chapter. 

11.1.1  Multiprocessors 

The  most  popular  parallel  machine  architecture  is  t he  symmetric  multiproces 
sor  (SMP).  High-performance  personal  computers  often  have  two  processors, 
and  many  server  machines  have  four,  eight,  and  some  even  tens  of  processors. 
Moreover,  as  it  has  become  feasible  for  several  high-performance  processors  to 
fit  on  a  single  chip,  multiprocessors  have  become  even  more  widely  used. 

Processors  on  a  symmetric  multiprocessor  share  the  same  address  space.  To 
communicate,  a  processor  can  simply  write  to  a  memory  location,  which  is  then 
read  by  any  other  processor.  Symmetric  multiprocessors  are  so  named  because 
all  processors  can  access  all  of the  memory  in  the  system  with  a  uniform  access 
time.  Fig.  11.1  shows  the  high-level  architecture  of  a  multiprocessor.  T he 
processors  may  have  their  own  first-level,  second-level,  and  in  some  cases,  even 
a  third-level  cache.  T he  highest-level  caches  are  connected  to  physical  memory 
through  typically  a  shared  bus. 

Processor 

Processor 

Processor 

Processor 

First-level 
Cache 

First-level 
Cache 

First-level 
Cache 

First-level 
Cache 

Second-level 
Cache 

Second-level 
Cache 

Second-level 
Cache 

Second-level 
Cache 

Bus 

Memory 

Figure  11.1:  The  symmetric  multi-processor  architecture 

Symmetric  multiprocessors  use  a  coherent  cache  protocol to  hide  t he  presence 
of  caches  from  t he  programmer.  Under  such  a  protocol,  several  processors  are 

11.1. 

BASIC  CONCEPTS 

773 

allowed  to  keep  copies  of  t he  same  cache  line1  at  the  same  time,  provided  t h at 
they  are  only  reading  the  data.  When  a  processor  wishes  to  write  to  a  cache 
line,  copies  from  all  other  caches  are  removed.  W h en  a  processor  requests  d a ta 
not  found  in  its  cache,  the  request  goes  out  on  the  shared  bus,  and  the  d a ta 
will  be  fetched  either  from  memory  or  from  the  cache  of  another  processor. 

The  time  taken  for  one  processor  to  communicate  with  another  is  about 
twice  the  cost  of  a  memory  access.  The  data,  in  units  of  cache  lines,  must 
first  be  written  from  t he  first  processor's  cache  to  memory,  and  then  fetched 
from  t he  memory  to  t he  cache  of  t he  second  processor.  You  may  think  t h at 
interprocessor  communication  is  relatively  cheap,  since  it  is  only  about  twice  as 
slow  as  a  memory  access.  However,  you  must  remember  t h at  memory  accesses 
are  very  expensive  when  compared  to  cache  hits—they  can  be  a  hundred  times 
slower.  This  analysis  brings  home  the  similarity  between  efficient  parallelization 
and  locality  analysis.  For  a  processor  to  perform  well,  either  on  its  own  or  in 
t he  context  of  a  multiprocessor,  it  must  find  most  of  the  d a ta  it  operates  on  in 
its  cache. 

In  the  early  2000's,  the  design  of symmetric  multiprocessors  no  longer  scaled 
beyond  tens  of  processors,  because  the  shared  bus,  or  any  other  kind  of  inter 
connect  for  t h at  matter,  could  not  operate  at  speed  with  the  increasing  number 
of processors.  To  make  processor  designs  scalable,  architects  introduced  yet  an 
other  level  in  the  memory  hierarchy.  Instead  of  having  memory  t h at  is  equally 
far  away  for  each  processor,  they  distributed  the  memories  so  t h at  each  pro 
cessor  could  access  its  local  memory  quickly  as  shown  in  Fig.  11.2.  Remote 
memories  thus  constituted  the  next  level  of  the  memory  hierarchy;  they  are 
collectively  bigger  but  also  take  longer  to  access.  Analogous  to  the  principle  in 
memory-hierarchy  design  t h at  fast  stores  are  necessarily  small,  machines  t h at 
support  fast  interprocessor  communication  necessarily  have  a  small  number  of 
processors. 

There  are  two  variants  of  a  parallel  machine  with  distributed  memories: 
NUM  A  (nonuniform  memory  access)  machines  and  message-passing  machines. 
NUM  A  architectures  provide  a  shared  address  space  to  t he  software,  allowing 
processors  to  communicate  by  reading  and  writing  shared  memory.  On  message-
passing  machines,  however,  processors  have  disjoint  address  spaces,  and  proces 
sors  communicate  by  sending  messages  to  each  other.  Note  t h at  even  though  it 
is  simpler  to  write  code  for  shared  memory  machines,  the  software  must  have 
good  locality  for  either  type  of  machine  to  perform  well. 

11.1.2  Parallelism  in  Applications 

We  use  two  high-level  metrics  to  estimate  how  well  a  parallel  application  will 
perform:  parallelism  coverage  which  is  the  percentage  of  the  computation  t h at 
runs  in  parallel,  granularity  of  parallelism,  which  is  t he  amount  of  computation 
t h at  each  processor  can  execute  without  synchronizing  or  communicating  with 
others.  One  particularly  attractive  target  of parallelization  is  loops:  a  loop  may 

1You  may  wish  to  review  the  discussion  of  caches  and  cache  lines  in  Section  7.4. 

774 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

Processor 

Processor 

Processor 

Processor 

First-level 
Cache 

First-level 
Cache 

First-level 
Cache 

First-level 
Cache 

Second-level 
Cache 

Second-level 
Cache 

Second-level 
Cache 

Second-level 
Cache 

Memory 

Memory 

Memory 

Memory 

Bus  or  other  Interconnect 

Figure  11.2:  Distributed  memory  machines 

have  many  iterations,  and  if they  are  independent  of each  other,  we  have  found 
a  great  source  of  parallelism. 

A m d a h l 's  L aw 

The  significance  of parallelism  coverage is  succinctly  captured  by  Amdahl's  Law. 
Amdahl's  Law  states  t h a t,  if  /  is  the  fraction  of  the  code  parallelized,  and  if 
the  parallelized  version  runs  on  a  p-processor  machine  with  no  communication 
or  parallelization  overhead,  the  speedup  is 

1 

( 1 - /)  +  ( / / * )' 

For  example,  if half of t he  computation  remains  sequential,  t he  computation  can 
only  double  in  speed,  regardless  of  how  many  processors  we  use.  The  speedup 
achievable  is  a  factor  of  1.6  if  we  have  4  processors.  Even  if  t he  parallelism 
coverage  is  90%,  we  get  at  most  a  factor  of  3  speed  up  on  4  processors,  and  a 
factor  of  10  on  an  unlimited  number  of  processors. 

G r a n u l a r i ty  of  P a r a l l e l i sm 

It  is  ideal  if  the  entire  computation  of  an  application  can  be  partitioned  into 
many  independent  coarse-grain  tasks  because  we  can  simply  assign  the  differ 
ent  tasks  to  different  processors.  One  such  example  is  the  S E TI  (Search  for 
Extra-Terrestrial  Intelligence)  project,  which  is  an  experiment  t h at  uses  home 
computers  connected  over  t he  Internet  to  analyze  different  portions  of  radio 
telescope  d a ta  in  parallel.  Each  unit  of  work,  requiring  only  a  small  amount 

11.1. 

BASIC  CONCEPTS 

775 

of  input  and  generating  a  small  amount  of  output,  can  be  performed  indepen 
dently  of all  others.  As  a  result,  such  a  computation  runs  well  on  machines  over 
t he  Internet,  which  has  relatively  high  communication  latency  (delay)  and  low 
bandwidth. 

Most  applications  require  more  communication  and  interaction  between  pro 
cessors,  yet  still  allow  coarse-grained  parallelism.  Consider,  for  example,  the 
web  server  responsible  for  serving  a  large  number  of  mostly  independent  re 
quests  out  of  a  common  database.  We  can  run  the  application  on  a  multi 
processor,  with  a  thread  implementing  t he  database  and  a  number  of  other 
threads  servicing  user  requests.  Other  examples  include  drug  design  or  airfoil 
simulation,  where  t he  results  of  many  different  parameters  can  be  evaluated 
independently.  Sometimes  the  evaluation  of  even  just  one  set  of  parameters  in 
a  simulation  takes  so  long  t h at  it  is  desirable  to  speed  it  up  with  paralleliza 
tion.  As  the  granularity  of  available  parallelism  in  an  application  decreases, 
better  interprocessor  communication  support  and  more  programming  effort  are 
needed. 

Many  long-running  scientific  and  engineering  applications,  with  their  simple 
control  structures  and  large  d a ta  sets,  can  be  more  readily  parallelized  at  a  finer 
grain  t h an  t he  applications  mentioned  above.  Thus,  this  chapter  is  devoted  pri 
marily  to  techniques  t h at  apply  to  numerical  applications,  and  in  particular,  to 
programs  t h at  spend  most  of  their  time  manipulating  d a ta  in  multidimensional 
arrays.  We  shall  examine  this  class  of  programs  next. 

11.1.3  Loop-Level  Parallelism 

Loops  are  the  main  target  for  parallelization,  especially  in  applications  using 
arrays.  Long  running  applications  tend  to  have  large  arrays,  which  lead  to 
loops  t h at  have  many  iterations,  One  for  each  element  in  the  array. 
It  is  not 
uncommon  to  find  loops  whose  iterations  are  independent  of  one  another.  We 
can  divide  the  large  number  of  iterations  of  such  loops  among  the  processors. 
If  the  amount  of  work  performed  in  each  iteration  is  roughly  the  same,  simply 
dividing  the  iterations  evenly  across  processors  will  achieve  maximum  paral 
lelism.  Example  11.1  is  an  extremely  simple  example  showing  how  we  can  take 
advantage  of  loop-level  parallelism. 

E x a m p le  1 1 . 1:  The  loop 

f or  (i  =  0; 

i  <  n; 
Z[i]  = X[i]  - Y [ i ]; 

i++)  { 

Z[i]  = Z[i]  * Z[i] ; 

} 

computes  the  square  of  diferences  between  elements  in  vectors  X  and  Y  and 
stores  it  into  Z.  T he  loop  is  parallelizable  because  each  iteration  accesses  a 
different  set  of  data.  We  can  execute  the  loop  on  a  computer  with  M  processors 
by  giving  each  processor  an  unique  ID  p  =  0 , 1 , . ..  ,  M  -  1  and  having  each 
processor  execute  the  same  code: 

776 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

Task-Level  Parallelism 

It  is  possible to  find  parallelism  outside  of iterations  in  a loop.  For  example, 
we  can  assign  two  different  function  invocations,  or  two  independent  loops, 
to  two  processors.  This  form  of  parallelism  is  known  as  task  parallelism. 
The  task  level  is  not  as  attractive  a  source  of  parallelism  as  is  the  loop 
level.  T he  reason  is  t h at  t he  number  of  independent  tasks  is  a  constant 
for  each  program  and  does  not  scale  with  the  size  of  t he  data,  as  does  the 
number  of  iterations  of  a  typical  loop.  Moreover,  the  tasks  generally  are 
not  of equal  size,  so  it  is  hard  to  keep  all  the  processors  busy  all  t he  time. 

b  =  c e i l ( n / M ); 
f or  (i  =  b * p; 

i  <  m i n ( n , b * ( p + 1 ) ); 

i++)  { 

-  Y [ i ]; 
Z [ i]  =  X [ i] 
Z [ i]  =  Z [ i]  *  Z [ i ]; 

} 

We  divide  t he  iterations  in  the  loop  evenly  among  the  processors;  the  p th 
processor  is  given  the  p th  swath  of iterations  to  execute.  Note  t h at  the  number 
of  iterations  may  not  be  divisible  by  M,  so  we  assure  t h at  the  last  processor 
does  not  execute  past  the  bound  of the  original  loop  by  introducing  a  minimum 
operation. 

• 

The  parallel  code  shown  in  Example  11.1  is  an  S P MD  (Single  P r o g r am 
Multiple  Data)  program.  T he  same  code  is  executed  by  all  processors,  but  it 
is  parameterized  by  an  identifier  unique  to  each  processor,  so  different  proces 
sors  can  take  different  actions.  Typically  one  processor,  known  as  the  master, 
executes  all  the  serial  part  of  the  computation.  The  master  processor,  upon 
reaching  a  parallelized  section  of  the  code,  wakes  up  all  the  slave  processors. 
All  the  processors  execute  the  parallelized  regions  of  t he  code.  At  t he  end 
of  each  parallelized  region  of  code,  all  the  processors  participate  in  a  barrier 
synchronization.  Any  operation  executed  before  a  processor  enters  a  synchro 
nization  barrier  is  guaranteed  to  be  completed  before  any  other  processors  are 
allowed  to  leave  t he  barrier  and  execute  operations  t h at  come  after  the  barrier. 
If  we  parallelize  only  little  loops  like  those  in  Example  11.1,  then  the  re 

sulting  code  is  likely  to  have  low  parallelism  coverage  and  relatively  fine-grain 
parallelism.  We  prefer  to  parallelize  the  outermost  loops  in  a  program,  as  t h at 
yields  the  coarsest  granularity  of  parallelism.  Consider,  for  example,  the  appli 
cation  of  a  two-dimensional  F FT  transformation  t h at  operates  on  an  n  x  n  d a ta 
set.  Such  a  program  performs  n  F F T 's  on  the  rows  of  t he  data,  then  another 
n  F F T 's  on  the  columns.  It  is  preferable  to  assign  each  of  t he  n  independent 
F F T 's  to  one  processor  each,  rather  t h an  trying  to  use  several  processors  to 
collaborate  on  one  F F T.  The  code  is  easier  to  write,  the  parallelism  coverage 

11.1. 

BASIC  CONCEPTS 

777 

for  t he  algorithm  is  100%,  and  the  code  has  good  d a ta  locality  as  it  requires  no 
communication  at  all  while  computing  an  F F T. 

Many  applications  do  not  have  large  outermost  loops  t h at  are  parallelizable. 
T he  execution  time  of these  applications,  however,  is  often  dominated  by  time-
consuming  kernels,  which  may  have  hundreds  of  lines  of  code  consisting  of 
loops  with  different  nesting  levels.  It  is  sometimes  possible  to  take  the  kernel, 
reorganize  its  computation  and  partition  it  into  mostly  independent  units  by 
focusing  on  its  locality. 

11.1.4  Data  Locality 

There  are  two  somewhat  different  notions  of  d a ta  locality  t h at  need  to  be  con 
sidered  when  parallelizing  programs.  Temporal  locality  occurs  when  the  same 
d a ta  is  used  several  times  within  a  short  time  period.  Spatial  locality  occurs 
when  different  d a ta  elements  t h at  are  located  near  to  each  other  are  used  within 
a  short  period  of  time.  An  important  form  of  spatial  locality  occurs  when  all 
the  elements  t h at  appear  on  one  cache  line  are  used  together.  The  reason  is 
t h at  as  soon  as  one  element  from  a  cache  line  is  needed,  all  the  elements  in  t he 
same  line  are  brought  to  the  cache  and  will  probably  still  be  there  if  they  are 
used  soon.  T he  effect  of this  spatial  locality  is  t h at  cache  misses  are  minimized, 
with  a  resulting  important  speedup  of  the  program. 

Kernels  can  often  be  written  in  many  semantically  equivalent  ways  but  with 
widely  varying  d a ta  localities  and  performances.  Example  11.2  shows  an  alter 
native  way  of  expressing  the  computation  in  Example  11.1. 

E x a m p le  1 1 . 2:  Like  Example  11.1  the  following  also  finds  the  squares  of 
differences  between  elements  in  vectors  X  and  Y. 

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

Z[i]  = X[i]  - Y [ i ]; 

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

Z[i]  = Z[i]  * Z[i]; 

The  first  loop  finds  the  differences,  the  second  finds  the  squares.  Code  like  this 
appears  often  in  real  programs,  because  t h at  is  how  we  can  optimize  a  program 
for  vector  machines,  which  are  supercomputers  which  have  instructions  t h at 
perform  simple  arithmetic  operations  on  vectors  at  a  time.  We  see  t h at  the 
bodies  of  the  two  loops  here  are  fused  as  one  in  Example  11.1. 

Given  t h at  t he  two programs perform  t he  same  computation,  which  performs 
better?  The  fused  loop  in  Example  11.1  has  better  performance  because  it  has 
better  d a ta  locality.  Each  difference  is  squared  immediately,  as  soon  as  it  is 
produced;  in  fact,  we  can  hold  the  difference  in  a  register,  square  it,  and  write 
t he  result  just  once  into  the  memory  location  Z[i]. 
In  contrast,  the  code  in 
Example  11.1  fetches  Z[i]  once,  and  writes  it  twice.  Moreover,  if  the  size  of 
t he  array  is  larger  t h an  t he  cache,  Z\i\  needs  to  be  refetched  from  memory  the 
second  time  it  is  used  in  this  example.  Thus,  this  code  can  run  significantly 
slower. 

• 

778 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

f or  (j  =  0; 

j  <  n; 

j++) 

f or  (i  =  0; 

i  <  n; 

i++) 

Z [ i , j]  =  0; 

(a)  Zeroing  an  array  column-by-column. 

f or  (i  =  0; 

i  <  n; 

f or  (j  =  0; 

i++) 
j  <  n; 

j + +) 

Z [ i , j]  =  0; 

(b)  Zeroing  an  array  row-by-row. 

b  =  c e i l ( n/ M ); 
f or  (i  =  b * p; 

i  <  m i n ( n , b * ( p + l ) ); 

i++) 

f or  (j  =  0; 

j  <  n; 

j++) 

Z [ i , j]  =  0; 

(c)  Zeroing  an  array  row-by-row  in  parallel. 

Figure  11.3:  Sequential  and  parallel  code  for  zeroing  an  array 

E x a m p le  1 1 . 3:  Suppose  we  want  to  set  array  Z,  stored  in  row-major  order 
(recall  Section  6.4.3),  to  all  zeros.  Fig.  11.3(a)  and  (b)  sweeps  through  t he 
array  column-by-column  and  row-by-row,  respectively.  We  can  transpose  t he 
loops  in  Fig.  11.3(a)  to  arrive  at  Fig.  11.3(b).  In  terms  of spatial  locality,  it  is 
preferable  to  zero  out  the  array  row-by-row  since  all  t he  words  in  a  cache  line 
are  zeroed  consecutively.  In  t he  column-by-column  approach,  even  though  each 
cache  line  is  reused  by  consecutive  iterations  of  the  outer  loop,  cache  lines  will 
be  thrown  out  before  reuse  if  t he  size  of  a  colum  is  greater  t h an  t he  size  of  t he 
cache.  For  best  performance,  we  parallelize  the  outer  loop  of  Fig.  11.3(b)  in  a 
manner  similar  to  t h at  used  in  Example  11.1. 

• 

T he  two  examples  above  illustrate  several  i m p o r t a nt  characteristics  associ 

ated  with  numeric  applications  operating  on  arrays: 

•  Array  code  often  has  many  parallelizable  loops. 

•  W h en  loops  have  parallelism,  their  iterations  can  be  executed  in  arbitrary 

order;  they  can  be  reordered  to  improve  d a ta  locality  drastically. 

•  As  we  create  large  units  of  parallel  computation  t h at  are  independent  of 
each  other,  executing  these  serially  tends  to  produce  good  d a ta  locality. 

11.1.5 

Introduction  to  Affine  Transform  Theory 

Writing  correct  and  efficient  sequential  programs  is  difficult;  writing  parallel 
programs  t h at  are  correct  and  efficient  is  even  harder.  T he  level  of  difficulty 

11.1. 

BASIC  CONCEPTS 

779 

increases  as  t he  granularity  of parallelism  exploited  decreases.  As  we  see  above, 
programmers  must  pay  attention  to  d a ta  locality  to  get  high  performance.  Fur 
thermore,  the  task  of taking  an  existing  sequential  program  and  parallelizing  it 
is  extremely  hard.  It  is  hard  to  catch  all  the  dependences  in  the  program,  es 
pecially  if  it  is  not  a  program  with  which  we  are  familiar.  Debugging  a  parallel 
program  is  harder  yet,  because  errors  can  be  nondeterministic. 

Ideally,  a  parallelizing  compiler  automatically  translates  ordinary  sequential 
programs  into  efficient  parallel  programs  and  optimizes  the  locality  of  these 
programs.  Unfortunately,  compilers  without  high-level  knowledge  about  t he 
application,  can  only  preserve  the  semantics  of  the  original  algorithm,  which 
may  not  be  amenable  to  parallelization.  Furthermore,  programmers  may  have 
made  arbitrary  choices  t h at  limit  the  program's  parallelism. 

Successes  in  parallelization  and  locality  optimizations  have  been  demon 
strated  for  Fortran  numeric  applications  t h at  operate  on  arrays  with  affine 
accesses.  Without  pointers  and  pointer  arithmetic,  Fortran  is  easier  to  ana 
lyze.  Note  t h at  not  all  applications  have  affine  accesses;  most  notably,  many 
numeric  applications  operate  on  sparse  matrices  whose  elements  are  accessed 
indirectly  through  another  array.  This  chapter  focuses  on  the  parallelization 
and  optimizations  of  kernels,  consisting  of  mostly  tens  of  lines. 

As  illustrated  by  Examples  11.2  and  11.3,  parallelization  and  locality  op 
timization  require  t h at  we  reason  about  the  different  instances  of  a  loop  and 
their  relations  with  each  other.  This  situation  is  very  different  from  data-flow 
analysis,  where  we  combine  information  associated  with  all  instances  together. 
For  the  problem  of  optimizing  loops  with  array  accesses,  we  use  three  kinds 
of  spaces.  Each  space  can  be  thought  of  as  points  on  a  grid  of  one  or  more 
dimensions. 

1.  T he  iteration  space  is  the  set  of  t he  dynamic  execution  instances  in  a 
computation,  t h at  is,  the  set  of  combinations  of  values  taken  on  by  the 
loop  indexes. 

2.  T he  data  space  is  t he  set  of  array  elements  accessed. 

3.  The  processor  space  is  the  set  of  processors  in  the  system.  Normally, 
these  processors  are  assigned  integer  numbers  or  vectors  of  integers  to 
distinguish  among  them. 

Given  as  input  are  a  sequential  order  in  which  the  iterations  are  executed  and 
affine  array-access  functions  (e.g.,  X[iJ  +  1])  t h at  specify  which  instances  in 
the  iteration  space  access  which  elements  in  the  d a ta  space. 

T he  output  of the  optimization,  again  represented  as  affine  functions,  defines 
what  each  processor  does  and  when.  To  specify  what  each  processor  does, 
we  use  an  affine  function  to  assign  instances  in  the  original  iteration  space  to 
processors.  To  specify  when,  we  use  an  affine  function  to  m ap  instances  in  the 
iteration  space  to  a  new  ordering.  The  schedule  is  derived  by  analyzing  the 
array-access  functions  for  d a ta  dependences  and  reuse  patterns. 

780 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

The  following  example  will  illustrate  the  three  spaces  —  iteration,  d a t a, 
and  processor. 
It  will  also  introduce  informally  the  important  concepts  and 
issues  t h at  need  to  be  addressed  in  using  these  spaces  to  parallelize  code.  The 
concepts  each  will  be  covered  in  detail  in  later  sections. 

E x a m p le  1 1 . 4:  Figure  11.4  illustrates  the  different  spaces  and  their  relations 
used  in  the  following  program: 

f l o at  Z[100]  ; 
f or  (i  =  0; 

i  <  10; 
Z [ i + 1 0]  =  Z [ i]  ; 

i++) 

The  three  spaces  and  the  mappings  among  them  are  as  follows: 

Region  of data  accessed 

Data  space 

Iteration  space 

Affine  array 
index  functions 

Affine  partitioning 

Processor  space 

• 

0 

• 

1 

rj 

Figure  11.4:  Iteration,  data,  and  processor  space  for  Example  11.4 

1.  Iteration  Space:  T he  iteration  space  is  the  set  of  iterations,  whose  ID's 
are  given  by  the  values  held  by  the  loop  index  variables.  A  d-deep  loop 
nest  (i.e.,  d  nested  loops)  has  d  index  variables,  and  is  thus  modeled  by 
a  G?-dimensional  space.  The  space  of  iterations  is  bounded  by  the  lower 
and  upper  bounds  of the  loop  indexes.  The  loop  of this  example  defines  a 
one-dimensional  space  of  10  iterations,  labeled  by  the  loop  index  values: 
i  =  0 , 1 , . .. 

, 9. 

2.  Data  Space:  The  d a ta  space  is  given  directly  by  t he  array  declarations. 
In  this  example,  elements  in  the  array  are  indexed  by  a  —  0 , 1 , . ..  ,99. 
Even  though  all  arrays  are  linearized  in  a  program's  address  space,  we 
treat  n-dimensional  arrays  as  n-dimensional  spaces,  and  assume  t h at  the 
individual  indexes  stay  within  their  bounds.  In  this  example,  t he  array  is 
one-dimensional  anyway. 

11.1.  BASIC  CONCEPTS 

781 

3.  Processor  Space:  We  pretend  t h at  there  are  an  unbounded  number  of 
virtual  processors  in  the  system  as  our  initial  parallelization  target.  The 
processors  are  organized  in  a  multidimensional  space,  one  dimension  for 
each  loop  in  t he  nest  we  wish  to  parallelize.  After  parallelization,  if  we 
have  fewer  physical  processors  t h an  virtual  processors,  we  divide  the  vir 
tual  processors  into  even  blocks,  and  assign  a  block  each  to  a  processor. 
In  this  example,  we  need  only  ten  processors,  one  for  each  iteration  of 
t he  loop.  We  assume  in  Fig.  11.4  t h at  processors  are  organized  in  a  one-
dimensional  space  and  numbered  0 , 1 , . ..  , 9,  with  loop  iteration  i  assigned 
to  processor  i.  If there  were,  say,  only  five  processors,  we  could  assign  it 
erations  0  and  1  to  processor  0,  iterations  2  and  3  to  processor  1,  and 
so  on.  Since  iterations  are  independent,  it  doesn't  m a t t er  how  we  do  t he 
assignment,  as  long  as  each  of the  five  processors  gets  two  iterations. 

4.  Affine  Array-Index  Function:  Each  array  access  in  the  code  specifies  a 
mapping  from  an  iteration  in  the  iteration  space  to  an  array  element  in 
the  d a ta  space.  T he  access  function  is  affine  if  it  involves  multiplying  the 
loop  index  variables  by  constants  and  adding  constants.  Both  the  array 
index  functions  i  +  10,  and  i  are  affine.  From  the  access  function,  we  can 
tell  t he  dimension  of  the  d a ta  accessed. 
In  this  case,  since  each  index 
function  has  one  loop  variable,  t he  space  of  accessed  array  elements  is  one 
dimensional. 

5.  Affine  Partitioning:  We  parallelize  a  loop  by  using  an  affine  function  to 
assign  iterations  in  an  iteration  space  to  processors  in  the  processor  space. 
In  our  example,  we  simply  assign  iteration  i  to  processor  i.  We  can  also 
specify  a  new  execution  order  with  affine  functions.  If  we  wish  to  execute 
the  loop  above  sequentially,  but  in  reverse,  we  can  specify  the  ordering 
function  succinctly  with  an  affine  expression  10  —  i.  Thus,  iteration  9  is 
the  1st  iteration  to  execute  and  so  on. 

6.  Region  of  Data  Accessed:  To  find  the  best  affine  partitioning,  it  useful  to 
know  the  region  of d a ta  accessed  by  an  iteration.  We  can  get  the  region  of 
d a ta  accessed  by  combining  the  iteration  space  information  with  the  array 
index  function.  In  this  case,  the  array  access  Z[i  +  10]  touches  the  region 
{a  |  10  <  a  <  20}  and  the  access  Z[i]  touches  the  region  {a\0  <  a  <  10}. 

7.  Data  Dependence:  To  determine  if the  loop  is  parallelizable,  we  ask  if there 
is  a  d a ta  dependence  t h at  crosses  t he  boundary  of each  iteration.  For  this 
example,  we  first  consider  the  dependences  of  the  write  accesses  in  the 
loop.  Since  the  access  function  Z[z + 10]  maps  different  iterations  to  differ 
ent  array  locations,  there  are  no  dependences  regarding the  order  in  which 
the  various  iterations  write  values  to  the  array.  Is  there  a  dependence  be 
tween  the  read  and  write  accesses?  Since  only  Z[10],  Z[ll],...  ,  Z[19]  are 
written  (by  the  access  Z[i  +  10]),  and  only  Z[0],  Z[l],...  ,  Z[9]  are  read 
(by  the  access  Z[i]),  there  can  be  no  dependencies  regarding  the  relative 
order  of  a  read  and  a  write.  Therefore,  this  loop  is  parallelizable.  T h at 

782  CHAPTER 

11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

is,  each  iteration  of the  loop  is  independent  of all  other  iterations,  and  we 
can  execute  the  iterations  in  parallel,  or  in  any  order  we  choose.  Notice, 
however,  t h at  if  we  made  a  small  change,  say  by  increasing  the  upper 
limit  on  loop  index  i  to  10  or  more,  then  there  would  be  dependencies, 
as  some  elements  of  array  Z  would  be  written  on  one  iteration  and  then 
read  10  iterations  later.  In  t h at  case,  the  loop  could  not  be  parallelized 
completely,  and  we  would  have  to  think  carefully  about  how  iterations 
were  partitioned  among  processors  and  how  we  ordered  iterations. 

• 

Formulating  the  problem  in  terms  of  multidimensional  spaces  and  affine 
mappings  between  these  spaces  lets  us  use  standard  mathematical  techniques 
to  solve  the  parallelization  and  locality  optimization  problem  generally.  For 
example,  the  region  of d a ta  accessed  can  be  found  by  the  elimination  of variables 
using  the  Fourier-Motzkin  elimination  algorithm.  D a ta  dependence  is  shown  to 
be  equivalent  to  the  problem  of  integer  linear  programming.  Finally,  finding 
the  affine  partitioning  corresponds  to  solving  a  set  of  linear  constraints.  Don't 
worry  if  you  are  not  familiar  with  these  concepts,  as  they  will  be  explained 
starting  in  Section  11.3. 

11.2  Matrix  Multiply:  An  In-Depth  Example 

We  shall  introduce  many  of  the  techniques  used  by  parallel  compilers  in  an  ex 
tended  example.  In  this  section,  we  explore  the  familiar  matrix-multiplication 
algorithm  to  show  t h at  it  is  nontrivial  to  optimize  even  a  simple  and  easily 
parallelizable  program.  We  shall  see  how  rewriting  the  code  can  improve  d a ta 
locality;  t h at  is,  processors  are  able  to  do  their  work  with  far  less  communica 
tion  (with  global  memory  or  with  other  processors,  depending  on  the  architec 
ture)  t h an  if  the  straightforward  program  is  chosen.  We  shall  also  discuss  how 
cognizance  of the  existence  of cache  lines  t h at  hold  several  consecutive  d a ta  ele 
ments  can  improve  the  running  time  of programs  such  as  matrix  multiplication. 

11.2.1  The  Matrix-Multiplication  Algorithm 

In  Fig.  11.5  we  see  a  typical  matrix-multiplication  p r o g r a m .2  It  takes  two  nxn 
matrices,  X  and  F,  and  produces  their  product  in  a  third  n xn  matrix  Z. 
Recall  t h at  %  —  the  element  of  matrix  Z  in  row  i  and  column  j  —  must 

become  YJl=i  ^-ihXkj-

The  code  of Fig.  11.5  generates  n2  results,  each  of which  is  an  inner  product 
between  one  row  and  one  column  of  the  two  matrix  operands.  Clearly,  the 

2In  pseudocode  programs  in  this  chapter,  we  shall  generally  use  C  syntax,  but  to  make 
multidimensional array accesses — the  central  issue for most  of the  chapter — easier to  read, 
we shall use Fortran-style array references, that is, Z[i,j] instead of 

11.2. 

MATRIX  MULTIPLY:  AN 

IN-DEPTH  EXAMPLE 

783 

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

for  (j  = 0;  j  < n;  j++)  { 

Z[i,j]  = 0.0; 
for  (k =  0;  k  < n;  k++) 

Z[i,j]  = Z[i,j]  + X[i,k]*Y[k,j]; 

} 

Figure  11.5:  The  basic  matrix-multiplication  algorithm 

calculations  of  each  of  the  elements  of  Z  are  independent  and  can  be  executed 
in  parallel. 

T he  larger  n  is,  the  more  times  the  algorithm  touches  each  element.  T h at  is, 
there  are  3 n2  locations  among  the  three  matrices,  but  t he  algorithm  performs 
n3  operations,  each  of  which  multiplies  an  element  of  X  by  an  element  of  Y 
and  adds  the  product  to  an  element  of  Z.  Thus,  the  algorithm  is  computation-
intensive  and  memory  accesses  should  not,  in  principle,  constitute  a  bottleneck. 

Serial  E x e c u t i on  of  t he  M a t r ix  M u l t i p l i c a t i on 

Let  us  first  consider  how  this  program  behaves  when  run  sequentially  on  a 
uniprocessor.  The  innermost  loop  reads  and  writes  the  same  element  of  Z,  and 
uses  a  row  of  X  and  a  column  of  Y.  Z[i,j]  can  easily  be  stored  in  a  register 
and  requires  no  memory  accesses.  Assume,  without  loss  of  generality,  t h at  t he 
matrix  is  laid  out  in  row-major  order,  and  t h at  c  is  the  number  of array  elements 
in  a  cache  line. 

0  1 

n  - 1 

i  =0 

Figure  11.6:  The  d a ta  access  p a t t e rn  in  matrix  multiply 

Figure  11.6  suggests  the  access  p a t t e rn  as  we  execute  one  iteration  of  the 
outer  loop  of Fig.  11.5.  In  particular,  the  picture  shows  the  first  iteration,  with 
i  =  0.  Each  time  we  move  from  one  element  of  t he  first  row  of  X  to  the  next, 

784 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

we  visit  each  element  in  a  single  column  of  Y.  We  see  in  Fig.  11.6  the  assumed 
organization  of  the  matrices  into  cache  lines.  T h at  is,  each  small  rectangle 
represents  a  cache  line  holding  four  array  elements  (i.e.,  c  =  4  and  n  =  12  in 
the  picture). 

Accessing  X  puts  little  burden  on  the  cache.  One  row  of  X  is  spread  among 
only  n/c  cache  lines.  Assuming  these  all  fit  in  the  cache,  only  n/c  cache  misses 
occur  for  a  fixed  value  of  index  i,  and  the  total  number  of  misses  for  all  of  X  is 
n2/c,  the  minimum  possible  (we  assume  n  is  divisible  by  c,  for  convenience). 

However,  while  using  one  row  of  X,  the  matrix-multiplication  algorithm 
accesses  all  the  elements  of  Y,  column  by  column.  T h at  is,  when  j  =  0,  the 
inner  loop  brings  to  the  cache  the  entire  first  column  of  Y.  Notice  t h at  t he 
elements  of  t h at  column  are  stored  among  n  different  cache  lines.  If  the  cache 
is  big  enough  (or  n  small  enough)  to  hold  n  cache  lines,  and  no  other  uses  of 
the  cache  force  some  of  these  cache  lines  to  be  expelled,  then  the  column  for 
j  =  0  will  still  be  in  the  cache  when  we  need  the  second  column  of  Y.  In  t h at 
case,  there  will  not  be  another  n  cache  misses  reading  Y,  until  j  =  c,  at  which 
time  we  need  to  bring  into  the  cache  an  entirely  different  set  of  cache  lines  for 
Y.  Thus,  to  complete  t he  first  iteration  of  t he  outer  loop  (with  i  =  0)  requires 
between  n2/c  and  n2  cache  misses,  depending  on  whether  columns  of cache  lines 
can  survive  from  one  iteration  of  the  second  loop  to  the  next. 

Moreover,  as  we  complete  t he  outer  loop,  for  i  =  1,2,  and  so  on,  we  may 
have  many  additional  cache  misses  as  we  read  Y,  or  none  at  all.  If the  cache  is 
big  enough  t h at  all  n2/c  cache  lines  holding  Y  can  reside  together  in  t he  cache, 
then  we  need  no  more  cache  misses.  The  total  number  of  cache  misses  is  thus 
2 n2/ c,  half  for  X  and  half  for  Y.  However,  if  the  cache  can  hold  one  column  of 
Y  but  not  all  of  Y,  then  we  need  to  bring  all  of  Y  into  cache  again,  each  time 
we  perform  an  iteration  of  the  outer  loop.  T h at  is,  t he  number  of  cache  misses 
is  n2/c  +  n3/ c;  the  first  t e rm  is  for  X  and  the  second  is  for  Y.  Worst,  if  we 
cannot  even  hold  one  column  of  Y  in  the  cache,  then  we  have  n2  cache  misses 
per  iteration  of  t he  outer  loop  and  a  total  of  n2/c  +  n3  cache  misses. 

R o w - b y - R ow  P a r a l l e l i z a t i on 

Now,  let  us  consider  how  we  could  use  some  number  of processors,  say p  proces 
sors,  to  speed  up  the  execution of Fig.  11.5.  An  obvious  approach to  parallelizing 
matrix  multiplication  is  to  assign  different  rows  of  Z  to  different  processors.  A 
processor  is  responsible  for  n/p  consecutive  rows  (we  assume  n  is  divisible  by 
p,  for  convenience).  W i th  this  division  of  labor,  each  processor  needs  to  access 
n/p  rows  of  matrices  X  and  Z,  but  the  entire  Y  matrix.  One  processor  will 
compute  n2 jp  elements  of  Z,  performing  n3/p  multiply-and-add  operations  to 
do  so. 

While  the  computation  time  thus  decreases  in  proportion  to  p,  the  commu 
nication  cost  actually  rises  in  proportion  to  p.  T h at  is,  each  of  p  processors 
has  to  read  n2/p  elements  of  X,  but  all  n2  elements  of  Y.  T he  total  number 
of  cache  lines  t h at  must  be  delivered  to  the  caches  of the  p  processors  is  at  last 

11.2. 

MATRIX  MULTIPLY:  AN 

IN-DEPTH  EXAMPLE 

785 

n2/c  + p n2/ c;  t he  two  terms  are  for  delivering  X  and  copies  of  Y,  respectively. 
As  p  approaches  n,  t he  computation  time  becomes  0 ( n2)  while  the  communi 
cation  cost  is  0 ( n3).  T h at  is,  the  bus  on  which  d a ta  is  moved  between  memory 
and  t he  processors'  caches  becomes  the  bottleneck.  Thus,  with  the  proposed 
d a ta  layout,  using  a  large  number  of  processors  to  share  the  computation  can 
actually  slow  down  t he  computation,  rather  t h an  speed  it  up. 

11.2.2  Optimizations 

T he  matrix-multiplication  algorithm  of  Fig.  11.5  shows  t h at  even  though  an 
algorithm  may  reuse  the  same  data,  it  may  have  poor  d a ta  locality.  A  reuse 
of  d a ta  results  in  a  cache  hit  only  if  the  reuse  happens  soon  enough,  before 
t he  d a ta  is  displaced  from  the  cache.  In  this  case,  n2  multiply-add  operations 
separate  the  reuse  of  the  same  d a ta  element  in  matrix  Y,  so  locality  is  poor. 
In  fact,  n  operations  separate  the  reuse  of  the  same  cache  line  in  Y.  In  addi 
tion,  on  a  multiprocessor,  reuse  may  result  in  a  cache  hit  only  if  t he  d a ta  is 
reused  by  the  same  processor.  When  we  considered  a  parallel  implementation 
in  Section  11.2.1,  we  saw  t h at  elements  of  Y  had  to  be  used  by  every  processor. 
Thus,  t he  reuse  of  Y  is  not  turned  into  locality. 

C h a n g i ng  D a ta  L a y o ut 

One  way  to  improve  the  locality  of  a  program  is  to  change  the  layout  of its  d a ta 
structures.  For  example,  storing  Y  in  column-major  order  would  have  improved 
the  reuse  of  cache  lines  for  matrix  Y.  T he  applicability  of  this  approach  is 
limited,  because  the  same  matrix  normally  is  used  in  different  operations.  If  Y 
played  the  role  of  X  in  another  matrix  multiplication,  then  it  would  suffer  from 
being  stored  in  column-major  order,  since  the  first  matrix  in  a  multiplication 
is  better  stored  in  row-major  order. 

B l o c k i ng 

It  is  sometimes  possible  to  change  the  execution  order  of  the  instructions  to 
improve  d a ta  locality.  The  technique  of  interchanging  loops,  however,  does  not 
improve  the  matrix-multiplication  routine.  Suppose  the  routine  were  written 
to  generate  a  column  of  matrix  Z  at  a  time,  instead  of  a  row  at  a  time.  T h at 
is,  make  the  j - l o op  the  outer  loop  and  the  z-loop  the  second  loop.  Assuming 
matrices  are  still  stored  in  row-major  order,  matrix  Y  enjoys  better  spatial  and 
temporal  locality,  but  only  at  the  expense  of  matrix  X. 

Blocking  is  another  way  of  reordering  iterations  in  a  loop  t h at  can  greatly 
improve  the  locality  of  a  program. 
Instead  of  computing  the  result  a  row  or 
a  column  at  a  time,  we  divide  the  matrix  up  into  submatrices,  or  blocks,  as 
suggested  by  Fig.  11.7,  and  we  order  operations  so  an  entire  block  is  used  over 
a  short  period  of  time.  Typically,  the  blocks  are  squares  with  a  side  of  length 
B.  If  B  evenly  divides  n,  then  all  the  blocks  are  square.  If  B  does  not  evenly 

786 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

divide  n,  then  t he  blocks  on  the  lower  and  right  edges  will  have  one  or  b o th 
sides  of  length  less  t h an  B. 

~* 

n 

• 

Figure  11.7:  A  matrix  divided  into  blocks  of  side  B 

Figure  11.8  shows  a  version  of  the  basic  matrix-multiplication  algorithm 
where  all  three  matrices  have  been  blocked  into  squares  of  side  B.  As  in 
Fig.  11.5,  Z  is  assumed  to  have  been  initialized  to  all  O's.  We  assume  t h at 
B  divides  n; 
if  not,  then  we  need  to  modify  line  (4)  so  the  upper  limit  is 
m i n (u  +  B,n),  and  similarly  for  lines  (5)  and  (6). 

for  (jj  =  0;  jj  <  n;  jj  =  jj+B) 

1)  for  (ii  =  0;  ii  <  n;  ii  =  ii+B) 
2) 
3) 
4) 
5) 
6) 
7) 

for  (kk  =  0;  kk  <  n;  kk  =  kk+B) 
for  (i =  ii;  i  <  ii+B;  i++) 

for  (j  = jj;  j  < jj+B;  j++) 

for  (k = kk;  k  < kk+B;  k++) 

Z[i,j]  = Z[i,j]  + X[i,k]*Y[k,j]; 

Figure  11.8:  Matrix  multiplication  with  blocking 

The  outer  three  loops,  lines  (1)  through  (3),  use  indexes  ii,  jj,  and  kk,  which 
are  always  incremented  by  B,  and  therefore  always  mark  the  left  or  upper  edge 
of  some  blocks.  W i th  fixed  values  of  ii,  jj,  and  kk,  lines  (4)  through  (7)  enable 
the  blocks  with  upper-left  corners  X[ii,kk]  and  Y[kk,jj] 
to  make  all  possible 
contributions  to  the  block  with  upper-left  corner  Z[ii,jj). 

If  we  pick  B  properly,  we  can  significantly  decrease  the  number  of  cache 
misses,  compared  with  the  basic  algorithm,  when  all  of  X,  Y,  or  Z  cannot  fit 
in  t he  cache.  Choose  B  such  t h at  it  is  possible  to  fit  one  block  from  each  of t he 
matrices  in  the  cache.  Because  of  the  order  of t he  loops,  we  actually  need  each 

11.2. 

MATRIX  MULTIPLY:  AN 

IN-DEPTH  EXAMPLE 

787 

Another  View  of  Block-Based  Matrix  Multiplication 

We  can  imagine  t h at  the  matrices  X,Y,  and  Z  of  Fig.  11.8  are  not  n xn 
floating-point  numbers,  but  rather  (n/B)  x  (n/B)  matrices 
matrices  of 
whose  elements  are  themselves  B  x  B  matrices  of  floating-point  numbers. 
Lines  (1)  through  (3)  of  Fig.  11.8  are  then  like  the  three  loops  of  t he 
basic  algorithm  in  Fig.  11.5,  but  with  n/B  as  t he  size  of  the  matrices, 
rather  t h an  n.  We  can  then  think  of  lines  (4)  through  (7)  of  Fig.  11.8 
as  implementing  a  single  multiply-and-add  operation  of  Fig.  11.5.  Notice 
t h at  in  this  operation,  t he  single  multiply  step  is  a  matrix-multiply  step, 
and  it  uses  the  basic  algorithm  of  Fig.  11.5  on  the  floating-point  numbers 
t h at  are  elements  of  the  two  matrices  involved.  The  matrix  addition  is 
element-wise  addition  of  floating-point  numbers. 

block  of  Z  in  cache  only  once,  so  (as  in  the  analysis  of  the  basic  algorithm  in 
Section  11.2.1)  we  shall  not  count  the  cache  misses  due  to  Z. 

To  bring  a  block  of  X  or  Y  to  the  cache  takes  B2/c  cache  misses;  recall  c 
is  the  number  of  elements  in  a  cache  line.  However,  with  fixed  blocks  from  X 
and  Y,  we  perform  B3  multiply-and-add  operations  in  lines  (4)  through  (7)  of 
Fig.  11.8.  Since  the  entire  matrix-multiplication  requires  n3  multiply-and-add 
operations,  the  number  of  times  we  need  to  bring  a  pair  of  blocks  to  t he  cache 
is  n3/ B3.  As  we  require  2B2/c  cache  misses  each  time  we  do,  the  total  number 
of  cache  misses  is  2n3/Bc. 

It  is  interesting  to  compare  this  figure  2n3/Be  with  the  estimates  given  in 
Section  11.2.1.  There,  we  said  t h at  if  entire  matrices  can  fit  in  the  cache,  then 
0 ( n2/ c)  cache  misses  suffice.  However,  in  t h at  case,  we  can  pick  B  =  n,  i.e., 
make  each  matrix  be  a  single  block.  We  again  get  0 ( n2/ c)  as  our  estimate  of 
cache  misses.  On  the  other  hand,  we  observed  t h at  if  entire  matrices  will  not 
fit  in  cache,  we  require  0 ( n3/ c)  cache  misses,  or  even  0 ( n3)  cache  misses.  In 
t h at  case,  assuming  t h at  we  can  still  pick  a  significantly  large  B  (e.g.,  B  could 
be  200,  and  we  could  still  fit  three  blocks  of  8-byte  numbers  in  a  one-megabyte 
cache),  there  is  a  great  advantage  to  using  blocking  in  matrix  multiplication. 

T he  blocking  technique  can  be  reapplied  for  each  level  of  the  memory  hi 
erarchy.  For  example,  we  may  wish  to  optimize  register  usage  by  holding  the 
operands  of  a  2  x  2  matrix  multiplication  in  registers.  We  choose  successively 
bigger  block  sizes  for  the  different  levels  of  caches  and  physical  memory. 

Similarly,  we  can  distribute  blocks  between  processors  to  minimize  d a ta  traf 
fic.  Experiments  showed  t h at  such  optimizations  can  improve  the  performance 
of  a  uniprocessor  by  a  factor  of  3,  and  the  speed  up  on  a  multiprocessor  is  close 
to  linear  with  respect  to  the  number  of  processors  used. 

788 

CHAPTER  11.  OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

11.2.3  Cache  Interference 

Unfortunately,  there  is  somewhat  more  to  the  story  of  cache  utilization.  Most 
caches  are  not  fully  associative  (see  Section  7.4.2).  In  a  direct-mapped  cache, 
if  n  is  a  multiple  of  the  cache  size,  then  all  the  elements  in  the  same  row  of 
an  n  x  n  array  will  be  competing  for  the  same  cache  location. 
In  t h at  case, 
bringing  in  the  second  element  of  a  column  will  throw  away  the  cache  line  of 
the  first,  even  though  the  cache  has  the  capacity  to  keep  both  of  these  lines  at 
the  same  time.  This  situation  is  referred  to  as  cache  interference. 

There  are  various  solutions  to  this  problem.  The  first  is  to  rearrange  the 
d a ta  once  and  for  all  so  t h at  the  d a ta  accessed  is  laid  out  in  consecutive  d a ta 
locations.  The  second  is  to  embed  the  n  x  n  array  in  a  larger  mxn  array  where 
m  is  chosen  to  minimize  the  interference  problem.  Third,  in  some  cases  we  can 
choose  a  block  size  t h at  is  guaranteed  to  avoid  interference. 

11.2.4  Exercises  for  Section  11.2 

E x e r c i se  1 1 . 2 . 1:  The  block-based  matrix-multiplication  algorithm  of  Fig. 
11.8  does  not  have  the  initialization  of  the  matrix  Z  to  zero,  as  t he  code  of 
Fig.  11.5  does.  Add  the  steps  t h at  initialize  Z  to  all  zeros  in  Fig.  11.8. 

11.3 

Iteration  Spaces 

The  motivation  for  this  study  is  to  exploit  the  techniques  t h a t,  in  simple  settings 
like  matrix  multiplication  as  in  Section  11.2,  were  quite  straightforward.  In  the 
more  general  setting,  the  same  techniques  apply,  but  they  are  far  less  intuitive. 
But  by  applying  some  linear  algebra,  we  can  make  everything  work  in  t he 
general  setting. 

As  discussed  in  Section  11.1.5,  there  are  three  kinds  of  spaces  in  our  trans 
formation  model: 
iteration  space,  d a ta  space,  and  processor  space.  Here  we 
start  with  the  iteration  space.  The  iteration  space  of  a  loop  nest  is  defined  to 
be  all  the  combinations  of  loop-index  values  in  the  nest. 

Often,  the  iteration  space  is  rectangular,  as  in  t he  matrix-multiplication 
example  of  Fig.  11.5.  There,  each  of  the  nested  loops  had  a  lower  bound  of  0 
and  an  upper  bound  of  n  —  1.  However,  in  more  complicated,  but  still  quite 
realistic,  loop  nests,  the  upper  a n d / or  lower  bounds  on  one  loop  index  can 
depend  on  the  values  of the  indexes  of t he  outer  loops.  We  shall  see  an  example 
shortly. 

11.3.1  Constructing  Iteration  Spaces  from  Loop  Nests 

To  begin,  let  us  describe  the  sort  of  loop  nests  t h at  can  be  handled  by  the 
techniques  to  be  developed.  Each  loop  has  a  single  loop  index,  which  we  assume 
is  incremented  by  1  at  each  iteration.  T h at  assumption  is  without  loss  of 
generality,  since  if t he  incrementation  is  by  integer  c  >  1,  we  can  always  replace 

11.3. 

ITERATION  SPACES 

789 

uses  of t he  index  i  by  uses  of ci + a  for  some  positive  or  negative  constant  a,  and 
then  increment  i  by  1  in  t he  loop.  The  bounds  of the  loop  should  be  written  as 
affine  expressions  of  outer  loop  indices. 

E x a m p le  11.5  :  Consider  the  loop 

f or  (i  =  2; 

i  <=  100; 

i  =  i + 3) 

Z [ i]  =  0; 

which  increments  i  by  3  each  time  around  the  loop.  T he  effect  is  to  set  to  0  each 
of  t he  elements  Z[2],  Z[5],  Z [ 8 ] , . ..  ,  Z[98].  We  can  get  the  same  effect  with: 

f or  (j  =  0; 

j  <=  3 2; 

j++) 

Z [ 3 * j + 2]  =  0; 

T h at  is,  we  substitute  3j  +  2  for  i.  The  lower  limit  i  =  2  becomes  j  =  0  (just 
solve  3j  +  2  =  2  for  j ),  and  the  upper  limit  i  <  100  becomes  j  <  32  (simplify 
3j  +  2  <  100  to  get  j  <  32.67  and  round  down  because  j  has  to  be  an  integer). 
• 

Typically,  we  shall  use  for-loops  in  loop  nests.  A  while-loop  or  repeat-loop 
can  be  replaced  by  a  for-loop  if  there  is  an  index  and  upper  and  lower  bounds 
for  the  index,  as  would  be  the  case  in  something  like  the  loop  of  Fig.  11.9(a). 
A  for-loop  like  f or 

i++)  serves  exactly  the  same  purpose. 

i < 1 0 0; 

( i = 0; 

However,  some  while-  or  repeat-loops  have  no  obvious  limit.  For  example, 

Fig.  11.9(b)  may  or may not  terminate,  but  there  is  no  way to tell  what  condition 
on  i  in  the  unseen  body  of  the  loop  causes  the  loop  to  break.  Figure  11.9(c) 
is  another  problem  case.  Variable  n  might  be  a  parameter  of  a  function,  for 
example.  We  know  the  loop  iterates  n  times,  but  we  don't  know  what  n  is  at 
compile  time,  and  in  fact  we  may  expect  t h at  different  executions  of  the  loop 
will  execute  different  numbers  of times.  In  cases  like  (b)  and  (c),  we  must  treat 
the  upper  limit  on  i  as  infinity. 

A  <i-deep  loop  nest  can  be  modeled  by  a  dl-dimensional  space.  The  dimen 
sions  are  ordered,  with  the  kth.  dimension  representing  the  kth  nested  loop, 
in  this 
counting  from  t he  outermost  loop, 
space  represents  values  for  all  the  loop  indexes;  the  outermost  loop  index  has 
value  xi,  the  second  loop  index  has  value  x2,  and  so  on.  The  innermost  loop 
index  has  value  x&. 

inward.  A  point 

(xi,x2,...  ,Xd) 

But  not  all  points  in  this  space  represent  combinations  of  indexes  t h at  ac 
tually  occur  during  execution  of  the  loop  nest.  As  an  affine  function  of  outer 
loop  indices,  each  lower  and  upper  loop  bound  defines  an  inequality  dividing 
the  iteration  space  into  two  half  spaces: 
those  t h at  are  iterations  in  the  loop 
(the  positive  half  space),  and  those  t h at  are  not  (the  negative  half  space).  T he 
conjunction  (logical  AND)  of all  the  linear  equalities  represents  the  intersection 
of the  positive  half spaces,  which  defines  a  convex  polyhedron,  which  we  call  the 
iteration  space  for  the  loop  nest.  A  convex  polyhedron  has  the  property  t h at  if 

790 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

i  =  0; 
w h i le 

( i < 1 0 0)  { 

<some  s t a t e m e n ts  n ot 
i  =  i + 1; 

i n v o l v i ng  i> 

} 

(a)  A  while-loop  with  obvious  limits. 

i  =  0; 
w h i le  (1)  { 

<some  s t a t e m e n t s> 
i  =  i + 1; 

} 

(b)  It  is  unclear  when  or  if  this  loop  terminates. 

i  =  0; 
w h i le  ( i < n)  { 

<some  s t a t e m e n ts  n ot 
i  =  i + 1; 

i n v o l v i ng  i  or  n> 

} 

(c)  We  don't  know  the  value  of  n,  so  we  don't 
know  when  this  loop  terminates. 

Figure  11.9:  Some  while-loops 

two  points  are  in  the  polyhedron,  all  points  on  the  line  between  t h em  are  also  in 
the  polyhedron.  All  the  iterations  in  the  loop  are  represented  by  the  points  with 
integer  coordinates  found  within  the  polyhedron  described  by  the  loop-bound 
inequalities.  And  conversely,  all  integer  points  within  t he  polyhedron  represent 
iterations  of  t he  loop  nest  at  some  time. 

f or  (i  =  0; 

i  <=  5; 

i++) 

f or  (j  =  i; 

j  <=  7; 

j++) 

Z [ j , i]  =  0; 

Figure  11.10:  A  2-dimensional  loop  nest 

E x a m p le  1 1 . 6:  Consider  the  2-dimensional  loop  nest  in  Fig.  11.10.  We  can 
model  this  two-deep  loop  nest  by  t he  2-dimensional  polyhedron  shown  in  Fig. 
11.11.  T he  two  axes  represent  the  values  of  the  loop  indexes  i  and  j.  Index  i 
can  take  on  any  integral  value  between  0  and  5;  index  j  can  take  on  any  integral 
value  such  t h at  i  <  j  <  7. 

• 

11.3. 

ITERATION  SPACES 

791 

i < 5 

0<  i 

J 

Figure  11.11:  T he  iteration  space  of  Example  11.6 

Iteration  Spaces  and  Array-Accesses 

In  t he  code  of Fig.  11.10,  the  iteration  space  is  also  the  portion  of the  array 
A  t h at  t he  code  accesses.  T h at  sort  of  access,  where  the  array  indexes  are 
also  loop  indexes  in  some  order,  is  very  common.  However,  we  should  not 
confuse  the  space  of  iterations,  whose  dimensions  are  loop  indexes,  with 
the  d a ta  space.  If we  had  used  in  Fig.  11.10  an  array  access  like  A[2*i,  i+j] 
instead  of  A[i, j],  the  difference  would  have  been  apparent. 

11.3.2  Execution  Order  for  Loop  Nests 

A  sequential  execution  of  a  loop  nest  sweeps  through  iterations  in  its  iteration 
space  in  an  ascending  lexicographic  order.  A  vector  i  =  [io, i\,...  , in]  is  lexi 
cographically  less  than  another  vector  i'  =  [ i0, « i,  •  •  •  ,i'n>],  written  i  -<  i',  if  and 
only  if  there  exists  an  m  <  min(n, n')  such  t h at  [io, i\,...  , im]  =  [i'o, i[,  •  •  •  , i'm] 
and  im+i  <  i'm+i-  Note  t h at  m  —  0  is  possible,  and  in  fact  common. 

E x a m p le  1 1 . 7:  W i th  i  as  the  outer  loop,  the  iterations  in  the  loop  nest  in 
Example  11.6  are  executed  in  the  order  shown  in  Fig.  11.12. 

• 

11.3.3  Matrix  Formulation  of Inequalities 

T he  iterations  in  a  d-deep  loop  can  be  represented  mathematically  as 

{i in  Zd  |  Bi + b  >  0} 

(11.1) 

792 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

[0,1], 
[1,1], 

[0,2], 
[1,2], 
[2,2], 

[0,3], 
[1,3], 
[2,3], 
[3,3], 

[0,4], 
[1,4], 
[2,4], 
[3,4], 
[4,4], 

[0,5], 
[1,5], 
[2,5], 
[3,5], 
[4,5], 
[5,5], 

[0,6], 
[1,6], 
[2,6], 
[3,6], 
[4,6], 
[5,6], 

[0,7] 
[1,7] 
[2,7] 
[3,7] 
[4,7] 
[5,7] 

Figure  11.12:  Iteration  order  for  loop  nest  of  Fig.  11.10 

Here, 

1.  Z,  as  is  conventional  in  mathematics,  represents  t he  set  of  integers  — 

positive,  negative,  and  zero, 

2.  B  is  a  d  x  d  integer  matrix, 

3.  b  is  an  integer  vector  of  length  d,  and 

4.  0  is  a  vector  of  d  0's. 

E x a m p le .11.8  :  We  can  write  the  inequalities  of Example  11.6  as  in  Fig.  11.13. 
T h at  is,  the  range  of  i  is  described  by  i  >  0  and  i  <  5;  the  range  of  j  is 
described  by  j  >  i  and  j  <  7.  We  need  to  put  each  of  these  inequalities  in 
the  form  ui  +  vj  +  w  >  0.  Then,  [w, v]  becomes  a  row  of  the  matrix  B  in  the 
inequality  (11.1),  and  w  becomes  t he  corresponding  component  of  t he  vector 
b.  For  instance,  i  >  0  is  of  this  form,  with  u  =  1,  v  =  0,  and  w  =  0.  This 
inequality  is  represented  by  t he  first  row  of B  and  top  element  of b  in  Fig.  11.13. 

1 

-1 
-1 
-1 
0 

0  " 
0 
0 
1 

-1 

i 

j 

+ 
+ 

'  0  " 
5 
0 
0 
7 

> 
> 

"  0  " 
0 
0 
0 
0 

Figure  11.13:  Matrix-vector  multiplication  and  a  vector  inequality  represents 
the  inequalities  defining  an  iteration  space 

As  another  example,  the  inequality  i  <  5  is  equivalent  to  (—l)i + ( 0 ) j +5  >  0, 
and  is  represented  by  the  second  row  of  B  and  b  in  Fig.  11.13.  Also,  j  >  i 
+ 0  >  0  and  is  represented  by  the  third  row.  Finally,  j  <  7 
becomes  ( —+ 
• 
+  7  >  0  and  is  the  last  row  of  the  matrix  and  vector. 
becomes  (0)i  + 

11.3. 

ITERATION  SPACES 

793 

Manipulating  Inequalities 

To  convert  inequalities,  as  in  Example  11.8,  we  can  perform  transforma 
tions  much  as  we  do  for  equalities,  e.g.,  adding  or  subtracting  from  b o th 
sides,  or  multiplying  b o th  sides  by  a  constant.  T he  only  special  rule  we 
must  remember  is  t h at  when  we  multiply  b o th  sides  by  a  negative  number, 
we  have  to  reverse  t he  direction  of  the  inequality.  Thus,  i  <  5,  multiplied 
by  — 1,  becomes  —i  >  —5.  Adding  5  to  both  sides,  gives  —  i  +  5  >  0,  which 
is  essentially  t he  second  row  of  Fig.  11.13. 

11.3.4 

Incorporating  Symbolic  Constants 

Sometimes,  we  need  to  optimize  a  loop  nest  t h at  involves  certain  variables  t h at 
are  loop-invariant  for  all  the  loops  in  the  nest.  We  call  such  variables  symbolic 
constants,  but  to  describe  the  boundaries  of  an  iteration  space  we  need  to  treat 
them  as  variables  and  create  an  entry  for  t h em  in  the  vector  of  loop  indexes, 
i.e.,  the  vector  i  in  t he  general  formulation  of  inequalities  (11.1). 

E x a m p le  1 1 .9  :  Consider  the  simple  loop: 

f or  (i  =  0; 

i  <=  n; 

i++)  { 

} 

This  loop  defines  a  one-dimensional  iteration  space,  with  index  i,  bounded  by 
i  >  0  and  i  <  n.  Since  n  is  a  symbolic  constant,  we  need  to  include  it  as  a 
variable,  giving  us  a  vector  of  loop  indexes  [i,n]. 
In  matrix-vector  form,  this 
iteration  space  is  defined  by 

"  -1 

1  " 

1  0 

i  > '  0  " 
> '  0  " 
> 
n 
0 

Notice  t h a t,  although  the  vector  of  array  indexes  has  two  dimensions,  only  the 
first  of these,  representing  i,  is  part  of the  output  —  the  set  of points  lying  with 
the  iteration  space. 

• 

11.3.5  Controlling  the  Order  of  Execution 

The  linear  inequalities  extracted  from  the  lower  and  upper  bounds  of  a  loop 
body  define  a  set  of iterations  over  a  convex  polyhedron.  As  such,  t he  represen 
tation  assumes  no  execution  ordering  between  iterations  within  the  iteration 
space.  The  original  program  imposes  one  sequential  order  on  the  iterations, 
which  is  the  lexicographic  order  with  respect  to  the  loop  index  variables  ordered 
from  the  outermost  to  the  innermost.  However,  the  iterations  in  the  space  can 
be  executed  in  any  order  as  long  as  their  d a ta  dependences  are  honored  (i.e., 

794 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

the  order  in  which  writes  and  reads  of  any  array  element  are  performed  by  the 
various  assignment  statements  inside  the  loop  nest  do  not  change). 

The  problem  of how  we  choose  an  ordering  t h at  honors  the  d a ta  dependences 
and  optimizes  for  d a ta  locality  and  parallelism  is  hard  and  is  dealt  with  later 
starting  from  Section  11.7.  Here  we  assume  t h at  a  legal  and  desirable  ordering 
is  given,  and  show  how  to  generate  code  t h at  enforce  the  ordering.  Let  us  start 
by  showing  an  alternative  ordering  for  Example  11.6. 

E x a m p le  1 1 . 1 0:  There  are  no  dependences  between  iterations  in  t he  program 
in  Example  11.6.  We  can  therefore  execute  the  iterations  in  arbitrary  order, 
sequentially  or  concurrently.  Since  iteration 
accesses  element  Z[j, i]  in 
the  code,  the  original  program  visits  the  array  in  t he  order  of  Fig.  11.14(a). 
To  improve  spatial  locality,  we  prefer  to  visit  contiguous  words  in  the  array 
consecutively,  as  in  Fig.  11.14(b). 

This  access  p a t t e rn  is  obtained  if  we  execute  t he  iterations  in  t he  order 
shown  in  Fig.  11.14(c).  T h at  is,  instead  of  sweeping  the  iteration  space  in 
Fig.  11.11  horizontally,  we  sweep  the  iteration  space  vertically,  so  j  becomes 
the  index  of t he  outer  loop.  T he  code  t h at  executes  t he  iterations  in  the  above 
order  is 

f or  (j  =  0; 
f or 

j  <=  7; 

(i  -  0; 
Z [ j , i]  =  0; 

i  <=  m i n ( 5 , j ); 

i++) 

• 

Given  a  convex  polyhedron  and  an  ordering  of  the  index  variables,  how  do 
we  generate  the  loop  bounds  t h at  sweep  through  the  space  in  lexicographic 
order  of  the  variables?  In  t he  example  above,  the  constraint  i  <  j  shows  up  as 
a  lower  bound  for  index  j  in  t he  inner  loop  in  the  original  program,  but  as  an 
upper  bound  for  index  «,  again  in  the  inner  loop,  in  t he  transformed  program. 
T he  bounds  of t he  outermost  loop,  expressed  as  linear  combinations  of sym 
bolic  constants  and  constants,  define  the  range  of  all  t he  possible  values  it  can 
take  on.  The  bounds  for  inner  loop  variables  are  expressed  as  linear  combi 
nations  of  outer  loop  index  variables,  symbolic  constants  and  constants.  They 
define  the  range  the  variable  can  take  on  for  each  combination  of values  in  outer 
loop  variables. 

P r o j e c t i on 

Geometrically  speaking,  we  can  find  the  loop  bounds  of  the  outer  loop  index 
in  a  two-deep  loop  nest  by  projecting  t he  convex  polyhedron  representing  the 
iteration  space  onto  t he  outer  dimension  of  t he  space.  T he  projection  of  a 
polyhedron  on  a  lower-dimensional  space  is  intuitively  the  shadow  cast  by  t he 
object  onto  t h at  space.  The  projection  of t he  two-dimensional  iteration  space  in 
Fig.  11.11  opto  the  i  axis  is  t he  vertical  line  from  0  to  5;  and  the  projection  onto 

11.3. 

ITERATION  SPACES 

795 

Z[0,0],  Z[1,0],  Z[2,0],  Z[3,0],  Z[4,0],  Z[5,0],  Z[6,0], 
Z [ 6 , l ], 
Z [ l , l ],  Z [ 2 , l ],  Z [ 3 , l ],  Z [ 4 , l ],  Z [ 5 , l ], 
Z[2,2],  Z[3,2],  Z[4,2],  Z[5,2],  Z[6,2], 
Z[3,3],  Z[4,3],  Z[5,3],  Z[6,3], 
Z[4,4],  Z[5,4],  Z[6,4], 
Z[5,5],  Z[6,5], 

Z[7,0] 
Z [ l , 7] 
Z[7,2] 
Z[7,3] 
Z[7,4] 
Z[7,5] 

(a)  Original  access  order. 

Z[0,0] 
Z [ l , l] 
Z[1,0], 
Z[2,0],  Z [ 2 , l ], 
Z[2,2] 
Z[3,0],  Z [ 3 , l ],  Z[3,2], 
Z[3,3] 
Z[4,0],  Z [ 4 , l ],  Z[4,2],  Z[4,3], 
Z[4,4] 
Z[5,0],  Z [ 5 , l ],  Z[5,2],  Z[5,3],  Z[5,4], 
Z[6,0],  Z [ 6 , l ],  Z[6,2],  Z[6,3],  Z[6,4], 
Z[7,0],  Z [ 7 , l ],  Z[7,2],  Z[7,3],  Z[7,4], 

Z[5,5] 
Z[6,5] 
Z[7,5] 

(b)  Preferred  order  of  access. 

[0,0] 

[0,1], 
[0,2], 
[0,3], 
[0,4], 
[0,5], 
[0,6], 
[0,7], 

[1,1] 
[1,2], 
[1,3], 
[1,4], 
[1,5], 
[1,6], 
[1,7], 

[2,2] 
[2,3], 
[2,4], 
[2,5], 
[2,6], 
[2,7], 

[3,3] 
[3,4], 
[3,5], 
[3,6], 
[3,7], 

[4,4] 
[4,5], 
[4,6], 
[4,7], 

[5,5] 
[5,6] 
[5,7] 

(c)  Preferred  order  of  iterations. 

Figure  11.14:  Reordering  the  accesses  and  iterations  for  a  loop  nest 

796 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

the  j  axis  is  the  horizontal  line  from  0  to  7.  When  we  project  a  3-dimensional 
object  along  the  z  axis  onto  a  2-dimensional  x  and  y  plane,  we  eliminate  variable 
z,  losing  t he  height  of t he  individual  points  and  simply  record  t he  2-dimensional 
footprint  of  the  object  in  the  x-y  plane. 

Loop  bound  generation  is  only  one  of the  many  uses  of projection.  Projection 
can  be  defined  formally  as  follows.  Let  S  be  an  n-dimensional  polyhedron. 
T he  projection  of  S  onto  t he  first  m  of  its  dimensions  is  t he  set  of  points 
(xi,x2,... 
is 
follows: 

in  S.  We  can  compute  projection  using  Fourier-Motzkin  elimination,  as 

for  some  xm + 1, xm + 2,  ••• 

,xn,  vector  [xi,x2,... 

such 

t h at 

,xm) 

,xn] 

A l g o r i t hm  1 1 . 1 1:  Fourier-Motzkin  elimination. 

T h at  is,  5  is  a  set  of 
I N P U T:  A  polyhedron  S  with  variables 
linear  constraints  involving  the  variables  X{.  One  given  variable  xm  is  specified 
to  be  t he  variable  to  be  eliminated. 

(i.e.,  all 
O U T P U T:  A  polyhedron  5"  with  variables  x\,... 
the  variables  of  S  except  for  xm)  t h at  is  the  projection  of  S  onto  dimensions 
other  t h an  the  m t h. 

,xm-\,xm+i,... 

,xn 

M E T H O D:  Let  C  be  all  the  constraints  in  S  involving  xm.  Do  the  following: 

1.  For  every  pair  of  a  lower  bound  and  an  upper  bound  on  xm  in  C,  such  as 

create  the  new  constraint 

L  < 

c\xm 

c2xm 

<  U 

c2L  <  c\U 

Note  t h at  c\  and  c2  are  integers,  but  L  and  U  may  be  expressions  with 
variables  other  t h an  xm. 

2.  If  integers  c\  and  c2  have  a  common  factor,  divide  b o th  sides  by  t h at 

factor. 

3.  If t he  new  constraint  is  not  satisfiable,  then  there  is  no  solution  to  S;  i.e., 

the  polyhedra  5  and  S'  are  both  empty  spaces. 

4.  S'  is  the  set  of  constraints  S  -  C,  plus  all  t he  constraints  generated  in 

step  2. 

Note,  incidentally,  t h at  if  xm  has  u  lower  bounds  and  v  upper  bounds,  elimi 
nating  xm  produces  up  to  uv  inequalities,  but  no  more. 

• 

T he  constraints  added  in  step  (1)  of Algorithm  11.11  correspond  to  t he  im 

plications  of constraints  C  on  the  remaining  variables  in  the  system.  Therefore, 
there  is  a  solution  in  S'  if  and  only  if  there  exists  at  least  one  corresponding 

11.3. 

ITERATION  SPACES 

797 

solution  in  S.  Given  a  solution  in  S'  t he  range  of  the  corresponding  xm  can 
be  found  by  replacing  all  variables  but  xm  in  the  constraints  C  by  their  actual 
values. 

E x a m p le  1 1 . 12  :  Consider  the  inequalities  defining  the  iteration  space  in  Fig. 
11.11.  Suppose  we  wish  to  use  Fourier-Motzkin  elimination  to  project  the  two-
dimensional  space  away  from  the  i  dimension  and  onto  the  j  dimension.  There 
is  one  lower  bound  on  i:  0  <  i  and  two  upper  bounds:  i  <  j  and  i  <  5.  This 
generates  two  constraints:  0  <  j  and  0  <  5.  The  latter  is  trivially  true  and 
can  be  ignored.  T he  former  gives  the  lower  bound  on  j,  and  the  original  upper 
• 
bound  j  <  7  gives  t he  upper  bound. 

L o o p - B o u n ds  G e n e r a t i on 

Now  t h at  we  have  defined  Fourier-Motzkin  elimination,  the  algorithm  to  gen 
erate  the  loop  bounds  to  iterate  over  a  convex  polyhedron  (Algorithm  11.13)  is 
straightforward.  We  compute  the  loop  bounds  in  order,  from  the  innermost  to 
the  outer  loops.  All  the  inequalities  involving  the  innermost  loop  index  vari 
ables  are  written  as  the  variable's  lower  or  upper  bounds.  We  then  project 
away  t he  dimension  representing  t he  innermost  loop  and  obtain  a  polyhedron 
with  one  fewer  dimension.  We  repeat  until  the  bounds  for  all  the  loop  index 
variables  are  found. 

A l g o r i t hm  1 1 . 1 3:  Computing  bounds  for  a  given  order  of  variables. 

I N P U T:  A  convex  polyhedron  S  over  variables  v\,... 

,vn. 

O U T P U T:  A  set  of lower  bounds  L{  and  upper  bounds  Ui  for  each  vi,  expressed 
only  in  terms  of  the  fj's,  for  j  <  i. 

M E T H O D:  T he  algorithm  is  described  in  Fig.  11.15. 

• 

E x a m p le  1 1 . 1 4:  We  apply  Algorithm  11.13  to  generate  the  loop  bounds  t h at 
sweep  the  the  iteration  space  of Fig.  11.11  vertically.  The  variables  are  ordered 
j, i.  The  algorithm  generates  these  bounds: 

Li  :  0 
Ui :  5,J 
Lj: 

0 
7 

We  need  to  satisfy  all  the  constraints,  thus  the  bound  on  i  is  min(5,  j).  There 
are  no  redundancies  in  this  example. 

• 

798 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

Sn  —  S;  /*  Use  Algorithm  11.11  to  find  the  bounds  */ 
)  { 
for  (  i  =  n;  i  >  1;  i 
LVi  =  all  the  lower  bounds  on  vi  in  Sf, 
UVi  =  all  t he  upper  bounds  on  vi  in  Si\ 
Si-i  =  Constraints  returned  by  applying  Algorithm  11.11 

to  eliminate  Vi  from  the  constraints  Sf, 

} 
/*  Remove  redundancies  */ 
S'  =  0; 
for  (  i  =  1;  i  <  n;  i  +  +  )  { 

Remove  any  bounds  in  LVi  and  UVi 
Add  the  remaining  constraints  of  LVi  and  UVi  on  vi  to  5"; 

implied  by  S'; 

} 

Figure  11.15:  Code  to  express  variable  bounds  with  respect  to  a  given  variable 
ordering 

[5,5] 
[5,6] 
[5,7] 

[4,4], 
[4,5], 
[4,6], 
[4,7] 

[3,3], 
[3,4], 
[3,5], 
[3,6], 
[3,7] 

[2,2], 
[2,3], 
[2,4], 
[2,5], 
[2,6], 
[2,7] 

[0,0], 

[0,1], 
[0,2], 
[0,3], 
[0,4], 
[0,5], 
[0,6], 
[0,7] 

[1,1], 
[1,2], 
[1,3], 
[1,4], 
[1,5], 
[1,6], 
[1,7] 

Figure  11.16:  Diagonalwise  ordering  of t he  iteration  space  of  Fig.  11.11 

11.3.6  Changing  Axes 

Note  t h at  sweeping  t he  iteration  space  horizontally  and  vertically,  as  discussed 
above,  are  just  two  of  t he  most  common  ways  of  visiting  t he  iteration  space. 
There  are many  other  possibilities;  for example,  we  can  sweep  the  iteration  space 
in  Example  11.6  diagonal  by  diagonal,  as  discussed  below  in  Example  11.15. 

E x a m p le  1 1 . 1 5:  We  can  sweep  t he  iteration  space  shown  in  Fig.  11.11  diag 
onally  using  the  order  shown  in  Fig.  11.16.  The  difference  between  t he  coordi 
nates  j  and  i  in  each  diagonal  is  a  constant,  starting  with  0  and  ending  with 
7.  Thus,  we  define  a  new  variable  k  =  j  —  i  and  sweep  through  the  iteration 
space  in  lexicographic  order  with  respect  to  k  and  j.  Substituting  i  =  j  —  k  in 
the  inequalities  we  get: 

11.3. 

ITERATION  SPACES 

799 

To  create  the  loop  bounds  for  the  order  described  above,  we  can  apply  Algo 
rithm  11.13  to  t he  above  set  of  inequalities  with  variable  ordering  k,  j. 

Lj\ 
Uj\ 
Lk: 
Uk: 

k 
5  +  k,  7 
0 
7 

From  these  inequalities,  we  generate  the  following  code,  replacing  i  by  j  -  k  in 
array  accesses. 

f or  (k  =  0;  k  <=  7;  k++) 

f or  (j  =  k; 

j  <=  m i n ( 5 + k , 7 ); 

j++) 

Z [ j , j - k]  =  0; 

• 

In  general,  we  can  change  the  axes  of  a  polyhedron  by  creating  new  loop 
index  variables  t h at  represent  affine  combinations  of the  original  variables,  and 
defining  an  ordering  on  those  variables.  T he  hard  problem  lies  in  choosing  the 
right  axes  to  satisfy  the  d a ta  dependences  while  achieving  the  parallelism  and 
locality  objectives.  We  discuss  this  problem  starting  with  Section  11.7.  W h at 
we  have  established  here  is  t h at  once  the  axes  are  chosen,  it  is  straightforward 
to  generate  the  desired  code,  as  shown  in  Example  11.15. 

There  are  many  other  iteration-traversal  orders  not  handled  by  this  tech 
nique.  For  example,  we  may  wish  to  visit  all  the  odd  rows  in  an  iteration  space 
before  we  visit  the  even  rows.  Or,  we  may  want  to  start  with  the  iterations  in 
the  middle  of  the  iteration  space  and  progress  to  the  fringes.  For  applications 
t h at  have  affine  access  functions,  however,  the  techniques  described  here  cover 
most  of  the  desirable  iteration  orderings. 

11.3.7  Exercises  for  Section  11.3 

E x e r c i se  1 1 . 3 . 1:  Convert  each  of the  following  loops  to  a  form  where  the  loop 
indexes  are  each  incremented  by  1: 

a)  f or 

( i = 1 0; 

i < 5 0; 

i = i+ 7)  X [ i , i + 1]  = 0 ;. 

b)  f or  ( i=  - 3; 

i < = 1 0; 

i = i + 2)  X [ i]  =  x [ i + l ] ;. 

c)  f or 

( i = 5 0; 

i > = 1 0; 

i —)  X [ i]  =  0 ;. 

E x e r c i se  1 1 . 3 .2  :  Draw  or  describe  the  iteration  spaces  for  each  of the  follow 
ing  loop  nests: 

a)  T he  loop  nest  of  Fig.  11.17(a). 

b)  T he  loop  nest  of  Fig.  11.17(b). 

800 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

f or  (i  =  1; 

i  <  3 0; 

f or  (j  =  i + 2; 

i++) 
j  <  4 0 - 1; 

j++) 

X [ i , j]  =  0; 

(a)  Loop  nest  for  Exercise  11.3.2(a). 

f or  (i  =  10; 

i  <=  1000; 

i++) 

f or  (j  =  i; 

j  <  i + 1 0; 

j + +) 

X [ i , j]  =  0; 

(b)  Loop  nest  for  Exercise  11.3.2(b). 

f or  (i  =  0; 

i  <  100; 

i++) 

f or  (j  =  0; 
f or 

j  <  1 0 0 + i; 

j++) 

i + j;  k  <  1 0 0 - i - j;  k++) 

(k  = 
X [ i , j , k]  =  0; 

(c)  Loop  nest  for  Exercise  11.3.2(c). 

Figure  11.17:  Loop  nests  for  Exercise  11.3.2 

c)  T he  loop  nest  of  Fig.  11.17(c). 

E x e r c i se  1 1 . 3 . 3:  Write  the  constraints  implied  by  each  of  the  loop  nests  of 
Fig.  11.17  in  the  form  of  (11.1).  T h at  is,  give  the  values  of  t he  vectors  i  and  b 
and  the  matrix  B. 

E x e r c i se  1 1 . 3 . 4:  Reverse  each  of  t he  loop-nesting  orders  for  the  nests  of  Fig. 
11.17. 

E x e r c i se  1 1 . 3 .5  :  Use  the  Fourier-Motzkin  elimination  algorithm  to  eliminate 
i  from  each  of  the  sets  of  constraints  obtained  in  Exercise  11.3.3. 

E x e r c i se  1 1 . 3 . 6:  Use  t he  Fourier-Motzkin  elimination  algorithm  to  eliminate 
j  from  each  of the  sets  of  constraints  obtained  in  Exercise  11.3.3. 

E x e r c i se  1 1 . 3. 7:  For  each  of  the  loop  nests  in  Fig.  11.17,  rewrite  the  code  so 
the  axis  i  is  replaced  by  t he  major  diagonal,  i.e.,  t he  direction  of  t he  axis  is 
characterized  by  i  =  j.  The  new  axis  should  correspond  to  t he  outermost  loop. 

E x e r c i se  1 1 . 3 . 8:  Repeat  Exercise  11.3.7  for  the  following  changes  of  axes: 

a)  Replace  i  by  i  + j;  i.e.,  the  direction  of  the  axis  is  the  lines  for  which  i+j 

is  a  constant.  T he  new  axis  corresponds  to  the  outermost  loop. 

b)  Replace  j  by  i  —  2j.  The  new  axis  corresponds  to  the  outermost  loop. 

11.4. 

AFFINE  ARRAY  INDEXES 

801 

!  E x e r c i se  1 1 . 3 . 9:  Let  A,  B,  and  C  be  integer  constants  in  the  following  loop, 

with  C  >  1  and  B  >  A: 

f or  (i  =  A; 

i  <=  B; 

i  =  i  +  C) 

Z [ i]  =  0; 

Rewrite  t he  loop  so  the  incrementation  of the  loop  variable  is  1  and  t he  initial 
ization  is  to  0,  t h at  is,  to  be  of  the  form 

f or  (j  =  0; 

j  <=  D; 
Z[E*j  +  F]  = 0; 

j++) 

for  integers  D,  E,  and  F.  Express  D,  E,  and  F  in  terms  of  A,  B,  and  C. 

E x e r c i se  1 1 . 3 . 1 0:  For  a  generic  two-loop  nest 

f or  (i  =  0; 

i  <=  A; 

i++) 

f o r (j  =  B*i+C; 

j  <=  D*i+E; 

with  A  through  E  integer  constants,  write  the  constraints  t h at  define  the  loop 
nest's  iteration  space  in  matrix-vector  form,  i.e.,  in  the  form  Bi  +  b  =  0. 

E x e r c i se  1 1 . 3 . 1 1:  Repeat  Exercise  11.3.10  for  a  generic  two-loop  nest  with 
symbolic  integer  constants  rn  and  n  as  in 

f or  (i  =  0; 

i  <=  m; 

i++) 

f o r (j  =  A*i+B; 

j  <=  O i + n; 

j++) 

As  before,  A,  B:  and  C  stand  for  specific  integer  constants.  Only  i,  j,  m,  and 
n  should  be  mentioned  in  the  vector  of  unknowns.  Also,  remember  t h at  only  i 
and  j  are  output  variables  for  the  expression. 

11.4  Affine  Array  Indexes 

T he  focus  of this  chapter  is  on  the  class  of affine  array  accesses,  where  each  array 
index  is  expressed  as  affine  expressions  of  loop  indexes  and  symbolic  constants. 
Affine  functions  provide  a  succinct  mapping  from  the  iteration  space  to  t he  d a ta 
space,  making  it  easy  to  determine  which  iterations  m ap  to  the  same  d a ta  or 
same  cache  line. 

Just  as  the  affine  upper  and  lower  bounds  of  a  loop  can  be  represented  as  a 
matrix-vector  calculation,  we  can  do  t he  same  for  affine  access  functions.  Once 
placed  in  the  matrix-vector  form,  we  can  apply  standard  linear  algebra  to  find 
pertinent  information  such  as  the  dimensions  of  t he  d a ta  accessed,  and  which 
iterations  refer  to  the  same  data. 

802 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

11.4.1  Affine  Accesses 

We  say  t h at  an  array  access  in  a  loop  is  affine  if 

1.  The  bounds  of  the  loop  are  expressed  as  affine  expressions  of  the  sur 

rounding  loop  variables  and  symbolic  constants,  and 

2.  The  index  for  each  dimension  of  the  array  is  also  an  affine  expression  of 

surrounding  loop  variables  and  symbolic  constants. 

E x a m p le  1 1 . 1 6:  Suppose  i  and  j  are  loop  index  variables  bounded  by  affine 
expressions.  Some  examples  of  affine  array  accesses  are  Z[i],  Z[i  + j  +  1],  Z[0], 
Z[i,  i],  and  Z[2*i +1,3* j  —  10].  If  n  is  a  symbolic  constant  for  a  loop  nest,  then 
Z[S  *  n, n  —  j]  is  another  example  of  an  affine  array  access.  However,  Z[i  *  j] 
• 
and  Z[n  * j]  are  not  affine  accesses. 

Each  affine  array  access  can  be  described  by  two  matrices  and  two  vectors. 
The  first  matrix-vector  pair  is  the  B  and  b  t h at  describe  the  iteration  space  for 
the  access,  as  in  the  inequality  of  Equation  (11.1).  The  second  pair,  which  we 
usually  refer  to  as  F  and  f,  represent  the  function(s)  of  the  loop-index  variables 
t h at  produce  the  array  index(es)  used  in  t he  various  dimensions  of  the  array 
access. 

Formally,  we  represent  an  array  access  in  a  loop  nest  t h at  uses  a  vector  of 
index  variables  i  by  the  four-tuple  T  =  ( F , f , B > b );  it  maps  a  vector  i  within 
the  bounds 

to  the  array  element  location 

Bi  +  b  >  0 

Fi  +  f 

E x a m p le  1 1 . 1 7:  In  Fig.  11.18  are  some  common  array  accesses,  expressed  in 
matrix  notation.  The  two  loop  indexes  are  i  and  j,  and  these  form  the  vector 
i.  Also,  X,  Y,  and  Z  are  arrays  with  1,  2,  and  3  dimensions,  respectively. 

The  first  access,  A[i  -  1],  is  represented  by  a  1  x  2  matrix  F  and  a  vector  f 
of length  1.  Notice  t h at  when  we  perform  t he  matrix-vector  multiplication  and 
which  is  exactly  t he 
add  in  the  vector  f,  we  are  left  with  a  single  function, 
formula  for  the  access  to  the  one-dimensional  array  X.  Also  notice  t he  third 
access,  Y[j,j  + 1],  which,  after  matrix-vector  multiplication  and  addition,  yields 
a  pair  of  functions,  (J,j  +  1).  These  are  the  indexes  of  the  two  dimensions  of 
t he  array  access. 

Finally,  let  us  observe  the  fourth  access  K [ l , 2 ].  This  access  is  a  constant, 
and  unsurprisingly  t he  matrix  F  is  all  0's.  Thus,  the  vector  of  loop  indexes,  i, 
does  not  appear  in  the  access  function. 

• 

11.4. 

AFFINE  ARRAY  INDEXES 

803 

A C C E SS 

A F F I NE  E X P R E S S I ON 

X [ i - 1] 

[1 

0] 

• 

i 

j  .  + 1 - 1] 

Y [ i , j] 

Y [ j , j + 1] 

Y [ l , 2] 

"  1  0  ' 
0  1 

i 

_  j  . 

"  0  " 
0 

+ 

" 0 1' 
1 
0 

i 

.  j  _ 

+  "  0  " 
u  1 

" 0 0" 
0  0 

i 

.  j  . 

+ 

"  1  " 
2 

Z [ l , i , 2 * i + j] 

" 0 0" 
1  0 
2  1 

+ 

_ j  _ 

"  1  ' 
0 
0 

Figure  11.18:  Some  array  accesses  and  their  matrix-vector  representations 

11.4.2  Affine  and  Nonaffine  Accesses  in  Practice 

There  are  certain  common  d a ta  access  patterns  found  in  numerical  programs 
t h at  fail  to  be  affine.  Programs  involving  sparse  matrices  are  one  important 
example.  One  popular  representation  for  sparse  matrices  is  to  store  only  t he 
nonzero  elements  in  a  vector,  and  auxiliary  index  arrays  are  used  to  mark 
where  a  row  starts  and  which  columns  contain  nonzeros.  Indirect  array  accesses 
are  used  in  accessing  such  data.  An  access  of  this  type,  such  as 
is  a 
nonaffine  access  to  the  array  X.  If the  sparsity  is  regular,  as  in  banded  matrices 
having  nonzeros  only  around  the  diagonal,  then  dense  arrays  can  be  used  to 
represent  the  subregions  with  nonzero  elements.  In  t h at  case,  accesses  may  be 
affine. 

Another  common  example  of  nonaffine  accesses  is  linearized  arrays.  P r o 
grammers  sometimes  use  a  linear  array  to  store  a  logically  multidimensional 
object.  One  reason  why  this  is  t he  case  is  t h at  the  dimensions  of  the  array 
may  not  be  known  at  compile  time.  An  access  t h at  would  normally  look  like 
Z[i,j]  would  be  expressed  as  Z[i  *  n  +  j],  which  is  a  quadratic  function.  We 
can  convert  the  linear  access  into  a  multidimensional  access  if  every  access  can 

804 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

be  decomposed  into  separate  dimensions  with  the  guarantee  t h at  none  of  the 
components  exceeds  its  bound.  Finally,  we  note  t h at  induction-variable  analy 
ses  can  be  used  to  convert  some  nonaffine  accesses  into  affine  ones,  as  shown  in 
Example  11.18. 

E x a m p le  1 1 . 1 8:  We  can  rewrite  the  code 

j  =  n; 

f or  (i  =  0; 

i  <=  n; 

i++)  { 

Z [ j]  =  0; 
j  =  J + 2; 

} 

as 

j  =  n; 
f or  (i  =  0; 

i  <=  n; 

i++)  { 

Z [ n + 2 * i]  =  0; 

} 

to  make  the  access  to  matrix  Z  affine. 

• 

11.4.3  Exercises  for  Section  11.4 
E x e r c i se  1 1 . 4 . 1:  For  each  of  the  following  array  accesses,  give  the  vector  f 
and  the  matrix  F  t h at  describe  them.  Assume  t h at  the  vector  of  indexes  i  is 
i,  j , . . .,  and  t h at  all  loop  indexes  have  affine  limits. 

a)  X[2*i  +  S,2*j 

- 

i]. 

b)  Y[i-j,j 

-k,k- 

i}. 

c)  Z [ 3 , 2 * j , f c - 2 *i  +  l ]. 

11.5  Data  Reuse 

From  array access  functions  we  derive  two  kinds  of information  useful  for  locality 
optimization  and  parallelization: 

1.  Data  reuse:  for  locality  optimization,  we  wish  to  identify  sets  of iterations 

t h at  access  the  same  d a ta  or  the  same  cache  line. 

2.  Data  dependence:  for  correctness  of parallelization  and  locality  loop  trans 
formations,  we  wish  to  identify  all  the  d a ta  dependences  in  the  code.  Re 
call  t h at  two  (not  necessarily  distinct)  accesses  have  a  d a ta  dependence  if 
instances  of  the  accesses  may  refer  to  the  same  memory  location,  and  at 
least  one  of  them  is  a  write. 

11.5. 

DATA  REUSE 

805 

In  many  cases,  whenever  we  identify  iterations  t h at  reuse  the  same  data,  there 
are  d a ta  dependences  between  them. 

Whenever  there  is  a  d a ta  dependence,  obviously  the  same  d a ta  is  reused. 
For  example,  in  matrix  multiplication,  the  same  element  in  t he  output  array 
is  written  0(n)  times.  T he  write  operations  must  be  executed  in  t he  original 
execution  order;3  there  is  reuse  because  we  can  allocate  the  same  element  to  a 
register. 

However,  not  all  reuse  can  be  exploited  in  locality  optimizations;  here  is  an 

example  illustrating  this  issue. 

E x a m p le  1 1 . 1 9:  Consider  the  following  loop: 

f or  (i  =  0;  i  <  n;  i++) 
Z [ 7 i + 3]  =  Z [ 3 i + 5]  ; 

We  observe  t h at  the  loop  writes  to  a  different  location  at  each  iteration,  so  there 
are  no  reuses  or  dependences  on  the  different  write  operations.  T he  loop,  how 
ever,  reads  locations  5 , 8 , 1 1 , 1 4 , 1 7 , . . .,  and  writes  locations  3 , 1 0 , 1 7 , 2 4 ,— 
T he  read  and  write  iterations  access  the  same  elements  17,  38,  and  59  and  so 
on.  T h at  is,  the  integers  of  the  form  17  +  21  j  for  j  =  0 , 1,  2 , . ..  are  all  those 
integers  t h at  can  be  written  both  as  7ii  =  3  and  as  3i2  +  5,  for  some  integers 
i\  and  i2.  However,  this  reuse  occurs  rarely,  and  cannot  be  exploited  easily  if 
at  all. 

• 

D a ta  dependence  is  different  from  reuse  analysis  in  t h at  one  of  t he  accesses 
sharing  a  d a ta  dependence  must  be  a  write  access.  More  importantly,  d a ta  de 
pendence  needs  to  be  both  correct  and  precise.  It  needs  to  find  all  dependences 
for  correctness,  and  it  should  not  find  spurious  dependences  because  they  can 
cause  unnecessary  serialization. 

W i th  d a ta  reuse,  we  only  need  to  find  where  most  of  the  exploitable  reuses 
are.  This  problem  is  much  simpler,  so  we  take  up  this  topic  here  in  this  section 
and  tackle  d a ta  dependences  in  the  next.  We  simplify  reuse  analysis  by  ignoring 
loop  bounds,  because  they  seldom  change  the  shape  of  the  reuse.  Much  of  the 
reuse  exploitable  by  affine  partitioning  resides  among  instances  of  the  same 
array  accesses,  and  accesses  t h at  share  the  same  coefficient  matrix  (what  we 
have  typically  called  F  in  the  affine  index  function).  As  shown  above,  access 
p a t t e r ns  like  7%  +  3  and  3i  +  5  have  no  reuse  of interest. 

11.5.1  Types  of Reuse 

We  first  start  with  Example  11.20  to  illustrate  the  different  kinds  of d a ta  reuses. 
In  the  following,  we  need  to  distinguish  between  the  access  as  an  instruction  in 

3  There  is  a  subtle  point  here.  Because  of  the  commutativity  of  addition,  we  would  get  the 
same  answer  to  the  sum  regardless  of  the  order  in  which  we  performed  the  sum.  However, 
this  case  is  very  special.  In  general,  it  is  far  too  complex  for  the  compiler  to  determine  what 
computation  is  being  performed  by  a  sequence  of  arithmetic  steps  followed  by  writes,  and  we 
cannot  rely  on  there  being  any  algebraic  rules  that  will  help  us  reorder  the  steps  safely. 

806 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

a program,  e.g.,  x  =  Z [ i, j ]  ,  from  the  execution  of this  instruction  many  times, 
as  we  execute  the  loop  nest.  For  emphasis,  we  may  refer  to  the  statement  itself 
as  a  static  access,  while  the  various  iterations  of  the  statement  as  we  execute 
its  loop  nest  are  called  dynamic  accesses. 

Reuses  can  be  classified  as  self versus  group.  If  iterations  reusing  t he  same 
d a ta  come  from  the  same  static  access,  we  refer  to  the  reuse  as  self  reuse;  if 
they  come  from  different  accesses,  we  refer  to  it  as  group  reuse.  T he  reuse  is 
temporal  if  the  same  exact  location  is  referenced;  it  is  spatial  if  t he  same  cache 
line  is  referenced. 

E x a m p le  1 1 . 20  :  Consider  the  following  loop  nest: 

f l o at  Z[n]  ; 

f or  (i  =  0; 

f or  (j  =  0; 

i  <  n; 

i++) 
j  <  n; 

j + +) 

Z [ j + 1]  =  ( Z [ j]  +  Z [ j + 1]  +  Z [ j + 2 ] ) / 3; 

Accesses  Z[j],  Z[j  +  1],  and  Z[j  +  2]  each  have  self-spatial  reuse  because  con 
secutive  iterations  of  the  same  access  refer  to  contiguous  array  elements.  Pre 
sumably  contiguous  elements  are  very  likely  to  reside  on  the  same  cache  line. 
In  addition,  they  all  have  self-temporal  reuse,  since  the  exact  elements  are  used 
over  and  over  again  in  each  iteration  in  the  outer  loop.  In  addition,  they  all  have 
the  same  coefficient  matrix,  and  thus  have  group  reuse.  There  is  group  reuse, 
both  temporal  and  spatial,  between  the  different  accesses.  Although  there  are 
4 n2  accesses  in  this  code,  if  the  reuse  can  be  exploited,  we  only  need  to  bring 
in  about  n /c  cache  lines  into  the  cache,  where  c  is  t he  number  of  words  in  a 
cache  line.  We  drop  a  factor  of  n  due  to  self-spatial  reuse,  a  factor  of  c  to  due 
to  spatial  locality,  and  finally  a  factor  of  4  due  to  group  reuse. 

• 

In  the  following,  we  show  how  we  can  use  linear  algebra  to  extract  t he  reuse 
information  from  affine  array  accesses.  We  are  interested  in  not  just  finding 
how  much  potential  savings  there  are,  but  also  which  iterations  are  reusing  the 
d a ta  so  t h at  we  can  try  to  move  them  close  together  to  exploit  the  reuse. 

11.5.2 

Self  Reuse 

There  can  be  substantial  savings  in  memory  accesses  by  exploiting  self reuse.  If 
t he  d a ta  referenced  by  a  static  access  has  k  dimensions  and  the  access  is  nested 
in  a  loop  d  deep,  for  some  d  >  k,  then  t he  same  d a ta  can  be  reused  nd~k  times, 
where  n  is  the  number  of  iterations  in  each  loop.  For  example,  if  a  3-deep  loop 
nest  accesses  one  column  of  an  array,  then  there  is  a  potential  savings  factor 
It  turns  out  t h at  the  dimensionality  of  an  access  corresponds 
of  n2  accesses. 
to  the  concept  of  the  rank  of  the  coefficient  matrix  in  the  access,  and  we  can 
find  which  iterations  refer  to  the  same  location  by  finding  the  null  space  of  the 
matrix,  as  explained  below. 

11.5. 

DATA  REUSE 

R a nk  of  a  M a t r ix 

807 

T he  rank  of  a  m a t r ix  F  is  t he  largest  number  of  columns  (or  equivalently,  rows) 
of  F  t h at  are  linearly  independent.  A  set  of  vectors  is  linearly  independent  if 
none  of t he  vectors  can  be  written  as  a  linear  combination  of  finitely  many  other 
vectors  in  t he  set. 

E x a m p le  1 1 . 2 1:  Consider  the  matrix 

" 12 

3" 
5  7  9 
4  5  6 
_  2  1  0  _ 

Notice  t h at  the  second  row  is  t he  sum  of  the  first  and  third  rows,  while  t he 
fourth  row  is  the  third  row  minus  twice  the  first  row.  However,  the  first  and 
third  rows  are  linearly  independent;  neither  is  a  multiple  of  t he  other.  Thus, 
the  rank  of  t he  matrix  is  2. 

We  could  also  draw  this  conclusion  by  examining  the  columns.  T he  third 
column  is  twice  the  second  column  minus  the  first  column.  On  the  other  hand, 
any  two  columns  are  linearly  independent.  Again,  we  conclude  t h at  the  rank  is 
2. 

• 

E x a m p le  1 1 . 2 2:  Let  us  look  at  the  array  accesses  in  Fig.  11.18.  The  first 
access,  X[i  —  1],  has  dimension  1,  because  the  rank  of  the  matrix  [1  0]  is  1. 
T h at  is,  the  one  row  is  linearly  independent,  as  is  the  first  column. 

T he  second  access, 

has  dimension  2.  T he  reason  is  t h at  the  matrix 

" 1 0" 
1 
0 

has  two  independent  rows  (and  therefore  two  independent  columns,  of  course). 
T he  third  access,  Y[j, j  +  1],  is  of  dimension  1,  because  the  matrix 

"0  1  " 

0 

1 

has  rank  1.  Note  t h at  t he  two  rows  are  identical,  so  only  one  is  linearly  in 
dependent.  Equivalently,  t he  first  column  is  0  times  t he  second  column,  so 
the  columns  are  not  independent. 
Intuitively,  in  a  large,  square  array  Y,  the 
only  elements  accessed  lie  along  a  one-dimensional  line,  just  above  t he  main 
diagonal. 

T he  fourth  access,  Y[l,2]  has  dimension  0,  because  a  matrix  of  all  0's  has 
rank  0.  Note  t h at  for  such  a  matrix,  we  cannot  find  a  linear  sum  of  even  one 
row  t h at  is  nonzero.  Finally,  the  last  access,  Z[i,i,2  *  i  +  j],  has  dimension  2. 
Note  t h at  in  the  m a t r ix  for  this  access 

" 0 0" 
1  0 
2  1 

808 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

the  last  two  rows  are  linearly  independent;  neither  is  a  multiple  of  t he  other. 
However,  the  first  row  is  a  linear  "sum"  of  the  other  two  rows,  with  b o th 
coefficients  0. 

• 

N u ll  S p a ce  of  a  M a t r ix 

iterations,  so  on  average,  0(nd~r) 

A  reference  in  a  d-deep  loop  nest  with  rank  r  accesses  0(nr)  d a ta  elements 
iterations  must  refer  to  t he  same 
in  0(nd) 
array  element.  Which  iterations  access  the  same  d a t a?  Suppose  an  access  in 
this  loop  nest  is  represented  by  matrix-vector  combination  F  and  f.  Let  i  and 
i'  be  two  iterations  t h at  refer  to  the  same  array  element.  Then  Fi + f  =  Fi'  + f. 
Rearranging  terms,  we  get 

F(i  -  i')  =  0. 

There  is  a  well-known  concept  from  linear  algebra  t h at  characterizes  when 
i  and  i'  satisfy  t he  above  equation.  The  set  of  all  solutions  to  the  equation 
Fv  =  0  is  called  the  null  space  of  F.  Thus,  two  iterations  refer  to  the  same 
array  element  if  t he  difference  of  their  loop-index  vectors  belongs  to  t he  null 
space  of  matrix  F. 

It  is  easy  to  see  t h at  the  null  vector,  v  =  0,  always  satisfies  Fv  =  0.  T h at 
is,  two  iterations  surely  refer  to  the  same  array  element  if  their  difference  is 
0;  in  other  words,  if  they  are  really  the  same  iteration.  Also,  t he  null  space  is 
truly  a  vector  space.  T h at  is,  if  F vi  =  0  and  F v2  =  0,  then  F ( vi  +  v2)  =  0 
and  F ( c v i)  =  0. 

If the  matrix  F  is  fully  ranked,  t h at  is,  its  rank  is  d,  then  the  null  space  of F 
consists  of  only  the  null  vector.  In  t h at  case,  iterations  in  a  loop  nest  all  refer 
to  different  data.  In  general,  the  dimension  of the  null  space,  also  known  as  t he 
nullity,  is  d  —  r.  If  d  >  r,  then  for  each  element  there  is  a  (d  —  r)-dimensional 
space  of  iterations  t h at  access  t h at  element. 

The  null  space  can  be  represented  by  its  basis  vectors.  A  ^-dimensional  null 
space  is  represented  by  k  independent  vectors;  any  vector  t h at  can  be  expressed 
as  a  linear  combination  of  the  basis  vectors  belongs  to  the  null  space. 

E x a m p le  1 1 . 23  :  Let  us  reconsider  the  matrix  of  Example  11.21: 

1 
5 
4 
2 

2 
7 
5 
1 

3 
9 
6 
0 

We  determined  in  t h at  example  t h at  the  rank  of the  matrix  is  2;  thus  the  nullity 
is  3  -  2  =  1.  To  find  a  basis  for  t he  null  space,  which  in  this  case  must  be  a 
single  nonzero  vector  of  length  3,  we  may  suppose  a  vector  in  t he  null  space  to 

11.5. 

DATA  REUSE 

809 

be  [x,y,z]  and  t ry  to  solve  the  equation 

1  2  3 
5  7  9 
4  5  6 
2  1  0 

X 

y 
z 

'  0  " 
0 
0 

If  we  multiply  the  first  two  rows  by  the  vector  of  unknowns,  we  get  t he  two 
equations 

x  +  2y  +  3z 
5z  +  7y  +  9z 

= 
= 

0 
0 

We  could  write  the  equations  t h at  come  from  the  third  and  fourth  rows  as 
well,  but  because  there  are  no  three  linearly  independent  rows,  we  know  t h at 
the  additional  equations  add  no  new  constraints  on  x,  y,  and  z.  For  instance, 
the  equation  we  get  from  the  third  row,  Ax  +  5y  +  Qz  =  0  can  be  obtained  by 
subtracting  the  first  equation  from  the  second. 

We  must  eliminate  as  many  variables  as  we  can  from  the  above  equations. 
Start  by  using  the  first  equation  to  solve  for  x;  t h at  is,  x  —  —2y  —  3z.  Then 
substitute  for  x  in  the  second  equation,  to  get  —  3y  =  6z,  or  y  =  —2z.  Since 
x  =  —2y  —  3z,  and  y  =  —2z:  it  follows  t h at  x  =  z.  Thus,  the  vector  [x,y,z] 
is  really  [z,  —2z,z].  We  may  pick  any  nonzero  value  of  z  to  form  the  one  and 
only  basis  vector  for  the  null  space.  For  example,  we  may  choose  z  =  1  and  use 
[1,  —2,1]  as  the  basis  of  the  null  space. 

• 

Accesses  X[i — 1]  and  Y[j, j + 

E x a m p le  1 1. 2 4:  The  rank,  nullity,  and  null  space  for  each  of the  references  in 
Example  11.17  are  shown  in  Fig.  11.19.  Observe  t h at  t he  sum  of  the  rank  and 
nullity  in  all  the  cases  is  the  depth  of the  loop  nest,  2.  Since  the  accesses 
and  Z[l, i,  2  *  i  +  j]  have  a  rank  of  2,  all  iterations  refer  to  different  locations. 
b o th  have  rank-1  matrices,  so  0(n)  iterations 
refer  to  the  same  location.  In  the  former  case,  entire  rows  in  the  iteration  space 
refer  to  the  same  location.  In  other  words,  iterations  t h at  differ  only  in  the  j 
dimension  share  t he  same  location,  which  is  succinctly  represented  by  t he  basis 
of  the  null  space,  [0,1].  For  Y[j,j  +  1],  entire  columns  in  the  iteration  space 
refer  to  the  same  location,  and  this  fact  is  succinctly  represented  by  the  basis 
of t he  null  space,  [1,0]. 

Finally,  t he  access  F [ l , 2]  refers  to  the  same  location  in  all  the  iterations. 
T he  null  space  corresponding  has  2  basis  vectors,  [0,1],  [1,0],  meaning  t h at  all 
pairs  of  iterations  in  t he  loop  nest  refer  to  exactly  the  same  location. 

• 

11.5.3 

Self-Spatial  Reuse 

The  analysis  of  spatial  reuse  depends  on  the  d a ta  layout  of  the  matrix.  C 
matrices  are  laid  out  in  row-major  order  and  Fortran  matrices  are  laid  out  in 
column-major  order.  In  other  words,  array  elements  X[iJ]  and  X[i,j  +  1]  are 

8 10 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

AC C E SS 

AF F I NE  EX P R E S S I ON 

RA NK 

NU L L 

BA S IS  OF 

I TY 

NU LL  SP A CE 

x C i - i] 

[1 

0] 

i 

.  j  . 

+ 

[ - i] 

1 

Yti.j] 

" 1 0" 

0 

1 

"  0 

' 

0 

+ 

i 

.  j  . 

Y [ j , j+ 1] 

" 0 1" 

0 

1 

i 

.  j  . 

' 

+  "  0 

1 

Y [ l, 2] 

" 0 0" 

0 

0 

i 

.  j  _ 

+  "  1  " 

2 

Z[l,i,2*i+j] 

" 0 0" 

1 

2 

0 

1 

i 

.  j  . 

+ 

"  1  " 

0 

0 

2 

1 

0 

2 

1 

0 

1 

2 

0 

"  0 

1 

1 

0 

"  1 

0 

0  " 

1 

Figure  1 1 . 1 9:  Rank  and  nullity  of  affine  accesses 

contiguous  in  C  and  X[i, j]  and  X[i  +  1, j]  are  contiguous  in  Fortran.  W i t h o ut 
loss  of  generality,  in  t he  rest  of  the  chapter,  we  shall  adopt  the  C  (row-major) 
array  layout. 

As  a  first  approximation,  we  consider  two  array  elements  to  share  the  same 
cache  line  if  and  only  if  they  share  the  same  row  in  a  two-dimensional  array. 
More  generally,  in  an  array  of  d  dimensions,  we  take  array  elements  to  share 
a  cache  line  if  they  differ  only  in  the  last  dimension.  Since  for  a  typical  array 
and  cache,  many  array  elements  can  fit  in  one  cache  line,  there  is  significant 
speedup  to  be  had  by  accessing  an  entire  row  in  order,  even  though,  strictly 
speaking,  we  occasionally  have  to  wait  to  load  a  new  cache  line. 

T he  trick  to  discovering  and  taking  advantage  of  self-spatial  reuse  is  to  drop 
the  last  row  from  the  coefficient  matrix  F.  If  t he  resulting  truncated  matrix  has 
rank  t h at  is  less  t h an  the  depth  of  t he  loop  nest,  then  we  can  assure  spatial 
locality  by  making  sure  t h at  the  innermost  loop  varies  only  the  last  coordinate 
of  the  array. 

E x a m p le  1 1 . 2 5:  Consider  the  last  access,  Z[l,  i,2*  i+  j],  in  Fig.  1 1 . 1 9.  If  we 

11.5. 

DATA 

REUSE 

811 

delete  the  last  row,  we  are  left  with  the  truncated  matrix 

" 0 0" 
0 
1 

T he  rank  of this  matrix  is  evidently  1,  and  since  the  loop  nest  has  depth  2,  there 
is  t he  opportunity  for  spatial  reuse.  In  this  case,  since  j  is  the  inner-loop  index, 
the  inner  loop  visits  contiguous  elements  of  the  array  Z  stored  in  row-major 
order.  Making  i  the  inner-loop  index  will  not  yield  spatial  locality,  since  as  i 
changes,  both  the  second  and  third  dimensions  change. 

• 

T he  general  rule  for  determining  whether  there  is  self-spatial  reuse  is  as 
follows.  As  always,  we  assume  t h at  the  loop  indexes  correspond  to  columns  of 
the  coefficient  matrix  in  order,  with  the  outermost  loop  first,  and  the  innermost 
loop  last.  Then  in  order  for  there  to  be  spatial  reuse,  the  vector  [ 0 , 0 , . ..  , 0,1] 
must  be  in  t he  null  space  of  t he  truncated  matrix.  T he  reason  is  t h at  if  this 
vector  is  in  t he  null  space,  then  when  we  fix  all  loop  indexes  but  the  innermost 
one,  we  know  t h at  all  dynamic  accesses  during  one  run  through  the  inner  loop 
vary  in  only  the  last  array  index.  If the  array  is  stored  in  row-major  order,  then 
these  elements  are  all  near  one  another,  perhaps  in  the  same  cache  line. 

E x a m p le  1 1 . 26  :  Note  t h at  [0,1]  (transposed  as  a  column  vector)  is  in  the  null 
space  of t he  truncated  matrix  of  Example  11.25.  Thus,  as  mentioned  there,  we 
expect  t h at  with  j  as  the  inner-loop  index,  there  will  be  spatial  locality.  On 
t he  other  hand,  if  we  reverse  the  order  of the  loops,  so  i  is  the  inner  loop,  then 
t he  coefficient  matrix  becomes 

" 0 0" 
1 
0 

Now,  [0,1]  is  not  in  the  null  space  of  this  matrix.  Rather,  the  null  space  is 
generated  by  the  basis  vector  [1,0].  Thus,  as  we  suggested  in  Example  11.25, 
we  do  not  expect  spatial  locality  if  i  is  the  inner  loop. 

We  should  observe,  however,  t h at  the  test  for  [ 0 , 0 , . ..  , 0,1]  being  in  t he 
null  space  is  not  quite  sufficient  to  assure  spatial  locality.  For  instance,  suppose 
the  access  were  not  Z[l,i,2*i  +  j]  but  Z[l,i,2*i  +  50*j].  Then,  only  every 
fiftieth  element  of  Z  would  be  accessed  during  one  run  of  the  inner  loop,  and 
we  would  not  reuse  a  cache  line  unless  it  were  long  enough  to  hold  more  t h an 
50  elements. 

• 

11.5.4  Group  Reuse 

We  compute  group  reuse  only  among  accesses  in  a  loop  sharing  the  same  coef 
ficient  matrix.  Given  two  dynamic  accesses  F ii  +  fi  and  F i2  +  f2,  reuse  of  the 
same  d a ta  requires  t h at 

F ii  + fi  =  F i2  + f2 

812 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

or 

F ( i i - i2)  =  ( f2- f i ). 

Suppose v  is  one  solution  to  this  equation.  Then  if w  is  any  vector  in  the  null 
space  of  F i, w + v  is  also  a  solution,  and  in  fact  those  are  all  the  solutions  to 
the  equation. 

E x a m p le  1 1 . 2 7:  T he  following  2-deep  loop  nest 

f or  (i  =  1; 

i  <=  n; 

i++) 

f or  (j  =  1;  j  <=  n; 

Z [ i , j]  =  Z [ i - l , j ]; 

has  two  array  accesses,  Z[i,j]  and  Z[i  —  l,j].  Observe  t h at  these  two  accesses 
are  both  characterized  by  the  coefficient  matrix 

1  0 
0  1 

like  the  second  access,  Y"[i, j]  in  Fig.  11.19.  This  matrix  has  rank  2,  so  there  is 
no  self-temporal  reuse. 

However,  each  access  exhibits  self-spatial  reuse.  As  described  in  Section 
11.5.3,  when  we  delete  the  bottom  row  of  the  matrix,  we  are  left  with  only  the 
top  row,  [1,0],  which  has  rank  1.  Since  [0,1]  is  in  the  null  space  of this  truncated 
matrix,  we  expect  spatial  reuse.  As  each  incrementation  of  inner-loop  index  j 
increases  the  second  array  index  by  one,  we  in  fact  do  access  adjacent  array 
elements,  and  will  make  maximum  use  of  each  cache  line. 

Although  there  is  no  self-temporal  reuse  for  either  access,  observe  t h at  the 
two  references  Z[i,j]  and  Z[i — l,j]  access  almost  the  same  set  of array  elements. 
T h at  is,  there  is  group-temporal  reuse  because  the  d a ta  read  by  access  Z[i — l,j) 
is  the  same  as  the  d a ta  written  by  access  Z[i,j],  except  for  the  case  i  =  1.  This 
simple  p a t t e rn  applies  to  the  entire  iteration  space  and  can  be  exploited  to 
improve  d a ta  locality  in  the  code.  Formally,  discounting  the  loop  bounds,  the 
two  accesses  Z[i,j]  and  Z[i-  l,j]  refer  to  the  same  location  in  iterations  (k,ji) 
and  (%2, j2),  respectively,  provided 

1  0 
0  1 

+ 

h 

1  o 
0  1 

«2 
h 

+ 

Rewriting  the  terms,  we  get 

" 1  0  ' 
0  1 

k  -  k 
.  h -32 . 

'  -1  " 
0 

T h at  is,  ji  =  J2  and  i2  =  k  +  1. 

Notice  t h at  the  reuse  occurs  along  the  i-axis  of the  iteration  space.  T h at  is, 
the  iteration  (kih)  occurs  n  iterations  (of  the  inner  loop)  after  the  iteration 

11.5. 

DATA  REUSE 

813 

T h u s,  many  iterations  are  executed  before  the  d a ta  written  is  reused. 
This  d a ta  may  or  may  not  still  be  in  t he  cache.  If  the  cache  manages  to  hold 
two  consecutive  rows  of  matrix  Z,  then  access  Z[i  — 
does  not  miss  in  the 
cache,  and  t he  total  number  of  cache  misses  for  t he  entire  loop  nest  is  n2/ c, 
where  c  is  the  number  of elements  per  cache  line.  Otherwise,  there  will  be  twice 
as  many  misses,  since  both  static  accesses  require  a  new  cache  line  for  each  c 
dynamic  accesses. 

• 

E x a m p le  1 1 . 28  :  Suppose  there  are  two  accesses 

A[i,  j, i  + j]  and  A[i  +  1, j  -  1, %  + j] 

in  a  3-deep  loop  nest,  with  indexes  i,  j,  and  k,  from  t he  outer  to  the  inner  loop. 
Then  two  accesses  ii  =  [i\,ji,k\]  and  i2  =  [^2,^2,^2]  reuse  t he  same  element 
whenever 

k 
h  + 
h 

0 
0 
0 

1  0  0  " 
0  1  0 
1  1  0 

«2 
J2  + 
fc2  . 

. 

1  " 

-1 
0 

One  solution  to  this  equation  for  a  vector  v  =  [i\  —  i2, ji  —  j2, &i  —  &2]  is 

v  =  [1,  —1,0];  t h at  is,  i\ 
space  of  the  matrix 

22  +  1,  Ji  =  ji  —  1,  and  k\  =  &2.4  However,  the  null 

F  = 

1  0  0 
1  0 
0 
1  0 
1 

is  generated  by  t he  basis  vector  [0,0,1];  t h at  is,  the  third  loop  index,  k,  can  be 
arbitrary.  Thus,  v,  the  solution  to  the  above  equation,  is  any  vector  [1,  — l , m] 
for  some  m.  P ut  another  way,  a  dynamic  access  to  A[i,j,i  +  j],  in  a  loop  nest 
with  indexes  i,  j,  and 
is  reused  not  only  by  other  dynamic  accesses  A[i, j,  i+j] 
with  the  same  values  of  i  and  j  and  a  different  value  of  k,  but  also  by  dynamic 
accesses  A[i  +  1, j  —  1, i  + j]  with  loop  index  values  i  +  1,  j  —  1,  and  any  value 
of  k. 

• 

Although  we  shall  not  do  so  here,  we  can  reason  about  group-spatial  reuse 
analogously.  As  per  the  discussion  of  self-spatial  reuse,  we  simply  drop  t he  last 
dimension  from  consideration. 

T he  extent  of  reuse  is  different  for  the  different  categories  of  reuse.  Self-
temporal  reuse  gives  the  most  benefit:  a  reference  with  a  ^-dimensional  null 
space  reuses  t he  same  d a ta  0(nk)  times.  T he  extent  of  self-spatial  reuse  is 
limited  by  t he  length  of  the  cache  line.  Finally,  t he  extent  of  group  reuse  is 
limited  by  the  number  of  references  in  a  group  sharing  the  reuse. 

4It  is  interesting  to  observe  that,  although  there  is  a  solution  in  this  case,  there  would  be 
no  solution  if  we  changed  one  of  the  third  components  from  i  + j  to  i  + j  +  1.  That  is,  in 
the  example  as  given,  both  accesses  touch  those  array  elements  that  lie  in  the  2-dimensional 
subspace  S  defined  by  "the  third  component  is  the  sum  of the  first  two  components."  If we 
changed  i + j  to  i + j  +  1,  none  of the  elements  touched  by  the  second  access  would  lie  in  S, 
and  there  would  be  no  reuse  at  all. 

814 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

11.5.5  Exercises  for  Section  11.5 

Exercise  1 1 . 5 . 1:  Compute  the  ranks  of  each  of  the  matrices  in  Fig.  11.20. 
Give  both  a  maximal  set  of  linearly  dependent  columns  and  a  maximal  set  of 
linearly  dependent  rows. 

0 
1 
1  2 
2  3 
3  4 

(a) 

3 

4 

12 
5  6 
9 
3  2 

7 
8 
10  12  15 
2 

3 

0  0  1 
0 
1  1 
1  1 
1 
5  6  3 

(b) 

(c) 

Figure  11.20:  Compute  the  ranks  and  null  spaces  of  these  matrices 

Exercise  1 1 . 5 .2 :  Find  a  basis  for  the  null  space  of each  matrix  in  Fig.  11.20. 

Exercise  1 1 . 5 . 3:  Assume  t h at  the  iteration  space  has  dimensions  (variables) 
i,  j,  and  k.  For  each  of  the  accesses  below,  describe  the  subspaces  t h at  refer  to 
the  following  single  elements  of  the  array: 

a)  A[iJ,i  + 

j] 

b)  A[i,i  +  l,i  +  2] 

!  c)  A[i,i,j  +  k] 

! 

d) 

A[i-j,j-k,k-i] 

! Exercise  1 1 . 5 . 4:  Suppose  array  A  is  stored  in  row-major  order  and  accessed 

inside  the  following  loop  nest: 

for  (i = 0;  i  <  100;  i++) 

for  (j  =  0;  j  <  100;  j++) 

for  (k = 0;  k <  100;  k++) 
<some  access  to  A> 

Indicate  for  each  of  the  following  accesses  whether  it  is  possible  to  rewrite  the 
loops  so  t h at  the  access  to  A  exhibits  self-spatial  reuse;  t h at  is,  entire  cache 
lines  are  used  consecutively.  Show  how  to  rewrite  t he  loops,  if  so.  Note:  the 
rewriting  of  t he  loops  may  involve  b o th  reordering  and  introduction  of  new 
loop  indexes.  However,  you  may  not  change  the  layout  of  the  array,  e.g.,  by 
changing  it  to  column-major  order.  Also  note: 
in  general,  reordering  of  loop 
indexes  may  be  legal  or  illegal,  depending  on  criteria  we  develop  in  the  next 
section.  However,  in  this  case,  where  t he  effect  of  each  access  is  simply  to  set 
an  array  element  to 0,  you  do  not  have  to  worry  about  the  effect  of  reordering 
loops  as  far  as  the  semantics  of  the  program  is  concerned. 

11.6.  ARRAY  DATA-DEPENDENCE  ANALYSIS 

815 

a)  A [ i + l , i + k , j]  =  0. 

!!  b)  A t j + k , i , i]  =  0. 

c)  A [ i ,j  , k , i + j + k]  =  0. 

!!  d)  A [ i , j - k , i + j , i + k]  =  0. 

E x e r c i se  1 1 . 5 . 5:  In  Section  11.5.3  we  commented  t h at  we  get  spatial  locality 
if  the  innermost  loop  varies  only  as  t he  last  coordinate  of  an  array  access. 
However,  t h at  assertion  depended  on  our  assumption  t h at  t he  array  was  stored 
in  row-major  order.  W h at  condition  would  assure  spatial  locality  if  t he  array 
were  stored  in  column-major  order? 

!  E x e r c i se  1 1 . 5 . 6:  In  Example  11.28  we  observed t h at  the  t he  existence  of reuse 
between  two  similar  accesses  depended  heavily  on  the  particular  expressions  for 
t he  coordinates  of  the  array.  Generalize  our  observation  there  to  determine 
for  which  functions  f(i,j)  there  is  reuse  between  the  accesses  A[i,j,i  +  j]  and 
A[i 

l,j-l,f(iJ)}. 

+ 

!  E x e r c i se  1 1 . 5 . 7:  In  Example  11.27  we  suggested  t h at  there  will  be  more  cache 
misses  t h an  necessary  if  rows  of  t he  matrix  Z  are  so  long  t h at  they  do  not  fit 
in  the  cache.  If  t h at  is  the  case,  how  could  you  rewrite  the  loop  nest  in  order 
to  guarantee  group-spatial  reuse? 

11.6  Array  Data-Dependence  Analysis 

Parallelization  or  locality  optimizations  frequently  reorder  t he  operations  ex 
ecuted  in  the  original  program.  As  with  all  optimizations,  operations  can  be 
reordered  only  if the  reordering  does  not  change  the  program's  output.  Since  we 
cannot,  in  general,  understand  deeply  what  a  program  does,  code  optimization 
generally  adopts  a  simpler,  conservative  test  for  when  we  can  be  sure  t h at  t he 
program  output  is  not  affected:  we  check  t h at  the  operations  on  any  memory 
location  are  done  in  the  same  order  in  the  original  and  modified  programs.  In 
the  present  study,  we  focus  on  array  accesses,  so  the  array  elements  are  the 
memory  locations  of  concern. 

Two  accesses,  whether  read  or  write,  are  clearly  independent  (can  be  re 
ordered)  if  they  refer  to  two  different  locations. 
In  addition,  read  operations 
do  not  change  the  memory  state  and  therefore  are  also  independent.  Following 
Section  11.5,  we  say  t h at  two  accesses  are  data  dependent  if  they  refer  to  t he 
same  memory  location  and  at  least  one  of them  is  a  write  operation.  To  be  sure 
t h at  the  modified  program  does  the  same  as  the  original,  the  relative  execu 
tion  ordering  between  every  pair  of  data-dependent  operations  in  the  original 
program  must  be  preserved  in  t he  new  program. 

Recall  from  Section  10.2.1  t h at  there  are  three  flavors  of  d a ta  dependence: 

1.  True  dependence,  where  a  write  is  followed  by  a  read  of  t he  same  location. 

816 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

2.  Antidependence,  where  a  read  is  followed  by  a  write  to  t he  same  location. 

3.  Output  dependence,  which  is  two  writes  to  the  same  location. 

In  the  discussion  above,  d a ta  dependence  is  defined  for  dynamic  accesses. 
We  say  t h at  a  static  access  in  a  program  depends  on  another  as  long  as  there 
exists  a  dynamic  instance  of  the  first  access  t h at  depends  on  some  instance  of 
the  second.5 

It  is  easy  to  see  how  d a ta  dependence  can  be  used  in  parallelization.  For 
example,  if  no  d a ta  dependences  are  found  in  the  accesses  of  a  loop,  we  can 
easily  assign  each  iteration  to  a  different  processor.  Section 11.7  discusses  how 
we  use  this  information  systematically  in  parallelization. 

11.6.1  Definition  of Data  Dependence  of  Array  Accesses 

Let  us  consider  two  static  accesses  to  t he  same  array  in  possibly  different  loops. 
T he  first  is  represented  by  access  function  and  bounds  T  =  (F,f,  B , b)  and  is 
in  a  d-deep  loop  nest;  the  second  is  represented  by  T'  =  ( F ' ,f , B ' , b ')  and  is 
in  a  rf'-deep  loop  nest.  These  accesses  are  d a ta  dependent  if 

1.  At  least  one  of t h em  is  a  write  reference  and 

2.  There  exist  vectors  i  in  Zd  and  i'  in  Zd'  such  t h at 

(a)  Bi  >  0, 

(b)  B'i'  >  0,  and 

(c)  Fi  +  f  =  F'i'  +  f. 

Since  a  static  access  normally  embodies  many  dynamic  accesses,  it  is  also 

meaningful  to  ask  if  its  dynamic  accesses  may  refer  to  the  same  memory  loca 
tion.  To  search  for  dependencies  between  instances  of the  same  static  access,  we 
assume  T  —  T'  and  augment  the  definition  above  with  the  additional  constraint 
t h at  i  ^  i'  to  rule  out  the  trivial  solution. 

E x a m p le  1 1 . 2 9:  Consider  the  following 1-deep  loop  nest: 

for  (i = 1;  i < 10;  i++)  { 

Z[i]  =  Z[i-1]; 

} 

This  loop  has  two  accesses:  Z[i - 1]  and  Z[i};  the  first  is  a  read  reference  and 
the  second  a  write.  To  find  all  t he  d a ta  dependences  in  this  program,  we  need 
to  check  if t he  write  reference  shares  a  dependence  with  itself  and  with  the  read 
reference: 

5Recall  the  difference  between  static  and  dynamic  accesses.  A  static  access  is  an  array 
reference  at  a  particular  location  in  a  program,  while  a  dynamic  access  is  one  execution  of 
that  reference. 

11.6. 

ARRAY  DATA-DEPENDENCE  ANALYSIS 

817 

1.  Data  dependence  between  Z[i  -  1]  and  Z[i].  Except  for  the  first  iteration, 
each  iteration  reads  the  value  written  in  the  previous  iteration.  Mathe 
matically,  we  know  t h at  there  is  a  dependence  because  there  exist  integers 
i  and  %'  such  t h at 

1  <  i  <  10,  1  <  i'  <  10,  and  i  -  1  =  i'. 

There are nine  solutions to the above system of constraints:  (i  =  2, %'  —  1), 
(i  =  3,z'  =  2),  and  so  forth. 

2.  Data  dependence  between  Z[i]  and  itse//. 

It  is  easy  to  see  t h at  different 
iterations  in  the  loop  write  to  different  locations;  t h at  is,  there  are  no 
d a ta  dependencies  among  t he  instances  of  the  write  reference  Z[i].  Math 
ematically,  we  know  t h at  there  does  not  exist  a  dependence  because  there 
do  not  exist  integers  i  and  i'  satisfying 

1  <  i  <  10,  1  <  i'  <  10,  i  =  i',  and  i  ^  %'. 

Notice  t h at  the  third  condition,  i  =  i',  comes  from  the  requirement  t h at 
Z[i]  and  Z[i']  are  the  same  memory  location  T he  contradictory  fourth 
condition,  i  ^  %',  comes  from  the  requirement  t h at  the  dependence  be 
nontrivial  —  between  different  dynamic  accesses. 

It  is  not  necessary  to  consider  d a ta  dependences  between  the  read  reference 
Z[i  —  1]  and  itself  because  any  two  read  accesses  are  independent. 

• 

11.6.2 

Integer  Linear  Programming 

D a ta  dependence  requires  finding  whether  there  exist  integers  t h at  satisfy  a 
system  consisting  of equalities  and  inequalities.  The  equalities  are  derived  from 
t he  matrices  and  vectors  representing  the  accesses;  the  inequalities  are  derived 
from  the  loop  bounds.  Equalities  can  be  expressed  as  inequalities:  an  equality 
x  —  y  can  be  replaced  by  two  inequalities,  x  >  y  and  y  >  x. 

Thus,  d a ta  dependence  may  be  phrased  as  a  search  for  integer  solutions  t h at 
satisfy  a  set  of  linear  inequalities,  which  is  precisely  the  well-known  problem 
Integer  linear  programming  is  an  NP-complete 
of  integer  linear  programming. 
problem.  While  no  polynomial  algorithm  is  known,  heuristics  have  been  de 
veloped  to  solve  linear  programs  involving  many  variables,  and  they  can  be 
quite  fast  in  many  cases.  Unfortunately,  such  standard  heuristics  are  inappro 
priate  for  d a ta  dependence  analysis,  where  the  challenge  is  to  solve  many  small 
and  simple  integer  linear  programs  rather  t h an  large  complicated  integer  linear 
programs. 

T he  d a ta  dependence  analysis  algorithm  consists  of  three  parts: 

818  CHAPTER 

11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

1.  Apply  the  GCD  (Greatest  Common  Divisor)  test,  which  checks  if there  is 
an  integer  solution  to  the  equalities,  using  the  theory  of  linear  Diophan-
tine  equations.  If  there  are  no  integer  solutions,  then  there  are  no  d a ta 
dependences.  Otherwise,  we  use  the  equalities  to  substitute  for  some  of 
the  variables  thereby  obtaining  simpler  inequalities. 

2.  Use  a  set  of  simple  heuristics  to  handle  the  large  numbers  of  typical  in 

equalities. 

3.  In  the  rare  case  where  t he  heuristics  do  not  work,  we  use  a  linear  integer 
programming  solver  t h at  uses  a  branch-and-bound  approach  based  on 
Fourier-Motzkin  elimination. 

11.6.3  The  GCD  Test 

The  first  subproblem  is  to  check  for  the  existence  of  integer  solutions  to  t he 
equalities.  Equations  with  the  stipulation  t h at  solutions  must  be  integers  are 
known  as  Diophantine  equations.  T he  following  example  shows  how  t he  issue 
of  integer  solutions  arises;  it  also  demonstrates  t h at  even  though  many  of  our 
examples  involve  a  single  loop  nest  at  a  time,  t he  d a ta  dependence  formulation 
applies  to  accesses  in  possibly  different  loops. 

E x a m p le  1 1 . 3 0:  Consider  the  following  code  fragment: 

f or  (i  =  1; 

Z [ 2 * i]  = 

i  <  10; 
. . .; 

} 
f or  (j  =  1; 

Z [ 2 * j + 1]  = 

j  <  10; 
. . .; 

i++)  { 

{ 

} 

T he  access  Z[2*i]  only  touches  even  elements  of  Z,  while  access  Z[2  *  j  +  1] 
touches  only  odd  elements.  Clearly,  these  two  accesses  share  no  d a ta  depen 
dence  regardless  of  t he  loop  bounds.  We  can  execute  iterations  in  t he  second 
loop  before  t he  first,  or  interleave  the  iterations.  This  example  is  not  as  con 
trived  as  it  may  look.  An  example  where  even  and  odd  numbers  are  treated 
differently  is  an  array  of  complex  numbers,  where  t he  real  and  imaginary  com 
ponents  are  laid  out  side  by  side. 

To  prove  the  absence  of  d a ta  dependences  in  this  example,  we  reason  as 
follows.  Suppose  there  were  integers  i  and  j  such  t h at  Z[2  *  i]  and  Z[2  * j  +  1] 
are  the  same  array  element.  We  get  t he  Diophantine  equation 

2i  =  2j  +  1. 

There  are  no  integers  i  and  j  t h at  can  satisfy  the  above  equation.  T he  proof 
is  t h at  if  i  is  an  integer,  then  2i  is  even.  If j  is  an  integer,  then  2j  is  even,  so 
2j  +  1  is  odd.  No  even  number  is  also  an  odd  number.  Therefore,  t he  equation 

11.6. 

ARRAY  DATA-DEPENDENCE  ANALYSIS 

819 

has  no  integer  solutions,  and  thus  there  is  no  dependence  between  the  read  and 
write  accesses. 

• 

To  describe  when  there  is  a  solution  to  a  linear  Diophantine  equation,  we 
need  t he  concept  of  t he  greatest  common  divisor  (GCD)  of  two  or  more  integers. 
The GCD of integers 0
integer  t h at  evenly  divides  all  these  integers.  GCD's  can  be  computed  efficiently 
by  the  well-known  Euclidean  algorithm  (see  the  box  on  the  subject). 

1, a2, . .. , an, denoted gcd(ai, a2, • • • , an)y is the largest 

E x a m p le  1 1 . 3 1:  gcd(24,36,54)  =  6,  because  24/6,  3 6 / 6,  and  5 4 /6  each  have 
remainder  0,  yet  any  integer  larger  t h an  6  must  leave  a  nonzero  remainder  when 
dividing  at  least  one  of 24,  36,  and  54.  For  instance,  12  divides  24  and  36  evenly, 
but  not  54. 

• 

T he  importance  of  t he  GCD  is  in  the  following  theorem. 

T h e o r em  1 1 . 3 2:  The  linear  Diophantine  equation 

aiX\  +  a2x2  +  • ..  +  anxn  =  c 

has  an  integer  solution  for  x\,  x2,... 
vides  c. 

• 

,xn 

if  and  only  if  gcd(ai,  a2,... 

,  an)  di 

E x a m p le  1 1 . 3 3:  We  observed  in  Example  11.30  t h at  the  linear  Diophantine 
equation  2i  =  2j  +  1  has  no  solution.  We  can  write  this  equation  as 

2%  -  2j  =  1. 

Now  gcd(2,  —2)  =  2,  and  2  does  not  divide  1  evenly.  Thus,  there  is  no  solution. 

For  another  example,  consider  the  equation 

24x  +  36y  +  54z  =  30. 

Since  gcd(24,36,54)  =  6,  and  3 0 /6  =  5,  there  is  a  solution  in  integers  for  x,  y, 
and  z.  One  solution  is  x  =  —1,  y  =  0,  and  z  =  1,  but  there  are  an  infinity  of 
other  solutions. 

• 

The  first  step  to  the  d a ta  dependence  problem  is  to  use  a  standard  method 
such  as  Gaussian  elimination  to  solve  the  given  equalities.  Every  time  a  linear 
equation  is  constructed,  apply  Theorem  11.32  to  rule  out,  if  possible,  the  ex 
istence  of  an  integer  solution. 
If  we  can  rule  out  such  solutions,  then  answer 
"no".  Otherwise,  we  use  the  solution  of the  equations  to  reduce  t he  number  of 
variables  in  the  inequalities. 

E x a m p le  1 1 . 3 4:  Consider  the  two  equalities 

x  —  2y  +  z 
3x  +  2y  +  z 

= 
= 

0 
5 

820 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

The  Euclidean  Algorithm 

The  Euclidean  algorithm  for  finding  gcd(a,  b)  works  as  follows.  First,  as 
sume  t h at  a  and  b  are  positive  integers,  and  a>b.  Note  t h at  t he  G CD  of 
negative  numbers,  or  the  G CD  of  a  negative  and  a  positive  number  is  t he 
same  as  the  G CD  of  their  absolute  values,  so  we  can  assume  all  integers 
are  positive. 

If  a  =  b,  then  gcd(a, b)  =  a.  If  a  >  b,  let  c  be  t he  remainder  of  a/b. 
If  c  =  0,  then  b  evenly  divides  a,  so  gcd(a, b)  =  b.  Otherwise,  compute 
gcd(6,c);  this  result  will  also  be  gcd(a, b). 
To  compute  g c d ( a i, a2, . ..  ,  an), 

for  n  >  2,  use 

the  Euclidean 
Then  recursively  compute 

algorithm 
g c d ( c , a3, a4,  •  •  •  ,an). 

to  compute  g c d ( a i , a2)  =  c. 

Looking  at  each  equality  by  itself,  it  appears  there  might  be  a  solution.  For 
the  first  equality,  g c d ( l,  - 2 , 1)  =  1  divides  0,  and  for  t he  second  equality, 
gcd(3,2,1)  =  1  divides  5.  However,  if  we  use  the  first  equality  to  solve  for 
z  =  2y  —  x  and  substitute  for  z  in  the  second  equality,  we  get  2x  +  Ay  =  5. 
This  Diophantine  equation  has  no  solution,  since  gcd(2,4)  =  2  does  not  divide 
5  evenly. 

• 

11.6.4  Heuristics  for  Solving  Integer  Linear  Programs 

The  d a ta  dependence  problem  requires  many  simple  integer  linear  programs  be 
solved.  We  now  discuss  several  techniques  to  handle  simple  inequalities  and  a 
technique  to  take  advantage  of t he  similarity  found  in  d a ta  dependence  analysis. 

I n d e p e n d e n t - V a r i a b l es  T e st 

Many  of t he  integer  linear  programs  from  d a ta  dependence  consist  of inequalities 
t h at  involve  only  one  unknown.  T he  programs  can  be  solved  simply  by  testing 
if  there  are  integers  between  t he  constant  upper  bounds  and  constant  lower 
bounds  independently. 

E x a m p le  1 1 . 35  :  Consider  the  nested  loop 

for (i = 0;  i <= 10;  i++) 

for (j = 0; j <= 10; j++) 
Z[i,j] = Z[j+10,i+9] ; 

11.6. 

ARRAY  DATA-DEPENDENCE  ANALYSIS 

821 

To  find  if there  is  a  d a ta  dependence  between  Z[i, j]  and  Z[j +10, i + 9],  we  ask 
if there  exist  integers  i,  j,  i',  and  j'  such  t h at 

0<t,j,«',j'<10 
i=j'  +  10 

j  =  i'  + 11 

The  G CD  test,  applied  to  the  two  equalities  above,  will  determine  t h at  there 

may  be  an  integer  solution.  T he  integer  solutions  to  t he  equalities  are  expressed 

by 

t = t i , j= t 2, t,= t2- l l , j,= t i - 1 0. 

for  any  integers  t\  and  t2.  Substituting  the  variables  t\  and  t2  into  t he  linear 
inequalities,  we  get 

o < 
o < 
o <  t2 
o <  h 

h 
h 

< 10 
< 10 
11  < io 
10  < io 

Thus,  combining  the  lower  bounds  from  the  last  two  inequalities  with  t he  upper 
bounds  from  the  first  two,  we  deduce 

10 <  h  < 10 
11 <  t2  < 10 

Since  the  lower  bound  on  t2  is  greater  t h an  its  upper  bound,  there  is  no  integer 
solution,  and  hence  no  d a ta  dependence.  This  example  shows  t h at  even  if there 
are  equalities  involving  several  variables,  the  GCD  test  may  still  create  linear 
inequalities  t h at  involve  one  variable  at  a  time. 

• 

A c y c l ic  T e st 

Another  simple  heuristic  is  to  find  if  there  exists  a  variable  t h at  is  bounded 
below  or  above  by  a  constant.  In  certain  circumstances,  we  can  safely  replace 
the  variable  by  the  constant;  the  simplified  inequalities  have  a  solution  if  and 
only  if t he  original  inequalities  have  a  solution.  Specifically,  suppose  every  lower 
bound  on  vi  is  of  the  form 

Co  <  CiVi  for  some  Ci  > 0. 

while  the  upper  bounds  on  vi  are  all  of  the  form 

C{Vi  <  C0  +  CiVi  + 

. 

. 

.  +  d-iVi^i  +  Ci+1Vi+i  + 

. . . cn+ vn. 

where  c i,  cx,...  ,  c«  are  all  nonnegative.  Then  we  can  replace  variable  Vi  by 
its  smallest  possible  integer  value.  If  there  is  no  such  lower  bound,  we  simply 

822 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

replace  vi  with  — oo.  Similarly,  if every  constraint  involving V{  can  be  expressed 
in  the  two  forms  above,  but  with  the  directions  of  the  inequalities  reversed, 
then  we  can  replace  variable  V{  with  the  largest  possible  integer  value,  or  by  oo 
if  there  is  no  constant  upper  bound.  This  step  can  be  repeated  to  simplify  t he 
inequalities  and  in  some  cases  determine  if  there  is  a  solution. 

E x a m p le  1 1 . 3 6:  Consider  the  following  inequalities: 

1  <  Vl,V2  <  10 
V3 
0  < 
<  4 
Vi 
V2  < 
Vl 

<  v3  +4 

Variable  vi  is  bounded  from  below  by  v2  and  from  above  by  v3.  However,  v2 
is  bounded  from  below  only  by  t he  constant  1,  and  v3  is  bounded  from  above 
only  by  t he  constant  4.  Thus,  replacing  v2  by  1  and  v3  by  4  in  the  inequalities, 
we  obtain 

1 
1 

< 
< 

vi 
v1 
vi 

< 

10 

< 

8 

which  can  now  be  solved  easily  with  t he  independent-variables  test. 

• 

T he  L o o p - R e s i d ue  T e st 

Let  us  now  consider  the  case  where  every  variable  is  bounded  from  below  and 
above  by  other  variables.  It  is  commonly  the  case  in  d a ta  dependence  analysis 
t h at  constraints  have  the  form  V{  <  Vj+c,  which  can  be  solved  using  a  simplified 
version  of the  loop-residue  test due  to  Shostack.  A  set  of these  constraints  can  be 
represented  by  a  directed  graph  whose  nodes  are  labeled  with  variables.  There 
is  an  edge  from  Vi  to  Vj  labeled  c  whenever  there  is  a  constraint  V{  <  Vj  +  c. 

We  define  t he  weight  of  a  p a th  to  be  the  sum  of  t he  labels  of  all  t he  edges 
along  the  p a t h.  Each  p a th  in  the  graph  represents  a  combination  of  the  con 
straints  in  the  system.  T h at  is,  we  can  infer  t h at  v  <  v'  +  c  whenever  there 
exists  a  p a th  from  v  to  v'  with  weight  c.  A  cycle  in  the  graph  with  weight  c 
If  we  can 
represents  t he  constraint  v  <  v  +  c  for  each  node  v  on  t he  cycle. 
find  a  negatively  weighted  cycle  in  t he  graph,  then  we  can  infer  v  <  v,  which  is 
impossible.  In  this  case,  we  can  conclude  t h at  there  is  no  solution  and  thus  no 
dependence. 

We  can  also  incorporate  into  t he  loop-residue  test  constraints  of  the  form 
c  <  v  and  v  <  c  for  variable  v  and  constant  c.  We  introduce  into  the  system  of 
inequalities  a  new  dummy  variable  vo,  which  is  added  to  each  constant  upper 
and  lower  bound.  Of  course,  v0  must  have  value  0,  but  since  t he  loop-residue 
test  only  looks  for  cycles,  t he  actual  values  of  the  variables  never  becomes 
significant.  To  handle  constant  bounds,  we  replace 

11.6. 

ARRAY  DATA-DEPENDENCE  ANALYSIS 

823 

c 
v  <  chy  v  <v§ 
c  <  v  by  vo  <  v  —  c. 

E x a m p le  1 1 . 3 7:  Consider  the  inequalities 

1 
< 
0  < 

V2 

< 

Vi,V2 
v3 

Vi 
2v! 

< 
< 

10 
4 

< 

2v3-7 

T he  constant  upper  and  lower  bounds  on  v\  become  VQ  <v\ — l  and  v\  <  i>o + 10; 
t he  constant  bounds  on  v2  and  v3  are  handled  similarly.  Then,  converting  t he 
last  constraint  to  v\  <  v3  —  4,  we  can  create  the  graph  shown  in  Fig.  11.21. 
The  cycle  v\,v3,Vo,v\  has  weight  — 1,  so  there  is  no  solution  to  this  set  of 
inequalities. 

• 

-1 

Figure  11.21:  Graph  for  the  constraints  of  Example  11.37 

M e m o i z a t i on 

Often,  similar  d a ta  dependence  problems  are  solved  repeatedly,  because  simple 
access  p a t t e r ns  are  repeated  throughout  the  program.  One  important  technique 
to  speed  up  d a ta  dependence  processing  is  to  use  memoization.  Memoization 
tabulates  t he  results  to  the  problems  as  they  are  generated.  The  table  of stored 
solutions  is  consulted  as  each  problem  is  presented;  the  problem  needs  to  be 
solved  only  if  t he  result  to  the  problem  cannot  be  found  in  t he  table. 

11.6.5 

Solving  General  Integer  Linear  Programs 

We  now  describe  a  general  approach  to  solving  the  integer  linear  programming 
problem.  The  problem  is  NP-complete;  our  algorithm  uses  a  branch-and-bound 
approach  t h at  can  take  an  exponential  amount  of time  in  the  worst  case.  How 
ever,  it  is  rare  t h at  the  heuristics  of  Section  11.6.4  cannot  resolve  the  problem, 
and  even  if  we  do  need  to  apply  t he  algorithm  of  this  section,  it  seldom  needs 
to  perform  t he  branch-and-bound  step. 

824 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

T he  approach  is  to  first  check  for  the  existence  of  rational  solutions  to  the 
inequalities.  This  problem  is  the  classical  linear-programming  problem.  If there 
is  no  rational  solution  to  the  inequalities,  then  t he  regions  of d a ta  touched  by  the 
accesses  in  question  do  not  overlap,  and  there  surely  is  no  d a ta  dependence.  If 
there  is  a  rational  solution,  we  first  try  to  prove  t h at  there  is  an  integer  solution, 
which  is  commonly  the  case.  Failing t h a t,  we  then  split  the  polyhedron  bounded 
by  the  inequalities  into  two  smaller  problems  and  recurse. 

E x a m p le  1 1 . 3 8:  Consider  t he  following  simple  loop: 

f or  (i  =  1; 

i  <  10; 
Z [ i]  =  Z[i+10J  ; 

i++) 

The  elements  touched  by  access  Z[i]  are  Z [ l ] , . ..  ,Z[9],  while  the  elements 
touched  by  Z[i  +  10]  are  Z [ l l ] , . ..  , Z[19].  T he  ranges  do  not  overlap  and 
therefore  there  are  no  d a ta  dependences.  More  formally,  we  need  to  show  t h at 
there  are  no  two  dynamic  accesses  i  and  i',  with  1  <  i  <  9,  1  <  i'  <  9,  and 
i  =  %'  +  10.  If there  were  such  integers  i  and  i',  then  we  could  substitute  i'  +  10 
for  i  and  get  the  four  constraints  on  i':  1  <  i'  <  9  and  1  <  i' +10  <  9.  However, 
i'  +  10  <  9  implies  i'  <  — 1,  which  contradicts  1  <  i'.  Thus,  no  such  integers  i 
and  %'  exist. 

• 

Algorithm  11.39  describes  how  to  determine  if  an  integer  solution  can  be 
found  for  a  set  of  linear  inequalities  based  on  the  Fourier-Motzkin  elimination 
algorithm. 

A l g o r i t hm  1 1 . 3 9:  Branch-and-bound  solution  to  integer  linear  programming 
problems. 

I N P U T:  A  convex  polyhedron  Sn  over  variables  vi,... 

,vn. 

O U T P U T:  "yes"  if  Sn  has  an  integer  solution,  "no"  otherwise. 

M E T H O D:  The  algorithm  is  shown  in  Fig.  11.22. 

• 

Lines  (1)  through  (3)  a t t e m pt  to  find  a  rational  solution  to  the  inequalities. 
If  there  no  rational  solution,  there  is  no  integer  solution.  If  a  rational  solution 
is  found,  this  means  t h at  t he  inequalities  define  a  nonempty  polyhedron.  It  is 
relatively  rare  for  such  a  polyhedron  not  to  include  any  integer  solutions  —  for 
t h at  to  happen,  the  polyhedron  must  be  relatively  thin  along  some  dimension 
and  fit  between  integer  points. 

Thus,  lines  (4)  through  (9)  try  to  check  quickly  if there  is  an  integer  solution. 
Each  step  of  the  Fourier-Motzkin  elimination  algorithm  produces  a  polyhedron 
with  one  fewer  dimension  t h an  the  previous  one.  We  consider  t he  polyhedra  in 
reverse  order.  We  start  with  the  polyhedron  with  one  variable  and  assign  to  t h at 
variable  an  integer  solution  roughly  in  the  middle  of t he  range  of possible  values 
if possible.  We  then  substitute  the  value  for  the  variable  in  all  other  polyhedra, 
decreasing  their  unknown  variables  by  one.  We  repeat  the  same  process  until 

11.6. 

ARRAY  DATA-DEPENDENCE  ANALYSIS 

825 

1) 

apply  Algorithm  11.13  to  Sn  to  project  away  variables 

vn,  vn-i,... 

,  vi 

in 

t h at  order; 

2) 

let  Si  be  the  polyhedron  after  projecting  away  vi+i,  for 

i  =  n  —  l ,n  —  2 , . ..  , 0; 

3) 

if  So  is  false  r e t u rn  "no"; 

/*  There  is  no  rational  solution  if  So,  which  involves 
only  constants,  has  unsatisfiable  constraints  */ 

for  (i  =  l;i  <  n;i++)  { 

if  (Si  does  not  include  an  integer  value)  break; 
pick  Ci,  an  integer  in  the  middle  of the  range  for  Vi  in  Sf, 
modify  Si  by  replacing  vi  by  cf, 

} 
if  (i  ==  n  +  1)  r e t u rn  "yes"; 
if  (i  ==  1)  r e t u rn  "no"; 
let  t he  lower  and  upper  bounds  on  Vi  in  Si  be 

k  and  Ui,  respectively; 

4) 
5) 
6) 
7) 

8) 
9) 
10) 
11) 

12) 

recursively  apply  this  algorithm  to  Sn  U  {v^  <  [k\}  and 

13) 

if  (either  returns  "yes")  r e t u rn  "yes"  e l se  r e t u rn  "no"; 

SnU{vi> 

\ui]}; 

Figure  11.22:  Finding  an  integer  solution  in  inequalities 

we  have  processed  all  the  polyhedra,  in  which  case  an  integer  solution  is  found, 
or  we  have  found  a  variable  for  which  there  is  no  integer  solution. 

If  we  cannot  find  an  integer  value  for  even  the  first  variable,  there  is  no 
integer  solution  (line  10).  Otherwise,  all  we  know  is  t h at  there  is  no  integer 
solution  including  the  combination  of specific  integers  we  have  picked  so  far,  and 
the  result  is  inconclusive.  Lines  (11)  through  (13)  represent  the  branch-and-
bound  step.  If  variable  Vi  is  found  to  have  a  rational  but  not  integer  solution, 
we  split  the  polyhedron  into  two  with  the  first  requiring  t h at  Vi  must  be  an 
integer  smaller  t h an  the  rational  solution  found,  and  the  second  requiring  t h at 
Vi  must  be  an  integer  greater  t h an  the  rational  solution  found.  If  neither  has  a 
solution,  then  there  is  no  dependence. 

11.6.6  Summary 

We  have  shown  t h at  essential  pieces  of  information  t h at  a  compiler  can  glean 
from  array  references  are  equivalent  to  certain  standard  mathematical  concepts. 
Given  an  access  function  T  —  (F,  f,  B,  b): 

1.  The  dimension  of  the  d a ta  region  accessed  is  given  by  t he  rank  of  t he 
matrix  F.  The  dimension  of  the  space  of  accesses  to  the  same  location  is 
given  by  the  nullity  of  F.  Iterations  whose  differences  belong  to  t he  null 
space  of  F  refer  to  the  same  array  elements. 

826 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

2.  Iterations  t h at  share  self-temporal  reuse  of  an  access  are  separated  by 
vectors  in  the  null  space  of F.  Self-spatial  reuse  can  be  computed  similarly 
by  asking  when  two  iterations  use  t he  same  row,  rather  t h an  the  same 
element.  Two  accesses  Fix  +  fi  and  F i2  +  f2  share  easily  exploitable 
locality  along  the  d  direction,  if d  is  t he  particular  solution  to  the  equation 
Fd  =  (fi  -  f2). 
In  particular,  if  d  is  the  direction  corresponding  to  the 
innermost  loop,  i.e.,  the  vector  [ 0 , 0 , . ..  , 0,1],  then  there  is  spatial  locality 
if  the  array  is  stored  in  row-major  form. 

3.  T he  d a ta  dependence  problem  —  whether  two  references  can  refer  to  t he 
same  location  —  is  equivalent  to  integer  linear  programming.  Two  access 
functions  share  a  d a ta  dependence  if  there  are  integer-valued  vectors  i 
and  i'  such  t h at  Bi  >  0,  B'i'  >  0,  and  Fi  +  f  =  F'i'  +  f. 

11.6.7  Exercises  for  Section  11.6 

E x e r c i se  1 1 . 6 . 1:  Find  the  GCD's  of  t he  following  sets  of  integers: 

a)  {16,24,56}. 

b)  { - 4 5 , 1 0 5 , 2 4 0 , }. 

!  c)  {84,105,180,315,350}. 

E x e r c i se  1 1 . 6 . 2:  For  t he  following  loop 

f or  (i  =  0; 

i  <  10; 
A [ i]  =  A C l O - i ]; 

i++) 

indicate  all  the 

a)  True  dependences  (write  followed  by  read  of t he  same  location). 

b)  Antidependences  (read  followed  by  write  to  the  same  location). 

c)  O u t p ut  dependences  (write  followed  by  another  write  to  the  same  loca 

tion) . 

!  E x e r c i se  1 1 . 6 . 3:  In  the  box  on  the  Euclidean  algorithm,  we  made  a  number 

of  assertions  without  proof.  Prove  each  of  the  following: 

a)  T he  Euclidean  algorithm as  stated  always  works.  In  particular,  gcd(6,  c)  = 

gcd(o,  6),  where  c  is  t he  nonzero  remainder  of  a/b. 

b)  gcd(a,&)  =  gcd(a,  -b). 

c)  g c d ( a i , a2, . ..  , o „)  =  gcd(gcd(oi,  a2) , a3, a4, . ..  , on)  for  n  >  2. 

11.6. 

ARRAY  DATA-DEPENDENCE  ANALYSIS 

827 

d)  T he  G CD  is  really  a  function  on  sets  of integers;  i.e.,  order  doesn't  m a t t e r. 
Show  the  commutative  law for  GCD:  gcd(a,  b)  =  gcd(6,  a).  Then,  show  the 
more  difficult  statement,  the  associative  law  for  G C D:  gcd(gcd(a,  b),c)  = 
gcd(a,gcd(6,  c)).  Finally,  show  t h at  together  these  laws  imply  t h at  the 
G CD  of  a  set  of  integers  is  the  same,  regardless  of  the  order  in  which  the 
G C D 's  of  pairs  of  integers  are  computed. 

e)  If  S  and  T  are  sets  of  integers,  then  g c d (5  U  T)  =  gcd(gcd(5), g c d ( T ) ). 

!  E x e r c i se  1 1 . 6 . 4:  Find  another  solution  to  the  second  Diophantine  equation 

in  Example  11.33. 

E x e r c i se  1 1 . 6 .5  :  Apply  the  independent-variables  test  in  the  following  situa 
tion.  The  loop  nest  is 

f or 

( i = 0; 
f or 

i < 1 0 0; 

i++) 

j < 1 0 0; 

( j = 0; 
f or  (k=0;  k<100;  k++) 

j++) 

and  inside  t he  nest  is  an  assignment  involving  array  accesses.  Determine  if there 
are  any  d a ta  dependences  due  to  each  of  the  following  statements: 

a)  A [ i , j , k]  =  A [ i + 1 0 0 , j + 1 0 0 , k + 1 0 0 ]. 

b)  A [ i , j , k]  =  A [ j + 1 0 0 , k + 1 0 0 , i + 1 0 0 ]. 

c)  A [ i , j , k]  =  A [ j - 5 0 , k - 5 0 , i - 5 0 ]. 

d)  A [ i , j , k]  =  A [ i + 9 9 , k + 1 0 0 , j ]. 

E x e r c i se  1 1 . 6 . 6:  In  the  two  constraints 

1 
3 

< 
< 

< y - 1 00 
x 
x  <  2y  -  50 

eliminate  x  by  replacing  it  by  a  constant  lower  bound  on  y. 

E x e r c i se  1 1 . 6 . 7:  Apply  the  loop-residue  test  to  the  following  set  of  con 
straints: 

0  <  £  <  99 
0  <  2/  <  99 
0  <  z  <  99 

y < a ; - 50 
z<y-60 

E x e r c i se  1 1 . 6 . 8:  Apply  t he  loop-residue  test  to  t he  following  set  of  con 
straints: 

0 < z < 99 
0<y  <  99 
0 < £ < 99 

y  <x-50 
z <y  +  40 
x  <  z  +  20 

828 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

E x e r c i se  1 1 . 6 . 9:  Apply  the  loop-residue  test  to  t he  following  set  of  con 
straints: 

0  <  x  <  99 
0<y<99 
0<z<99 

y  <  x  -  100 
z<y  +  60 
x<z  +  50 

11.7  Finding  Synchronization-Free  Parallelism 

Having  developed  the  theory  of  affine  array  accesses,  their  reuse  of  data,  and 
the  dependences  among  them,  we  shall  now  begin  to  apply  this  theory  to  paral 
lelization  and  optimization  of  real  programs.  As  discussed  in  Section  11.1.4,  it 
is  important  t h at  we  find  parallelism  while  minimizing  communication  among 
processors.  Let  us  start  by  studying  t he  problem  of parallelizing  an  application 
without  allowing  any  communication  or  synchronization  between  processors  at 
all.  This  constraint  may  appear  to  be  a  purely  academic  exercise;  how  often 
can  we  find  programs  and  routines  t h at  have  such  a  form  of  parallelism? 
In 
fact,  many  such  programs  exist  in  real  life,  and  the  algorithm  for  solving  this 
problem  is  useful  in  its  own  right.  In  addition,  the  concepts  used  to  solve  this 
problem  can  be  extended  to  handle  synchronization  and  communication. 

11.7.1  An  Introductory  Example 

Shown  in  Fig.  11.23  is  an  excerpt  of  a  C  translation  (with  Fortran-style  array 
accesses  retained  for  clarity)  from  a  5000-line  Fortran  multigrid  algorithm  to 
solve  three-dimensional  Euler  equations.  The  program  spends  most  its  time 
in  a  small  number  of  routines  like  t he  one  shown  in  the  figure. 
It  is  typical 
of  many  numerical  programs.  These  often  consist  of  numerous  for-loops,  with 
different  nesting  levels,  and  they  have  many  array  accesses,  all  of  which  are 
affine  expressions  of  surrounding  loop  indexes.  To  keep  the  example  short,  we 
have  elided  lines  from  the  original  program  with  similar  characteristics. 

The  code  of  Fig.  11.23  operates  on  the  scalar  variable  T  and  a  number 
of  different  arrays  with  different  dimensions.  Let  us  first  examine  the  use  of 
variable  T.  Because  each  iteration  in  the  loop  uses  the  same  variable  T,  we 
cannot  execute  the  iterations  in  parallel.  However,  T  is  used  only  as  a  way 
to  hold  a  common  subexpression  used  twice  in  the  same  iteration.  In  t he  first 
two  of  the  three  loop  nests  in  Fig.  11.23,  each  iteration  of  the  innermost  loop 
writes  a  value  into  T  and  uses  the  value  immediately  after  twice,  in  the  same 
iteration.  We  can  eliminate  the  dependences  by  replacing  each  use  of  T  by  t he 
right-hand-side  expression  in  the  previous  assignment  of  T,  without  changing 
the  semantics  of  the  program.  Or,  we  can  replace  the  scalar  T  by  an  array.  We 
then  have  each  iteration 

use  its  own  array  element  T[j,  i]. 

W i th  this  modification,  t he  computation  of  an  array  element  in  each  as 
signment  statement  depends  only  on  other  array  elements  with  t he  same  values 
for  the  last  two  components  (j  and  i,  respectively).  We  can  thus  group  all 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

829 

for  (j  = 2;  j  <= jl; 

for  (i = 2,  i <= il,  i++)  { 

AP[j,i] 

= 

T 

=  1.0/(1.0 + AP[j,i]); 

D[2,j,i] 

= T*AP[j,i] ; 

DW[l,2,j5i] = T*DW[l,2,j,i] ; 

} 

for  (k = 3;  k <= kl-1;  k++) 

for  (j  = 2;  j  <= jl;  j++) 

for  (i = 2;  i <= il;  i++)  { 

AM[j,i] 

=  AP[j,i]; 

AP[j,i] 
T 
D[k,j,i] 

= . . . ; 

=  . . . A P[ j , i] -  AM[j,i]*D[k-l,j,i]...; 
= T*AP[j,i]; 

DW[l,k,j,i] = T*(DW[l,k,j,i] + DW[1 ,k-l, j , i ] ). ..; 

} 

for  (k = kl-1;  k  >=  2;  k —) 

for  (j  = 2;  j  <= jl; 

for  (i = 2;  i  <= il;  i++) 

DW[l,k,j,i] = DW[l,k,j,i] + D[k,j,i]*DW[l,k+l,j,i]; 

Figure 11.23:  Code  excerpt  of a  multigrid  algorithm 

operations  t h at  operate  on  t he  ( j , i ) th  element  of  all  arrays  into  one  computa 
tion  unit,  and  execute  them  in  the  original  sequential  order.  This  modification 
produces  ( jl  —  1)  x  ( il  —  1)  units  of  computation  t h at  are  all  independent  of 
one  another.  Notice  t h at  second  and  third  nests  in  the  source  program  involve 
a  third  loop,  with  index  k.  However,  because  there  is  no  dependence  between 
dynamic  accesses  with  the  same  values  for  j  and  «,  we  can  safely  perform  t he 
loops  on  k  inside  t he  loops  on  j  and  i  —  t h at  is,  within  a  computation  unit. 

Knowing  t h at  these  computation  units  are  independent  enables  a  number 
of  legal  transforms  on  this  code.  For  example,  instead  of  executing  t he  code  as 
originally  written,  a  uniprocessor  can  perform  t he  same  computation  by  execut 
ing  t he  units  of  independent  operation  one  unit  at  a  time.  T he  resulting  code, 
shown  in  Fig. 11.24,  has  improved  temporal  locality,  because  results  produced 
are  consumed  immediately. 

T he  independent  units  of  computation  can  also  be  assigned  to  different 
processors  and  executed  in  parallel,  without  requiring  any  synchronization  or 
communication.  Since  there  are  ( jl  — 1)  x  ( il  — 1)  independent  units  of com 
putation,  we  can  utilize  at  most  ( jl  - 1)  x  ( il  - 1)  processors.  By  organizing 
the  processors  as  if  they  were  in  a 2-dimensional  array,  with  ID's 
where 
2  <  j  < 
i l,  t he  S P MD  program  to  be  executed  by  each 
processor  is  simply  the  body  in  the  inner  loop  in  Fig. 11.24. 

jl  a nd 2  <  i  < 

830 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

for (j = 2; j <= jl; j++) 

for (i = 2; i <= il; i++) { 

AP[j,i] 
T[j,i] 
D[2,j,i] 

=  ...; 
=  1.0/(1.0 + AP[j,i]); 
= T[j,i]*AP[j,i]; 

DW[l,2,j,i] 
for (k = 3; k <= kl-1; k++) { 

= T[j,i]*DW[l,2,j,i]; 

AM[j,i] 
AP[j,i] 
T[j,i] 
D[k,j,i] 
DW[l,k,j5i]  = T[j,i]*(DW[l,kJj,i] + DW[1 ,k-l, j , i] ). . . ; 

= A P [ j , i ]; 
=  ...; 
=  ...AP[j,i]  - AM[j,i]*D[k-l,j,i]...; 
= T[j,i]*AP[j,i]; 

} 

for (k = kl-1; k >= 2; k —) 

DW[l,k,j,i]  = DW[l,k,j,i] + D[k, j , i] *DW[1 ,k+l, j , i] ; 

} 

Figure 11.24:  Code  of Fig. 11.23  transformed  to  carry  outermost  parallel  loops 

T he  above  example  illustrates  the  basic  approach  to  finding  synchronization-
free  parallelism.  We  first  split  the  computation  into  as  m a ny  independent  units 
as  possible.  This  partitioning  exposes  the  scheduling  choices  available.  We 
then  assign  computation  units  to  the  processors,  depending  on  t he  number  of 
processors  we  have.  Finally,  we  generate  an  S P MD  program  t h at  is  executed 
on  each  processor. 

11.7.2  Affine  Space  Partitions 

A  loop  nest  is  said  to  have  k  degrees  of  parallelism  if  it  has,  within  the  nest,  k 
parallelizable  loops  —  t h at  is,  loops  such  t h at  there  are  no  d a ta  dependencies 
between  different  iterations  of  t he  loops.  For  example,  t he  code  in  Fig. 11.24 
has 2  degrees  of parallelism.  It  is  convenient  to  assign  the  operations  in  a  com 
putation  with  k  degrees  of  parallelism  to  a  processor  array  with  k  dimensions. 
We  shall  assume  initially  t h at  each  dimension  of  the  processor  array  has 
as  many  processors  as  there  are  iterations  of  the  corresponding  loop.  After 
all  the  independent  computation  units  have  been  found,  we  shall  m ap  these 
"virtual"  processors  to  t he  actual  processors.  In  practice,  each  processor  should 
be  responsible  for  a  fairly  large  number  of  iterations,  because  otherwise  there 
is  not  enough  work  to  amortize  away  t he  overhead  of  parallelization. 

We  break  down  the  program  to  be  parallelized  into  elementary  statements, 
such  as  3-address  statements.  For  each  statement,  we  find  an  affine  space 
partition  t h at  maps  each  dynamic  instance  of  the  statement,  as  identified  by  its 
loop  indexes,  to  a  processor  ID. 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

831 

E x a m p le  1 1 . 4 0:  As  discussed  above,  the  code  of Fig.  11.23  has  two  degrees  of 
parallelism.  We  view  the  processor  array  as  a  2-dimensional  space.  Let  ( p i , P 2) 
be  t he  ID  of  a  processor  in  the  array.  The  parallelization  scheme  discussed  in 
Section  11.7.1  can  be  described  by  simple  affine  partition  functions.  All  the 
statements  in  t he  first  loop  nest  have  this  same  affine  partition: 

Pi 
P2 

1  0 
1 
0 

+ 

All  t he  statements  in  the  second  and  third  loop  nests  have  the  following  same 
affine  partition: 

Pi 
P2 

• 

10 

0 
0  0 

1 

+ 

The  algorithm  to  find  synchronization-free  parallelism  consists  of three  steps: 

1.  Find,  for  each  statement  in  the  program,  an  affine  partition  t h at  maxi 
mizes  t he  degree  of  parallelism.  Note  t h at  we  generally  treat  the  state 
ment,  rather  t h an  the  single  access,  as  the  unit  of computation.  The  same 
affine  partition  must  apply  to  each  access  in  the  statement.  This  grouping 
of  accesses  makes  sense,  since  there  is  almost  always  dependence  among 
accesses  of  t he  same  statement  anyway. 

2.  Assign  the  resulting  independent  computation  units  among  the  processors, 
and  choose  an  interleaving  of the  steps  on  each  processor.  This  assignment 
is  driven  by  locality  considerations. 

3.  Generate  an  S P MD  program  to  be  executed  on  each  processor. 

We  shall  discuss  next  how  to  find  the  affine  partition  functions,  how  to  gen 
erate  a  sequential  program  t h at  executes  the  partitions  serially,  and  how  to 
generate  an  S P MD  program  t h at  executes  each  partition  on  a  different  pro 
cessor.  After  we  discuss  how  parallelism  with  synchronizations  is  handled  in 
Sections  11.8  through  11.9.9,  we  return  to  Step  2  above  in  Section  11.10  and 
discuss  t he  optimization  of  locality  for  uniprocessors  and  multiprocessors. 

11.7.3  Space-Partition  Constraints 

To  require  no  communication,  each  pair  of  operations  t h at  share  a  d a ta  depen 
dence  must  be  assigned  to  the  same  processor.  We  refer  to  these  constraints  as 
"space-partition  constraints."  Any  mapping  t h at  satisfies  these  constraints  cre 
ates  partitions  t h at  are  independent  of  one  another.  Note  t h at  such  constraints 
can  be  satisfied  by  p u t t i ng  all  the  operations  in  a  single  partition.  Unfortu 
nately,  t h at  "solution"  does  not  yield  any  parallelism.  Our  goal  is  to  create 

832 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

as  many  independent  partitions  as  possible  while  satisfying  the  space-partition 
constraints;  t h at  is,  operations  are  not  placed  on  the  same  processor  unless  it 
is  necessary. 

When  we  restrict  ourselves  to  affine  partitions,  then  instead  of  maximizing 
the  number  of  independent  units,  we  may  maximize  the  degree  (number  of 
dimensions)  of parallelism.  It  is  sometimes  possible  to  create  more  independent 
units  if  we  can  use  piecewise  affine  partitions.  A  piecewise  affine  partition 
divides  instances  of  a  single  access  into, different  sets  and  allows  a  different 
affine  partition  for  each  set.  However,  we  shall  not  consider  such  an  option 
here. 

Formally,  an  affine  partition  of  a  program  is  synchronization  free  if  and  only 
if  for  every  two  (not  necessarily  distinct)  accesses  sharing  a  dependence,  T\  = 
( F i , f i , B i , b i)  in  statement  s\  nested  in  d\  loops,  and  T2  =  ( F2,f y ,B2,b2)  in 
statement  s2  nested  in  d2  loops,  the  partitions  ( C i , c i)  and  ( C2, c2)  for  state 
ments  si  and  s2,  respectively,  satisfy  the  following  space-partition  constraints: 

•  For  all  ii  in  Zdl  and  i2  in  Zd2  such  t h at 

a)  B i ii  4- bi  >  0, 

b)  B2i2  +  b2  >  0,  and 

c)  F i ii  + fi  =  F2i2  +  f2, 

it  is  t he  case  t h at  C i ii  +  ci  =  C2i2  +  c2. 

T he  goal  of  the  parallelization  algorithm  is  to  find,  for  each  statement,  t he 
partition  with  the  highest  rank  t h at  satisfies  these  constraints. 

Shown  in  Fig.  11.25  is  a  diagram  illustrating  the  essence  of  t he  space-
partition  constraints.  Suppose  there  are  two  static  accesses  in  two  loop  nests 
with  index  vectors  ii  and  i2.  These  accesses  are  dependent  in  the  sense  t h at 
they  access  at  least  one  array  element  in  common,  and  at  least  one  of t h em  is  a 
write.  T he  figure  shows  particular  dynamic  accesses  in  the  two  loops  t h at  hap 
pen  to  access  the  same  array  element,  according  to  the  affine  access  functions 
F i ii  + fi  and  F2i2  + f2.  Synchronization  is  necessary  unless  t he  affine  partitions 
for  the  two  static  accesses,  C i ii  + ci  and  C2i2  + c2,  assign  t he  dynamic  accesses 
to  the  same  processor. 

If  we  choose  an  affine  partition  whose  rank  is  the  maximum  of the  ranks  of 
all  statements,  we  get  t he  maximum  possible  parallelism.  However,  under  this 
partitioning  some  processors  may  be  idle  at  times,  while  other  processors  are 
executing  statements  whose  affine  partitions  have  a  smaller  rank.  This  situation 
may  be  acceptable  if  t he  time  taken  to  execute  those  statements  is  relatively 
short.  Otherwise,  we  can  choose  an  affine  partition  whose  rank  is  smaller  t h an 
the  maximum  possible,  as  long  as  t h at  rank  is  greater  t h an  0. 

We  show  in  Example  11.41  a  small  program  designed  to  illustrate  the  power 
of  the  technique.  Real  applications  are  usually  much  simpler  t h an  this,  but 
may  have  boundary  conditions  resembling  some  of  t he  issues  shown  here.  We 
shall  use  this  example  throughout  this  chapter  to  illustrate  t h at  programs  with 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

833 

•  •  •  •  • 

i  • • • K] • 
•  • • n
\] 
•  •  •  •  • 

Loops 

2 

• 
• B CD 
•  •  •  • 

•  • • • • 
•  •  •  •  • 
•  •  • 
D •  • •  • 
•  • • •  • 
•  •  • • • 

Array 

•  •  • 

Processor  ID 

Figure 11.25:  Space-partition constraints 

affine  accesses  have  relatively  simple  space-partition  constraints,  t h at  these  con 
straints  can  be  solved  using  standard  linear  algebra  techniques,  and  t h at  t he 
desired  SPMD  program  can  be  generated  mechanically  from  t he  affine  parti 
tions. 

E x a m p le  1 1 . 4 1:  This  example  shows  how  we  formulate  the  space-partition 
constraints  for  the  program  consisting  of  the  small  loop  nest  with  two  state 
ments,  si  and  s2,  shown  in  Figure 11.26. 

for  (i  =  1;  i  <=  100;  i++) 

for  (j  =  1;  j  <=  100;  j++)  { 

X[i,j]  = X[i,j]  + Y[i-l,j];  /*  (si)  */ 

Y[i,j]  = Y[i,j]  + X[i,j-1];  /*  (s2)  */ 

} 

Figure 11.26:  A  loop  nest  exhibiting  long  chains  of  dependent  operations 

We show the  d a ta dependences  in  the program in  Figure 1L27.  T h at  is,  each 
black  dot  represents  an  instance  of  statement  Si,  and  each  white  dot  represents 
an instance of statement S
instance  of  the  statement  t h at  is  executed  for  those  values  of  t he  loop  indexes. 
Note,  however,  t h at  the  instance  of  s2  is  located  just  below  t he  instance  of  «i 
pair,  so  the  vertical  scale  of j  is  greater  t h an  the  horizontal 
for  the  same 
scale  of  i. 

2. T he dot located at coordinates (i, j) represents the 

Notice  t h at  X[i,j]  is  written  by  si  (i, j),  t h at  is,  by  t he  instance  of  statement 
It  is  later  read  by  s2(i,j + 1),  so  si(i,j)  must 

si  with  index  values  i  and  j. 

834 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

1 

2 

3 

4 

5 

6 

Figure  11.27:  Dependences  of  the  code  in  Example  11.41 

precede  s2(i,j  +  1).  This  observation  explains  the  vertical  arrows  from  black 
dots  to  white  dots.  Similarly,  Y[i,j]  is  written  by  s2(i,j)  and  later  read  by 
s\(i  +  1,  j).  Thus,  s2(i,j)  must  precede  si(i  +  l,j),  which  explains  the  arrows 
from  white  dots  to  black. 

It  is  easy  to  see  from  this  diagram  t h at  this  code  can  be  parallelized  without 
synchronization  by  assigning  each  chain  of  dependent  operations  to  the  same 
processor.  However,  it  is  not  easy  to  write  t he  S P MD  program  t h at  implements 
this  mapping  scheme.  While  the  loops  in  t he  original  program  have  100  itera 
tions  each,  there  are  200  chains,  with  half originating  and  ending  with  statement 
si  and  the  other  half  originating  and  ending  with  s2.  T he  lengths  of  the  chains 
vary  from  1  to  100  iterations. 

Since  there  are  two  statements,  we  are  seeking  two  affine  partitions,  one  for 
each  statement.  We  only  need  to  express  the  space-partition  constraints  for 
one-dimensional  affine  partitions.  These  constraints  will  be  used  later  by  the 
solution  method  t h at  tries  to  find  all  t he  independent  one-dimensional  affine 
partitions  and  combine  t h em  to  get  multidimensional  affine  partitions.  We  can 
thus  represent  t he  affine  partition  for  each  statement  by  a  1 x 2  matrix  and  a  1  x 1 
vector  to  translate  the  vector  of  indexes 
into  a  single  processor  number. 
Let  ([C11C12],  [ci]),  ([C2iC22],  [c2]),  be  t he  one-dimensional  affine  partitions  for 
the  statements  s1  and  s2,  respectively. 

We  apply  six  d a ta  dependence  tests: 

1.  Write  access  X[i,j]  and  itself  in  statement  s i, 

2.  Write  access  X[i,j]  with  read  access  X[i,  j]  in  statement  si, 

3.  Write  access  X[i,j]  in  statement  si  with  read  access  X[i,j  —  1]  in  state 

ment  82, 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

835 

4.  Write  access  ^ [ i, j]  and  itself  in  statement  s2, 

5.  Write  access  Y[i,j]  with  read  access  Y[i,j]  in  statement  s2, 

6.  Write  access  Y[i,  j]  in  statement  s2  with  read  access  Y[i — l,j]  in  statement 

s i. 

We  see  t h at  t he  dependence  tests  are  all  simple  and  highly  repetitive.  T he  only 
dependences  present  in  this  code  occur  in  case  (3)  between  instances  of  accesses 

j]  and  X[i,j  —  1]  and  in  case  (6)  between  Y[i,j]  and  Y[i  —  1, j ]. 
The  space-partition  constraints  imposed  by  the  d a ta  dependence  between 
X[i,j]  in  statement  si  and  X[i,j  —  1]  in  statement  s2  can  be  expressed  in  the 
following  terms: 

For  all 

and 

such  t h at 

1  <  i  <  100 
1  <  i'  <  100 
i  =  i' 

1  <  j  <  100 
1  <  j'  <  100 

we  have 

Cn 

C 12 

+  [  ci 1  =  [  C2l 

C22  1 

*./ 

+  [  c2 

L 

J 

L 

J 

n 

L 

J 

lie  within  the  itera 
T h at  is,  the  first  four  conditions  say  t h at  (i,j)  and 
tion  space  of  the  loop  nest,  and  the  last  two  conditions  say  t h at  t he  dynamic 
accesses  X[i, j]  and  X[i,j  —  1]  touch  the  same  array  element.  We  can  derive 
t he  space-partition  constraint  for  accesses  Y[i  — 
in  statement  s2  and  Y[i, j] 
in  statement  si  in  a  similar  manner. 

• 

11.7.4 

Solving  Space-Partition  Constraints 

Once  the  space-partition  constraints  have  been  extracted,  s t a n d a rd  linear  alge 
bra techniques  can  be  used  to  find  the  affine  partitions  satisfying  t he  constraints. 
Let  us  first  show  how  we  find  the  solution  to  Example  11.41. 

E x a m p le  1 1 . 42  :  We  can  find  t he  affine  partitions  for  Example  11.41  with  t he 
following  steps: 

1.  Create  t he  space-partition  constraints  shown  in  Example  11.41.  We  use 
the  loop  bounds  in  determining  t he  d a ta  dependences,  but  they  are  not 
used  in  the  rest  of  the  algorithm  otherwise. 

2.  T he  unknown  variables  in  the  equalities  are  i,  i',  j,  j ',  C n,  C 1 2,  ci,  C2i, 

2. Reduce t he number of unknowns by using the equalities due 

C 2 2, and C
to  the  access  functions:  i  —  i'  and  j  —  j'  —  1.  We  do  so  using  Gaussian 
elimination,  which  reduces  the  four  variables  to  two:  say  t\  —%  —  %',  and 
t2  =  j  +  1  =  j '.  T he  equality  for  the  partition  becomes 

[  Cn  —  C 21 

C 12  —  C 22 

] 

+  [  ci  -  c2  -  C 22  ]  =  0. 

t2 

836  CHAPTER 

11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

3.  T he  equation  above  holds  for  all  combinations  of t\  and  t2-  Thus,  it  must 

be  t h at 

Cn  —  C2\  — 
= 
C\2  —  C22 
= 
ci  -  c2  -  C22 

0 
0 
0. 

If  we  perform  t he  same  steps  on  the  constraint  between  t he  accesses 
Y[i  —  l,j]  and  Y[i,j],  we  get 

Cn  —  C21 
= 
C\2  ~  C22  — 

ci  -  c2  +  C2i 

= 

0 
0 
0. 

Simplifying  all  the  constraints  together,  we  obtain  the  following  relation 
ships: 

Cn  =  C21  =  —  C\ 22 

•C\2  —  C2 

-  C i. 

4.  Find  all  the  independent  solutions  to  the  equations  involving  only  un 
knowns  in  the  coefficient  matrix,  ignoring  t he  unknowns  in  the  constant 
vectors  in  this  step.  There  is  only  one  independent  choice  in  t he  coef 
ficient  matrix,  so  t he  affine  partitions  we  seek  can  have  at  most  a  rank 
of  one.  We  keep  the  partition  as  simple  as  possible  by  setting  Cn  — 1. 
We  cannot  assign  0  to  C\\  because  t h at  will  create  a  rank-0  coefficient 
matrix,  which  maps  all  iterations  to  the  same  processor.  It  then  follows 
t h at  C2i = 1,  C22  = - 1,  C12  = - 1. 

5.  Find  t he  constant  terms.  We  know  t h at  t he  difference  between  t he  con 
stant  terms,  c2  —  ci,  must  be — 1.  We  get  to  pick  the  actual  values, 
however.  To  keep  t he  partitions  simple,  we  pick  c2  =  0;  thus  ci  = — 1. 

Let  p  be  t he  ID  of t he  processor  executing  iteration 

In  terms  of p,  t he 

affine  partition  is 

si  :  [  p  ]  =  [ 1  -1 

+ [  - 1; 

8>:[p] = [l - 1] j + [ 0] 

T h at  is,  the  (i,j)th  iteration  of  si  is  assigned  to  the  processor  p  =  i  —  j  — 1, 
and  the  (i,j)th  iteration  of  s2  is  assigned  to  processor  p  —  %  —  j. 

• 

A l g o r i t hm  1 1. 4 3:  Finding  a  highest-ranked  synchronization-free  affine  par 
tition  for  a  program. 

I N P U T:  A  program  with  affine  array  accesses. 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

837 

O U T P U T:  A  partition. 

M E T H O D:  Do  the  following: 

1.  Find  all  data-dependent  pairs  of  accesses  in  a  program  for  each  pair  of 
data-dependent  accesses,  T\  —  ( F i , f i , B i , b i)  in  statement  s\  nested  in 
di  loops  and  T2  =  ( F 2 , f 2 , B2, b2)  in  statement  s2  nested  in  d2  loops. 
Let  ( C i , c i)  and  ( C2, c2)  represent  t he  (currently  unknown)  partitions  of 
statements  s\  and  s2,  respectively.  T he  space-partition  constraints  state 
t h at  if 

then 

F i ii  +  fi  —  F2i2  +  f2 

C i ii  +  ci  =  C2i2  +  c2 

for  all  ii  and  i2,  within  their  respective  loop  bounds.  We  shall  generalize 
t he  domain  of  iterations  to  include  all  ii  in  Zdl  and  i2  in  Zd2;  t h at  is,  the 
bounds  are  all  assumed  to  be  minus  infinity  to  infinity.  This  assumption 
makes  sense,  since  an  affine  partition  cannot  make  use  of the  fact  t h at  an 
index  variable  can  take  on  only  a  limited  set  of  integer  values. 

2.  For  each  pair  of  dependent  accesses,  we  reduce  the  number  of  unknowns 

in  the  index  vectors. 

(a)  Note  t h at  Fi  +  f  is  t he  same  vector  as 

F 

f 

T h at  is,  by  adding  an  extra  component  1  at  the  b o t t om  of  column-
vector  i,  we  can  make  t he  column-vector  f  be  an  additional,  last 
column  of  the  matrix  F.  We  may  thus  rewrite  t he  equality  of  t he 
access  functions  F i ii  +  f\  =  F2i2  +  f2  as 

[  Fi 

- f2 

(fi  -  f2); 

=  0. 

(b)  The  above  equations  will  in  general  have  more  t h an  one  solution. 
However,  we  may  still  use  Gaussian  elimination  to  solve  the  equations 
for  the  components  of ix  and  i2  as  best  we  can.  T h at  is,  eliminate  as 
many  variables  as  possible  until  we  are  left  with  only  variables  t h at 
cannot  be  eliminated.  The  resulting  solution  for  i2  and  i2  will  have 
the  form 

838  CHAPTER 

11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

where  U  is  an  upper-triangular  matrix  and  t  is  a  vector  of free  vari 
ables  ranging  over  all  integers. 

(c)  We  may  use  t he  same  trick  as  in  Step  (2a)  to  rewrite  the  equality  of 
the  partitions.  Substituting  the  vector  (ii,  i2,1)  with  t he  result  from 
Step  (2b),  we  can  write  the  constraints  on  the  partitions  as 

;  Ci  - C2 

(ci - c2)  ] U 

=  0. 

3.  Drop  t he  nonpartition  variables.  The  equations  above  hold  for  all  combi 

nations  of  t  if 

[  Ci 

- C2 

(ci  -  c2)  ]  U  =  0. 

Rewrite  these  equations  in  the  form  Ax  =  0,  where  x  is  a  vector  of  all 
the  unknown  coefficients  of  the  affine  partitions. 

4.  Find  t he  rank  of the  affine  partition  and  solve  for  the  coefficient  matrices. 
Since  t he  rank  of  an  affine  partition  is  independent  of  t he  value  of  the 
constant  terms  in  the  partition,  we  eliminate  all  t he  unknowns  t h at  come 
from  the  constant  vectors  like  ci  or  c2,  thus  replacing  Ax  =  0  by  sim 
plified  constraints  A'x'  =  0.  Find  t he  solutions  to  A ' x'  =  0,  expressing 
t h em  as  B,  a  set  of  basis  vectors  spanning  the  null  space  of  A'. 

5.  Find  the  constant  terms.  Derive  one  row  of  the  desired  affine  partition 
from  each  basis  vector  in  B,  and  derive  t he  constant  terms  using  Ax  =  0. 

Note  t h at  Step  3  ignores  the  constraints  imposed  by  the  loop  bounds  on 
variables  t.  T he  constraints  are  only  stricter  as  a  result,  and  t he  algorithm  must 
therefore  be  safe.  T h at  is,  we  place  constraints  on  t he  C 's  and c's  assuming 
t  is  arbitrary.  Conceivably,  there  would  be  other  solutions  for  the  C's  and c's 
t h at  are  valid  only  because  some  values  of  t  are  impossible.  Not  searching  for 
these  other  solutions  m ay  cause  us  to  miss  an  optimization,  b ut  cannot  cause 
the  program  to  be  changed  to  a  program  t h at  does  something  different  from 
what  the  original  program  does. 

11.7.5  A  Simple  Code-Generation  Algorithm 

Algorithm  11.43  generates  affine  partitions  t h at  split  computations  into  inde 
pendent  partitions.  Partitions  can  be  assigned  arbitrarily  to  different  proces 
sors,  since  they  are  independent  of  one  another.  A  processor  may  be  assigned 
more  t h an  one  partition  and  can  interleave  the  execution  of  its  partitions,  as 
long  as  operations  within  each  partition,  which  normally  have  d a ta  dependences, 
are  executed  sequentially. 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

839 

It  is  relatively  easy  to  generate  a  correct  program  given  an  affine  partition. 
We  first  introduce  Algorithm 11.45,  a  simple  approach  to  generating  code  for  a 
single  processor  t h at  executes  each  of  the  independent  partitions  sequentially. 
Such  code  optimizes  temporal  locality,  since  array  accesses  t h at  have  several 
uses  are  very  close  in  time.  Moreover,  the  code  easily  can  be  turned  into  an 
S P MD  program  t h at  executes  each  partition  on  a  different  processor.  T he  code 
generated  is,  unfortunately,  inefficient;  we  shall  next  discuss  optimizations  to 
make  the  code  execute  efficiently. 

The  essential  idea  is  as  follows.  We  are  given  bounds  for  t he  index  variables 
of a  loop  nest,  and  we  have  determined,  in  Algorithm 11.43,  a  partition  for  t he 
accesses  of  a  particular  statement  s.  Suppose  we  wish  to  generate  sequential 
code  t h at  performs  the  action  of  each  processor  sequentially.  We  create  an 
outermost  loop  t h at  iterates  through  t he  processor  IDs.  T h at  is,  each  iteration 
of  this  loop  performs  the  operations  assigned  to  a  particular  processor  ID.  T he 
original  program  is  inserted  as  t he  loop  body  of  this  loop;  in  addition,  a  test 
is  added  to  guard  each  operation  in  t he  code  to  ensure  t h at  each  processor 
only  executes  the  operations  assigned  to  it.  In  this  way,  we  guarantee  t h at  the 
processor  executes  all  t he  instructions  assigned  to  it,  and  does  so  in  t he  original 
sequential  order. 

E x a m p le 11.44:  Let  us  generate  code  t h at  executes  the  independent  parti 
tions  in  Example 11.41  sequentially.  The  original  sequential  program  is  from 
Fig. 11.26  is  repeated  here  as  Fig. 11.28. 

for  (i =  1;  i  <=  100;  i++) 

for  (j  =  1;  j  <=  100; 

{ 

X[i,jJ  = X[i,j]  + Y[i-l,j];  /*  (si)  */ 

Y[i,j3  = Y[i,j]  + X[i,j-1];  /*  (s2)  */ 

} 

Figure 11.28:  Repeat  of Fig. 11.26 

In  Example 11.41,  the  affine  partitioning  algorithm  found  one  degree  of 
parallelism.  Thus,  the  processor  space  can  be  represented  by  a  single  variable 
p.  Recall  also  from  t h at  example  t h at  we  selected  an  affine  partition  t h a t,  for 
all  values  of index  variables  i  and j  with 1 <  i  < 100  and 1 <  j  < 100,  assigned 

1.  Instance  (i, j)  of  statement  si  to  processor  p  =  i  -  j - 1,  and 

2.  Instance 

of  statement  s2  to  processor  p  —  %—  j. 

We  can  generate  the  code  in  three  steps: 

1.  For  each  statement,  find  all  the  processor  IDs  participating  in  the  com 

putation.  We  combine  the  constraints 1 <  i  < 100  and  1  <  j  < 100  with 
one  of  t he  equations  p  =  i  -  j - 1  or  p  =  i  -  j,  and  project  away  i  and  j 
to  get  the  new  constraints 

840 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

(a)  - 1 00  <  p  <  98  if  we  use  the  function  p  =  i  —  j  —  1  t h at  we  get  for 

statement  s i,  and 

(b)  —99  <  p  <  99  if  we  use  p  =  i  —  j  from  statement  s2. 

2.  Find  all  t he  processor  IDs  participating  in  any  of  the  statements.  When 
we  take  the  union  of  these  ranges,  we  get  - 1 00  <  p  <  99;  these  bounds 
are  sufficient  to  cover  all  instances  of  b o th  statements  si  and  s2. 

3.  Generate  the  code  to  iterate  through  the  computations  in  each  partition 
sequentially.  The  code,  shown in  Fig.  11.29,  has  an  outer loop  t h at  iterates 
through  all  the  partition  IDs  participating  in  the  computation  (line  (1)). 
Each  partition  goes  through  the  motion  of  generating  the  indexes  of  all 
the  iterations  in  t he  original  sequential  program  in  lines  (2)  and  (3)  so 
t h at  it  can  pick  out  the  iterations  the  processor  p  is  supposed  to  execute. 
The  tests  of  lines  (4)  and  (6)  make  sure  t h at  statements  s\  and  s2  are 
executed  only  when  the  processor  p  would  execute  them. 

T he  generated  code,  while  correct,  is  extremely  inefficient. 

First,  even 
though  each  processor  executes  computation  from  at  most  99  iterations,  it  gen 
erates  loop  indexes  for  100  x  100  iterations,  an  order  of  magnitude  more  t h an 
necessary.  Second,  each  addition  in  t he  innermost  loop  is  guarded  by  a  test, 
creating  another  constant  factor  of  overhead.  These  two  kinds  of  inefficiencies 
are  dealt  with  in  Sections  11.7.6  and  11.7.7,  respectively. 

• 

1) 

2) 

3) 

4) 
5) 

6) 
7) 

8) 

for  (p =  -100;  p  <= 99;  p++) 

for  (i =  1;  i  <=  100;  i++) 

for  (j  =  1;  j  <=  100;  j++)  { 

if  (p  ==  i - j -D 

X [ i5j]  = X[i,j]  + Y[i-l,j];  /*  (si)  */ 

if  (p  ==  i-j) 

Y[i,j]  = X[i,j-1]  + Y[i,j];  /*  (s2)  */ 

} 

Figure  11.29:  A  simple  rewriting  of Fig.  11.28  t h at  iterates  over  processor  space 

Although  the  code  of  Fig.  11.29  appears  designed  to  execute  on  a  unipro 
cessor,  we  could  take  t he  inner  loops,  lines  (2)  through  (8),  and  execute  t h em 
on  200  different  processors,  each  of  which  had  a  different  value  for p,  from  —100 
to  99.  Or,  we  could  partition  the  responsibility  for  t he  inner  loops  among  any 
number  of  processors  less  t h an  200,  as  long  as  we  arranged  t h at  each  processor 
knew  what  values  of p  it  was  responsible  for  and  executed  lines  (2)  through  (8) 
for  just  those  values  of p. 

A l g o r i t hm  1 1 . 4 5:  Generating  code  t h at  executes  partitions  of  a  program 
sequentially. 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

841 

I N P U T:  A  program  P  with  affine  array  accesses.  Each  statement  s  in  the 
program  has  associated  bounds  of  the  form  Bsi  +  bs  >  0,  where  i  is  the  vector 
of loop  indexes  for  t he  loop  nest  in  which  statement  s  appears.  Also  associated 
with  statement  s  is  a  partition  C5i + cs  =  p  where  p  is  an  m-dimensional  vector 
of variables  representing  a  processor  ID;  m  is  t he  maximum,  over  all  statements 
in  program  P,  of  t he  rank  of  t he  partition  for  t h at  statement. 

O U T P U T:  A  program  equivalent  to  P  but  iterating  over  the  processor  space 
rather  t h an  over  loop  indexes. 

M E T H O D:  Do  the  following: 

1.  For  each  statement,  use  Fourier-Motzkin  elimination  to  project  out  all  the 

loop  index  variables  from  the  bounds. 

2.  Use  Algorithm  11.13  to  determine  bounds  on  the  partition  ID's. 

3.  Generate  loops,  one  for  each  of  the  m  dimensions  of  processor  space.  Let 
p  =  [ p i , P 2 , --  -  ,Pm]  be  the  vector  of  variables  for  these  loops;  t h at  is, 
there  is  one  variable  for  each  dimension  of the  processor  space.  Each  loop 
variable pi  ranges  over  t he  union  of the  partition  spaces  for  all  statements 
in  t he  program  P. 

Note  t h at  the  union  of  the  partition  spaces  is  not  necessarily  convex.  To 
keep  the  algorithm  simple,  instead  of  enumerating  only  those  partitions  t h at 
have  a  nonempty  computation  to  perform,  set  the  lower  bound  of  each  pi  to 
the  minimum  of  all  the  lower  bounds  imposed  by  all  statements  and  the  upper 
bound  of  each  pi  to  the  maximum  of  all  the  upper  bounds  imposed  by  all 
statements.  Some  values  of  p  may  thereby  have  no  operations. 

T he  code  to  be  executed  by  each  partition  is  the  original  sequential  pro 
gram.  However,  every  statement  is  guarded  by  a  predicate  so  t h at  only  those 
operations  belonging  to  t he  partition  are  executed. 

• 

An  example  of  Algorithm  11.45  will  follow  shortly.  Bear  in  mind,  however, 

t h at  we  are  still  far  from  the  optimal  code  for  typical  examples. 

11.7.6  Eliminating  Empty  Iterations 

We  now  discuss  the  first  of  the  two  transformations  necessary  to  generate  ef 
ficient  S P MD  code.  T he  code  executed  by  each  processor  cycles  through  all 
t he  iterations  in  t he  original  program  and  picks  out  the  operations  t h at  it  is 
supposed  to  execute.  If  t he  code  has  k  degrees  of  parallelism,  the  effect  is  t h at 
each  processor  performs  k  orders  of  magnitude  more  work.  T he  purpose  of  the 
first  transformation  is  to  tighten  t he  bounds  of  the  loops  to  eliminate  all  the 
empty  iterations. 

We  begin  by  considering  the  statements  in  the  program  one  at  a  time.  A 
statement's  iteration  space  to  be  executed  by  each  partition  is  t he  original  itera 
tion  space  plus  the  constraint  imposed  by  the  affine  partition.  We  can  generate 

842 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

tight  bounds  for  each  statement  by  applying  Algorithm  11.13  to  t he  new  iter 
ation  space;  the  new  index  vector  is  like  the  original  sequential  index  vector, 
with  processor  ID's  added  as  outermost  indexes.  Recall  t h at  the  algorithm  will 
generate  tight  bounds  for  each  index  in  terms  of  surrounding  loop  indexes. 

After  finding  t he  iteration  spaces  of  t he  different  statements,  we  combine 
them,  loop  by  loop,  making  the  bounds  the  union  of  those  for  each  statement. 
Some  loops  end  up  having  a  single  iteration,  as  illustrated  by  Example  11.46 
below,  and  we  can  simply  eliminate  the  loop  and  simply  set  t he  loop  index  to 
t he  value  for  t h at  iteration. 

E x a m p le  1 1 . 4 6:  For  t he  loop  of  Fig.  11.30(a),  Algorithm  11.43  will  create 
the  affine  partition 

S\  : p  = i 
j 
s2:p  = 

Algorithm  11.45  will  create  the  code  of Fig.  11.30(b).  Applying  Algorithm  11.13 
to  statement  s\  produces  t he  bound:  p  <  i  <  p,  or  simply  %  =  p.  Similarly, 
the  algorithm  determines  j  =  p  for  statement  s2-  Thus,  we  get  t he  code  of 
Fig.  11.30(c).  Copy  propagation  of  variables  i  and  j  will  eliminate  the  unnec 
essary  test  and  produce  the  code  of  Fig.  11.30(d). 

• 

We  now  return  to  Example  11.44  and  illustrate  t he  step  to  merge  multiple 

iteration  spaces  from  different  statements  together. 

E x a m p le  1 1 * 4 7:  Let  us  now  tighten  the  loop  bounds  of  t he  code  in  Exam 
ple  11.44.  The  iteration  space  executed  by  partition p  for  statement  si  is  defined 
by  the  following  equalities  and  inequalities: 

- 1 00  < 
1  < 
< 
1 

p  < 
i  < 
j  < 

99 
100 
100 

i  -  p  -  1  =  j 

Applying  Algorithm  11.13  to  the  above  creates  the  constraints  shown  in  Fig. 
11.31(a).  Algorithm  11.13  generates  t he  constraint  p  +  2  <  i  <  100  + p  +  1 
from  i  —  p  -  1  =  j  and  1  <  j  <  100,  and  tightens  t he  upper  bound  of p  to  98. 
Likewise,  the  bounds  for  each  of  the  variables  for  statement  s2  are  shown  in 
Fig.  11.31(b). 

The  iteration  spaces  for  si  and  s2  in  Fig.  11.31  are  similar,  but  as  ex 
pected  from  Fig.  11.27,  certain  limits  differ  by  1  between  the  two.  T he  code  in 
Fig.  11.32  executes  over  this  union  of  iteration  spaces.  For  example,  for  i  use 
min(l,£>+1)  as  the  lower  bound  and  m a x ( 1 0 0 , 1 0 0+ p + 1)  as  t he  upper  bound. 
Note  t h at  t he  innermost  loop  has  2  iterations  except  t h at  it  has  only  one  t he 
first  and  last  time  it  is  executed.  The  overhead  in  generating  loop  indexes  is 
thus  reduced  by  an  order  of  magnitude.  Since  the  iteration  space  executed  is 
larger  t h an  either  t h at  of  si  and  s2,  conditionals  are  still  necessary  to  select 
when  these  statements  are  executed. 

• 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

for  (i=l;  i<=N;  i++) 

Y[i]  = Z [ i ];  /*  (si)  */ 

for  (j=l;  j<=N;  j++) 

X[j]  = Y [ j ];  /*  (s2)  */ 

(a)  Initial  code. 

for  (p=l;  p<=N;  p++)  { 

for  (i=l;  i<=N;  i++) 

if  (p  ==  i) 

Y[i]  = Z[i] ;  /*  (si)  */ 

for  (j=l;  j<=N;  j++) 

if  (p  ==  j) 

X[j]  = Y [ j ];  /*  (s2)  */ 

} 

(b)  Result  of  applying  Algorithm  11.45. 

for  (p=l;  p<=N;  p++)  { 

i  = p; 

if  (p  ==  i) 

Y[i]  = Z[i] ;  /*  (si)  */ 

j  = p; 
if  (p  ==  j) 

X[j]  = Y [ j ];  /*  (s2)  */ 

(c)  After  applying  Algorithm  11.13. 

for  (p=l;  p<=N;  p++)  { 

Y[p]  = Z[p];  /*  (si)  */ 
X[p]  = Y[p] ;  /*  (s2)  */ 

} 

(d)  Final  code. 

Figure  11.30:  Code  for  Example  11.46 

844 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

3  • 

i  : 

i — p — 1  <  3  < 
3  < 
1  < 

i - p -1 
100 

p +  2  < 
1  < 

i  < 
i  < 

100  +  ^ +1 
100 

P  : 

- 1 00  <  P  <  98 

(a)  Bounds  for  statement  s±. 

3  • 

i  — p  <  3  < 

i  — p 

1  <  3  <  100 

i  :  p+1 

< 
1  < 

i  <  100  +p 
i  <  100 

p: 

- 99  <  P  <  99 

(b)  Bounds  for  statement  s2. 

Figure  11.31:  Tighter  bounds  on  p,  i,  and  j  for  Fig.  11.29 

11.7.7  Eliminating  Tests  from  Innermost  Loops 

T he  second  transformation  is  to  remove  conditional  tests  from  the  inner  loops. 
As  seen  from  t he  examples  above,  conditional  tests  remain  if the  iteration  spaces 
of  statements  in  t he  loop  intersect  b ut  not  completely.  To  avoid  t he  need  for 
conditional  tests,  we  split  the  iteration  space  into  subspaces,  each  of  which 
executes  the  same  set  of  statements.  This  optimization  requires  code  to  be 
duplicated  and  should  only  be  used  to  remove  conditionals  in  t he  inner  loops. 
To  split  an  iteration  space  to  reduce  tests  in  inner  loops,  we  apply  the 

following  steps  repeatedly  until  we  remove  all  t he  tests  in  t he  inner  loops: 

1.  Select  a  loop  t h at  consists  of  statements  with  different  bounds. 

2.  Split  the  loop  using  a  condition  such  t h at  some  statement  is  excluded 
from  at  least  one  of its  components.  We  choose  the  condition  from  among 
the  boundaries  of  the  overlapping  different  polyhedra.  If  some  statement 
has  all  its  iterations  in  only  one  of  the  half  planes  of  the  condition,  then 
such  a  condition  is  useful. 

3.  Generate  code  for  each  of  these  iteration  spaces  separately. 

E x a m p le  1 1. 4 8:  Let  us  remove  t he  conditionals  from  t he  code  of  Fig.  11.32. 
Statements  si  and  52  are  mapped  to  t he  same  set  of  partition  ID's  except  for 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

845 

f or  (p  =  -100;  p  <=  99;  p++) 
f or  (i  =  m a x ( l , p + l ); 

i  <=  minQOO, 101+p); 

i++) 

(j  =  m a x ( l , i - p- 1 ); 
if 

i - j- 1) 

(p  == 

j  <=  m i n( 1 0 0, i - p ); 

j++)  { 

X[ i , j]  =  X[ i , j3  +  Y[ i - l , j ]; 

/* 

( s i)  */ 

if 

(p  == 

i - j) 

Y[ i , j]  =  X[ i , j- 1]  +  Y[ i , j ]; 

/* 

( s 2)  */ 

f or 

} 

Figure 11.32:  Code  of Fig. 11.29  improved  by  tighter  loop  bounds 

t he  boundary  partitions  at  either  end.  Thus,  we  separate  the  partition  space 
into  three  subspaces: 

1.  p  = -100, 

2. - 99 <  p < 98,  and 

3.  p  = 99. 

T he  code  for  each  subspace  can  then  be  specialized  for  the  value(s)  of  p 
contained.  Figure 11.33  shows  t he  resulting  code  for  each  of  the  three  iteration 
spaces. 

Notice  t h at  the  first  and  third  spaces  do  not  need  loops  on  i  or  j,  because 
for  the  particular  value  of p  t h at  defines  each  space,  these  loops  are  degenerate; 
they  have  only  one  iteration.  For  example,  in  space (1),  substituting  p = —100 
in  the  loop  bounds  restricts  i  to 1,  and  subsequently j  to 100.  T he  assignments 
to  p  in  spaces (1)  and (3)  are  evidently  dead  code  and  can  be  eliminated. 

Next  we  split  t he  loop  with  index  i  in  space (2).  Again,  the  first  and  last 
iterations  of  loop  index  i  are  different.  Thus,  we  split  t he  loop  into  three 
subspaces: 

a)  m a x ( l ,p + 1) <  i  <  p + 2,  where  only  s2  is  executed, 

b)  m a x ( l ,p + 2) <  i  <  min(100,100+p),  where  b o th  g\  and  s2  are  executed, 

and 

c)  1 0 1+p  <  i  <  min(101  +p, 100),  where  only  si  is  executed. 

T he  loop  nest  for  space (2)  in  Fig. 11.33 can thus  be  written  as  in  Fig. 11.34(a). 
Figure 11.34(b)  shows  the  optimized  program.  We  have  substituted  Fig. 
11.34(a)  for  t he  loop  nest  in  Fig. 11.33.  We  also  propagated  out  assignments  to 
p,  i,  and  j  into  the  array  accesses.  W h en  optimizing  at  the  intermediate-code 
level,  some  of  these  assignments  will  be  identified  as  common  subexpressions 
and  re-extracted  from  the  array-access  code. 

• 

846 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

(1)  */ 

/*  s p a ce 
p  =  - 1 0 0; 
i  =  1; 
j  =  100; 
X [ i , j]  =  X [ i , j]  +  Y [ i - l , j ]; 

/* 

( s i)  */ 

(2)  */ 

/*  s p a ce 
f or  (p  =  - 9 9;  p  <=  9 8;  p++) 
f or  (i  —  m a x ( l , p + l ); 

i  <=  m i n ( 1 0 0 , 1 0 1 + p ); 

i++) 

f or  (j  =  m a x ( l , i - p - l ); 

j  <=  m i n ( 1 0 0 , i - p ); 

j + +)  { 

if 

(p  == 

i - j - i) 

X [ i , j]  =  X [ i , j]  +  Y [ i - l , j ]; 

/* 

( s i)  */ 

if 

(p  == 

i - j) 

Y [ i , j]  =  X [ i , j - 1]  +  Y [ i , j ]; 

/* 

( s 2)  */ 

} 

(3)  */ 

/*  s p a ce 
p  =  9 9; 
i  =  100; 

j  =  i; 

Y [ i , j]  =  X [ i , j - 1]  +  Y [ i , j ]; 

/*  ( s 2)  */ 

Figure  11.33:  Splitting  the  iteration  space  on  t he  value  of p 

11.7.8 

Source-Code  Transforms 

We  have  seen  how  we  can  derive  from  simple  affine  partitions  for  each  statement 
programs  t h at  are  significantly  different  from  the  original  source. 
It  is  not 
apparent  from  t he  examples  seen  so  far  how  affine  partitions  correlate  with 
changes  at  the  source  level.  This  section  shows  t h at  we  can  reason  about  source 
code  changes  relatively  easily  by  breaking  down  affine  partitions  into  a  series 
of  primitive  transforms. 
S e v en  P r i m i t i ve Affine  T r a n s f o r ms 

Every  affine  partition  can  be  expressed  as  a  series  of primitive  affine  transforms, 
each  of  which  corresponds  to  a  simple  change  at  t he  source  level.  There  are 
seven  kinds  of  primitive  transforms:  t he  first  four  primitives  are  illustrated  in 
Fig.  11.35,  the  last  three,  also  known  as  unimodular  transforms,  are  illustrated 
in  Fig.  11.36. 

The  figure  shows  one  example  for  each  primitive:  a  source,  an  affine  parti 
tion,  and  the  resulting  code.  We  also  draw  the  d a ta  dependences  for  t he  code 
before  and  after  the  transforms.  From  the  d a ta  dependence  diagrams,  we  see 
t h at  each  primitive  corresponds  to  a  simple  geometric  transform  and  induces  a 
relatively  simple  code  transform.  T he  seven  primitives  are: 

11.7. 

FINDING  SYNCHRONIZATION-FREE  PARALLELISM 

847 

/*  s p a ce 
f or  (p  =  - 9 9;  p  <=  9 8;  p++)  { 

(2)  */ 

/*  s p a ce 
if 

(2a)  */ 

(p  >=  0)  { 
i  =  p + 1; 
J  =  U 
Y[ i , j]  = X[ i , j - 1]  + Y[ i , j ]; 

/*  ( s 2)  */ 

} 
/*  s p a ce 
f or  (i  =  m a x ( l , p + 2 ); 

(2b)  */ 

j  = i-p-i; 

i  <=  m i n ( 1 0 0 , 1 0 0 + p ); 

i++)  { 

X[ i , j]  = X[ i , j]  + Y[ i - l , j ]; 

/*  ( s i)  */ 

j  =  i-P5 
Y[i,j]  =  X[ i , j - 1]  +  Y[ i , j ]; 

/* 

( s 2)  */ 

} 
/*  s p a ce 
if 

(2c)  */ 

(p  <=  - 1)  { 
i  =  101+p; 
j  =  100; 
X[ i , j]  = X[ i , j]  + Y[ i - l , j ]; 

/*  ( s i)  */ 

} 

} 

(a)  Splitting  space  (2)  on  t he  value  of  i. 

/*  s p a ce  ( 1 );  p  =  - 1 00 
X[ 1 , 1 0 0]  = X [ l, 1 0 0]  + Y[ 0 , 1 0 0 ]; 

*/ 

/*  s p a ce 
f or  (p  =  - 9 9;  p  <=  9 8;  p++)  { 

(2)  */ 

if 

(p  >=  0) 

/* 

( s i)  */ 

f or 

} 
if 

Y[ p + l , l]  = X[ p + 1 , 0]  + Y[ p + l , l ]; 
(i  =  m a x ( l , p + 2 ); 
i  <=  m i n ( 1 0 0 , 1 0 0 + p ); 
X[ i , i - p - l]  = X[ i , i - p - l]  + Y[ i - l , i - p - l]  ; 
Y[ i , i - p]  = X[ i , i - p - l]  + Y[ i , i - p ]; 

i++)  { 

/* 

( s 2)  */ 

/* 
/* 

( s i)  */ 
( s 2)  */ 

(p  <=  - 1) 

X[ 1 0 1 + p , 1 0 0]  = X[ 1 0 1 + p , 1 0 0]  + Y[ 1 0 1 + p - l , 1 0 0 ]; 

/*  ( s i)  */ 

} 
/* 

s p a ce  ( 3 );  p  =  99 

*/ 

Y[ 1 0 0 , 1]  = X[ 1 0 0 , 0]  + Y[ 1 0 0 , l ]; 

/* 

(s2)  */ 

(b)  Optimized  code  equivalent  to  Fig.  11.28. 

Figure  11.34:  Code  for  Example  11.48 

848 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

SO U R CE  CO DE 

PA R T I T I ON 

TR A N S F O R M ED  CO DE 

for  (i=l;  i<=N;  i++) 

Y[i] = Z[i]; /*sl*/ 

for  (j=l;  j<=N;  j++) 

X[j]  =  Y [ j ];  /*s2*/ 

• 
©  ©  © 

t 

t 

t 

*2 

for  (p=l;  p<=M;  p++){ 

Y[p] = Z [ p ]; 

X[p] = Y [ p ]; 

} 

"  '  0 0  0 

'i 

S2 

for  (p=l;  p<=N;  p++){ 

Fusion 

s1:p  = 

i 

} 

S2-P  =  j 

Y[p] = Z [ p ]; 

X[p] = Y [ p ]; 

0  0  0  0  0  0 

si 

*2 

Fission 

si  :  i  =  p 

S2  •  j  = P 

for  (i=l;  i<=N;  i++) 

Y[i] = Z[i] ; /*sl*/ 

for  (j=l;  j<=N;  j++) 
X[j]  =  Y [ j ];  /*s2*/ 

- 

0  0  0  0  Q 

si 

t 

t 

t 

*2 

for  (i=l;  i<=N;  i++)  { 

Y[i]  = Z[i];  /*sl*/ 

X[i] = Y[i-1] ; /*s2*/ 

Re-indexing 

if (N>=1) X[1]=Y[0]; 
for  (p=i;  p<=N-l;  p++){ 

Y[p]=Z[p]; 

X[p+l]=Y[p]; 

} 

Q 

o 

*i 

S2 

si  :  p  =  i 
s2  :  p  =  i  - 1 

} 
if (N>=1) Y[N]=Z[N]; 

o  o  o  o  o  o 

S2 

for  (i=l;  i<=N;  i++) 

Y[2*i] = Z[2*i]; /*sl*/ 

for  (j=l;  j<=2N;  j++) 

X[j]=Y[j]; 

/*s2*/ 

# • • • • • *2 

for  (p=l;  p<=2*N;  p++){ 

if (p mod 2 == 0) 
Y[p] = Z C p ]; 

Scaling 

X[p] = Y[p] ; 

si  : p  —  2 * i 

} 

(S2  •  P  =  j) 

si 

S2 

Figure 11.35:  Primitive  affine  transforms (I) 

11.7. 

FINDING  SYNCHRONIZATION-FREE  PARALLELISM 

849 

SO U R CE  CO DE 

PA R T I T I ON 

TR A N S F O R M ED  CO DE 

for  (i=0;  i>=N;  i++) 

Y[N-i]  = Z [ i ]; 

/*sl*/ 

for  (j=0;  j<=N;  j++) 

X[j]  =  Y[j] ; 

/*s2*/ 

for  (p=0;  p<=N;  p + +H 

Y[p] = Z[N-p] ; 

Reversal 

X[p] = Y [ p ]; 

si  :  p  =  N  —  i 

} 

(S2-P  =  j) 

s2 

*2 

for  (i=l;  i<=N;  i++) 

for  (j=0;  j<=M;  j++) 

ZCi,j]  = 

Z[i-l,j]; 

P e r m u t a t i on 

p 

'0  1" 

i 

1 

0 

for  (p=0;  p<=M;  p++) 

for  (q=l;  q<=N;  i++) 

Z[q,p]  =  Z[q-l,p] 

O - K) 

o

—

»o  • 

for  (i=l;  i<=N+M-l;  i++) 

for  (j=max(l,i+N); 

j<=min(i,M);  j++) 

Z[i,j]  = 

Z[i-l,j-l]; 

Skewing 

p 

"1 
0 

- 1" 
1 

i 

+ 

for  (p=l;  p<=N;  p++) 

for  (q=l;  q<=M;  q++) 

Z[p,q-p]  = 

Z[p-l,q-p-l] 

O - K) 

O - K) 

O K) 

• 

Figure  11.36:  Primitive  affine  transforms  (II) 

850 

CHAPTER  U. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

Unimodular  Transforms 

A  unimodular  transform  is  represented  by  just  a  unimodular  coefficient 
matrix  and  no  constant  vector.  A  unimodular  matrix  is  a  square  matrix 
whose  determinant  is  ± 1.  T he  significance  of  a  unimodular  transform  is 
t h at  it  maps  an  n-dimensional  iteration  space  to  another  n-dimensional 
polyhedron,  where  there  is  a  one-to-one  correspondence  between  iterations 
of the  two  spaces. 

1.  Fusion.  The  fusion  transform  is  characterized  by  mapping  multiple  loop 
indexes  in  t he  original  program  to  t he  same  loop  index.  T he  new  loop 
fuses  statements  from  different  loops. 

2.  Fission.  Fission  is  the  inverse  of  fusion. 

It  maps  t he  same  loop  index 
for  different  statements  to  different  loop  indexes  in  t he  transformed  code. 
This  splits  the  original  loop  into  multiple  loops. 

3.  Re-indexing.  Re-indexing  shifts  the  dynamic  executions  of  a  statement 
by  a  constant  number  of  iterations.  The  affine  transform  has  a  constant 
term. 

4.  Scaling.  Consecutive  iterations  in  t he  source  program  are  spaced  apart  by 
a  constant  factor.  T he  affine  transform  has  a  positive  nonunit  coefficient. 

5.  Reversal.  Execute  iterations  in  a  loop  in  reverse  order.  Reversal  is  char 

acterized  by  having  —1  as  a  coefficient. 

6.  Permutation.  P e r m u te  t he  inner  and  outer  loops.  T he  affine  transform 

consists  of  permuted  rows  of  the  identity  matrix. 

7.  Shewing.  Iterate  through  the  iteration  space  in  t he  loops  at  an  angle.  T he 

affine  transform  is  a  unimodular  matrix  with  l's  on  t he  diagonal. 

A  G e o m e t r ic  I n t e r p r e t a t i on  of  P a r a l l e l i z a t i on 

T he  affine  transforms  shown  in  all  but  the fission example  are  derived  by  apply 
ing  the  synchronization-free  affine  partition  algorithm  to  the  respective  source 
codes.  (We  shall  discuss  how  fission  can  parallelize  code  with  synchronization 
in  the  next  section.)  In  each  of the  examples,  the  generated  code  has  an  (outer 
most)  parallelizable loop  whose  iterations  can  be  assigned  to  different  processors 
and  no  synchronization  is  necessary. 

These  examples  illustrate  t h at  there  is  a  simple  geometric  interpretation 
of  how  parallelization  works.  Dependence  edges  always  point  from  an  earlier 
instance  to  a  later  instance.  So,  dependences  between  separate  statements 
not  nested  in  any  common  loop  follows  the  lexical  order;  dependences  between 

11.7. 

FINDING 

SYNCHRONIZATION-FREE 

PARALLELISM 

851 

statements  nested  in  the  same  loop  follows  the  lexicographic  order.  Geometri 
cally,  dependences  of  a two-dimensional  loop  nest  always  point  within  the  range 
[0°,  180°),  meaning  t h at  the  angle  of  the  dependence  must  be  below  180°,  but 
no  less  t h an  0°. 

T he  affine  transforms  change  t he  ordering  of  iterations  such  t h at  all  t he 
dependences  are  found  only  between  operations  nested  within  the  same  iteration 
of  the  outermost  loop.  In  other  words,  there  are  no  dependence  edges  at  the 
boundaries  of iterations  in  the  outermost  loop.  We  can  parallelize  simple  source 
codes  by  drawing  their  dependences  and  finding  such  transforms  geometrically. 

11.7.9  Exercises  for  Section  11.7 

E x e r c i se  1 1 . 7 . 1:  For  t he  following  loop 

for  (i = 2;  i  <  100;  i++) 

A[i]  =  A[i-2]; 

a)  W h at  is  t he  largest  number  of  processors  t h at  can  be  used  effectively  to 

execute  this  loop? 

b)  Rewrite  t he  code  with  processor  p  as  a  parameter. 

c)  Set  up  and  find  one  solution  to  the  space-partition  constraints  for  this 

loop. 

d)  W h at  is  the  affine  partition  of  highest  rank  for  this  loop? 

E x e r c i se  1 1 . 7 . 2:  Repeat  Exercise  11.7.1  for  the  loop  nests  in  Fig.  11.37. 

E x e r c i se  1 1 . 7 . 3:  Rewrite  the  following  code 

for  (i = 0;  i  <  100;  i++) 

A[i] = 2*A[i] ; 

for  (j  = 0;  j  <  100;  j++) 

A[j]  = A[j]  +  1; 

so  it  consists  of a  single  loop.  Rewrite  the  loop  in  terms  of a  processor  number p 
so  the  code  can  be  partitioned  among  100  processors,  with  iteration  p  executed 
by  processor  p. 

E x e r c i se  1 1 . 7 . 4:  In  t he  following  code 

for  (i =  1;  i  <  100;  i++) 

for  (j  =  1;  j  <  100;  j++) 

/*  (s)  */ 

A[i,j]  = 

(A[i-l,j]  + A[i+l,j]  + A[i,j-1]  + A[i,j+l])/4; 

852 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

for (i = 0;  i <= 97;  i++) 

A[i] = A[i+2] ; 

(a) 

for  (i =  1;  i <= 100;  i++) 

for (j = 1;  j  <= 100;  j++) 

for  (k =  1;  k <= 100;  k++)  { 

A[i,j,k]  = A[i,j,k]  + B[i-l,j,k]; 
B[i,j,k] = B[i,j,k] + C[i, j-l,k] ; 
C[i,j,k]  = C[i,j,k]  + A[i,j,k-1]; 

} 

!(b) 

for (i =  1;  i <= 100;  i++) 

for  (j =  1;  j  <= 100;  j++) 

for  (k = 1;  k <= 100;  k++)  { 

A[i,j,k]  = A[i,j,k]  + B[i-l,j,k]; 
B[i,j,k]  = B[i,j,k]  + A[i,j-l,k]; 
C[i,j,k]  = C[i,j,k]  + A[i,j,k-1]  + B[i,j,k]; 

} 

!(c) 

Figure 11.37:  Code  for  Exercise 11.7.2 

the  only  constraints  are  t h at  t he  statement  s  t h at  forms  the  body  of  the  loop 
nest  must  execute  iterations  s(i  —  l,j)  and  s(i, j — 1)  before  executing  iteration 
s(i,j).  Verify  t h at  these  are  the  only  necessary  constraints.  T h en  rewrite  t he 
code  so  t h at  t he  outer  loop  has  index  variable  p,  and  on  t he  p th  iteration  of t he 
outer  loop,  all  instances  of  s(i,j)  such  t h at  i  +  j  =  p  are  executed. 

Exercise  1 1 . 7 . 5:  Repeat  Exercise 11.7.4,  b ut  arrange t h at  on the p th iteration 
of  the  outer  loop,  instances  of  s  such  t h at  i  —  j  =  p  are  executed. 

! Exercise  1 1 . 7 . 6:  Combine  the  following loops 

for (i = 0;  i < 100;  i++) 

A[i] = B [ i ]; 

for (j = 98;  j  >= 0;  j = j-2) 

B[i] = i; 

into  a  single  loop,  preserving  all  dependencies. 

11.8. 

SYNCHRONIZATION 

BETWEEN 

PARALLEL 

LOOPS 

853 

E x e r c i se  1 1 . 7 . 7:  Show  t h at  t he  matrix 

"2  1" 
1 
1 

is  unimodular.  Describe  the  transformation  it  performs  on  a  two-dimensional 
loop  nest. 

E x e r c i se  1 1 . 7 . 8:  Repeat  Exercise  11.7.7  on  the  matrix 

"1  3" 
2  5 

11.8  Synchronization  Between  Parallel  Loops 

Most  programs  have  no  parallelism  if we  do  not  allow  processors  to  perform  any 
synchronizations.  But  adding  even  a  small  constant  number  of  synchronization 
operations  to  a  program  can  expose  more  parallelism.  We  shall  first  discuss 
parallelism  made  possible  by  a  constant  number  of  synchronizations  in  this 
section  and  the  general  case,  where  we  embed  synchronization  operations  in 
loops,  in  the  next. 

11.8.1  A  Constant  Number  of  Synchronizations 

Programs  with  no  synchronization-free  parallelism  may  contain  a  sequence  of 
loops,  some  of which  are  parallelizable  if they  are  considered  independently.  We 
can  parallelize  such  loops  by  introducing  synchronization  barriers  before  and 
after  their  execution.  Example  11.49  illustrates  the  point. 

for  (i  =  1; 

i  <  n; 

for  (j  =  0; 

i++) 
j  <  n; 

j++) 

X [ i , j]  =  f ( X [ i , jl  +  X [ i - l , j ] ); 

for  (i  =  0; 

i  <  n; 

for  (j  =  1; 

i++) 
j  <  n; 

X [ i , j]  =  g ( X [ i , j]  +  X [ i , j - 1 ] ); 

Figure  11.38:  Two  sequential  loop  nests 

E x a m p le  1 1 . 4 9:  In  Fig.  11.38  is  a  program  representative  of  an  ADI  (Alter 
nating  Direction  Implicit)  integration  algorithm.  There  is  no  synchronization-
free  parallelism.  Dependences  in  the  first  loop  nest  require  t h at  each  processor 
works  on  a  column  of  array  X;  however,  dependences  in  t he  second  loop  nest 
require  t h at  each  processor  works  on  a  row  of  array  X.  For  there  to  be  no  com 
munication,  t he  entire  array  has  to  reside  on  the  same  processor,  hence  there 

854 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

is  no  parallelism.  We  observe,  however,  t h at  both  loops  are  independently 
parallelizable. 

One  way  to  parallelize  the  code  is  to  have  different  processors  work  on 
different  columns  of  t he  array  in  t he  first  loop,  synchronize  and  wait  for  all 
processors  to  finish,  and  then  operate  on  t he  individual  rows. 
In  this  way, 
all  the  computation  in  the  algorithm  can  be  parallelized  with  the  introduction 
of  just  one  synchronization  operation.  However,  we  note  t h at  while  only  one 
synchronization  is  performed,  this  parallelization  requires  almost  all  the  d a ta 
in  matrix  X  to  be  transferred  between  processors.  It  is  possible  to  reduce  t he 
amount  of communication  by  introducing  more  synchronizations,  which  we  shall 
discuss  in  Section  11.9.9. 

• 

It  may  appear  t h at  this  approach  is  applicable  only  to  programs  consisting 
of  a  sequence  of  loop  nests.  However,  we  can  create  additional  opportunities 
for  the  optimization  through  code  transforms.  We  can  apply  loop  fission  to 
decompose  loops  in  t he  original  program  into  several  smaller  loops,  which  can 
then  be  parallelized  individually  by  separating t h em  with  barriers.  We  illustrate 
this  technique  with  Example  11.50. 

E x a m p le  1 1. 5 0:  Consider  the  following  loop: 

for  (i=l;  i<=n;  i++)  { 

X[i]  = Y[i]  + Z[i]; 

W[A[i]] = X[i] ; 

/*  (si)  */ 
/*  (s2)  */ 

} 

Without  knowledge  of  t he  values  in  array  A,  we  must  assume  t h at  the  access 
in  statement  s2  may  write  to  any  of  t he  elements  of  W.  Thus,  the  instances  of 
S2  must  be  executed  sequentially  in  t he  order  they  are  executed  in  t he  original 
program. 

There  is  no  synchronization-free  parallelism,  and  Algorithm  11.43  will  sim 
ply  assign  all  t he  computation  to  t he  same  processor.  However,  at  t he  least, 
instances  of  statement  si  can  be  executed  in  parallel.  We  can  parallelize  part 
of this  code  by  having  different  processors  perform  difference  instances  of  state 
ment  si.  Then,  in  a  separate  sequential  loop,  one  processor,  say  numbered  0, 
executes  s2,  as  in  the  S P MD  code  shown  in  Fig.  11.39. 

• 

11.8.2  Program-Dependence  Graphs 

To  find  all  the  parallelism  made  possible  by  a  constant  number  of  synchroniza 
tions,  we  can  apply  fission  to  the  original  program  greedily.  Break  up  loops 
into  as  many  separate  loops  as  possible,  and  then  parallelize  each  loop  indepen 
dently. 

To  expose  all  t he  opportunities  for  loop  fission,  we  use  t he  abstraction  of a 
program-dependence  graph  ( P D G ).  A  program  dependence  graph  of  a  program 

11.8. 

SYNCHRONIZATION  BETWEEN  PARALLEL  LOOPS 

855 

X[p]  =  Y[p]  +  Z [ p ]; 
/*  s y n c h r o n i z a t i on  b a r r i er  */ 
if 

(p  ==  0) 

/*  ( s i)  */ 

f or 

( i = l; 
i++) 
i < = n; 
W[A[i]]  =  X [ i ]; 

/*  ( s 2)  */ 

Figure  11.39:  S P MD  code  for  t he  loop  in  Example  11.50,  with p being  a variable 
holding  t he  processor  ID 

is  a  graph  whose  nodes  are  the  assignment  statements  of the  program  and  whose 
edges  capture  the  d a ta  dependences,  and  the  directions  of the  d a ta  dependence, 
between  statements.  An  edge  from  statement  si  to  statement  s2  exists  whenever 
some  dynamic  instance  of  s\  shares  a  d a ta  dependence  with  a  later  dynamic 
instance  of  s2. 

To  construct  t he  P DG  for  a  program,  we  first  find  the  d a ta  dependences 
between  every  pair  of  (not  necessarily  distinct)  static  accesses  in  every  pair 
of  (not  necessarily  distinct)  statements.  Suppose  we  determine  t h at  there  is 
a  dependence  between  access  T\  in  statement  s\  and  access  T2  in  statement 
s2.  Recall  t h at  an  instance  of  a  statement  is  specified  by  an  index  vector 
i  =  [hih,  •  •  •  ,im]  where  ik  is  t he  loop  index  of  t he  kth  outermost  loop  in 
which  t he  statement  is  embedded. 

1.  If  there  exists  a  data-dependent  pair  of  instances,  ii  of  si  and  i2  of  s2, 

and  ii  is  executed  before  i2  in  the  original  program,  written  ii  ^S l S2
then  there  is  an  edge  from  s\  to  s2. 

l2, 

2.  Similarly,  if  there  exists  a  data-dependent  pair  of  instances,  ii  of  si  and 

i2  of  s2,  and  i2 

- < s i s2  ii>  then  there  is  an  edge  from  s2  to  s\. 

Note  t h at  it  is  possible  for  a  d a ta  dependence  between  two  statements  si  and 
s2  to  generate  b o th  an  edge  from  si  to  s2  and  an  edge  from  s2  back  to  s\. 

In  the  special  case  where  statements  si  and  s2  are  not  distinct,  ii  - <S ls2  i2  if 
and  only  if  ii  -<  i2  (ii  is  lexicographically  less  t h an  i2).  In  the  general  case,  si 
and  s2  may  be  different  statements,  possibly  belonging  to  different  loop  nests. 

E x a m p le  1 1 . 5 1:  For  t he  program  of Example  11.50,  there  are  no  dependences 
among  t he  instances  of  statement  s\.  However,  the  z'th  instance  of  statement 
s2  must  follow  the  ith  instance  of  statement  8\.  Worse,  since  the  reference 
Wp4[i]]  may  write  any  element  of  array  W,  the  ith  instance  of  s2  depends  on 
all  previous  instances  of  s2.  T h at  is,  statement  s2  depends  on  itself.  T he  P DG 
for  the  program  of  Example  11.50  is  shown  in  Fig.  11.40.  Note  t h at  there  is 
one  cycle  in  the  graph,  containing  s2  only. 

• 

The  program-dependence  graph  makes  it  easy  to  determine  if  we  can  split 
statements  in  a  loop.  Statements  connected  in  a  cycle  in  a  P DG  cannot  be 

 
856 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

Q 

Figure  11.40:  Program-dependence  graph  for  t he  program  of  Example  11.50 

split. 
If  si  —y  s2  is  a  dependence  between  two  statements  in  a  cycle,  then 
some  instance  of  si  must  execute  before  some  instance  of  s2,  and  vice  versa. 
Note  t h at  this  mutual  dependence  occurs  only  if  si  and  s2  are  embedded  in 
some  common  loop.  Because  of  the  mutual  dependence,  we  cannot  execute  all 
instances  of  one  statement  before  the  other,  and  therefore  loop  fission  is  not 
s2  is  unidirectional,  we 
allowed.  On  t he  other  hand,  if  the  dependence  s± 
can  split  up  the  loop  and  execute  all  the  instances  of  si  first,  then  those  of  s2. 

f or 

i  <  n; 

i++)  { 

(i  = 0; 
Z [ i]  =  Z [ i] 
f or  (j  =  i; 

/  WCi]; 
j++)  { 
j  <  n; 
X [ i , j]  =  Y[ i , j] * Y[ i , j ]; 
Z [ j]  =  Z [ j]  +  X [ i , j ]; 

/* 

( s i)  */ 

/* 
/* 

( s 2)  */ 
( s 3)  */ 

} 

} 

(a)  A  program. 

(b)  Its  dependence  graph. 

Figure  11.41:  P r o g r am  and  dependence  graph  for  Example  11.52. 

E x a m p le  1 1 . 5 2:  Figure  11.41(b)  shows  the  program-dependence  graph  for 
the  program  of  Fig.  11.41(a).  Statements  s±  and  53  belong  to  a  cycle  in  t he 
graph  and  therefore  cannot  be  placed  in  separate  loops.  We  can,  however,  split 
statement  s2  out  and  execute  all  its  instances  before  executing  the  rest  of  the 
computation,  as  in  Fig.  11.42.  T he  first  loop  is  parallelizable,  but  t he  second 
is  not.  We  can  parallelize  the  first  loop  by  placing  barriers  before  and  after  its 
parallel  execution. 

• 

11.8. 

SYNCHRONIZATION  BETWEEN  PARALLEL 

LOOPS 

857 

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

for  (j  =  i;  j  < n;  j++) 

X[i,j] = Y[i,j]*Y[i,j]; 

/*  (s2)  */ 

for  (i = 0;  i  < n;  i++)  { 
Z[i]  = Z[i]  / W[i] ; 
for  (j  =  i;  j  < n;  j++) 

/*  (si)  */ 

Z[j]  =  Z[j]  +  X[i,j]; 

/*  (s3)  */ 

} 

Figure  11.42:  Grouping  strongly  connected  components  of  a  loop  nest 

11.8.3  Hierarchical  Time 

While  t he  relation  - <S l S2  can  be  very  hard  to  compute  in  general,  there  is  a 
family  of  programs  to  which  the  optimizations  of  this  section  are  commonly 
applied,  and  for  which  there  is  a  straightforward  way  to  compute  dependencies. 
Assume  t h at  the  program  is  block  structured,  consisting  of  loops  and  simple 
arithmetic  operations  and  no  other  control  constructs.  A  statement  in  the 
program  is  either  an  assignment  statement,  a  sequence  of  statements,  or  a  loop 
construct  whose  body  is  a  statement.  The  control  structure  thus  represents  a 
hierarchy.  At  the  top  of the  hierarchy  is  the  node  representing  the  statement  of 
the  whole  program.  An  assignment  statement  is  a  leaf  node.  If  a  statement  is 
a  sequence,  then  its  children  are  the  statements  within  the  sequence,  laid  out 
from  left  to  right  according  to  their  lexical  order.  If  a  statement  is  a  loop,  then 
its  children  are  the  components  of  the  loop  body,  which  is  typically  a  sequence 
of  one  or  more  statements. 

sO; 
LI:  for  (i 

si; 

0;  ...)  { 

L2:  for  (j 

0; 

)  { 

s2; 

s3; 

} 
for  (k 

L3: 

0; 

s4; 

s5; 

} 

Figure  11.43:  A  hierarchically  structured  program 

E x a m p le  1 1 . 5 3:  T he  hierarchical  structure  of  the  program  in  Fig.  11.43  is 
shown  in  Fig.  11.44.  T he  hierarchical  n a t u re  of t he  execution  sequence  is  high-

858 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

lighted  in  Fig.  11.45.  T he  single  instance  of  s0  precedes  all  other  operations, 
because  it  is  the  first  statement  executed.  Next,  we  execute  all  instructions 
from  the  first  iteration  of  t he  outer  loop  before  those  in  the  second  iteration 
and  so  forth.  For  all  dynamic  instances  whose  loop  index  i  has  value  0,  the 
statements  s i,  L2,  L3,  and  s5  are  executed  in  lexical  order.  We  can  repeat  the 
same  argument  to  generate  the  rest  of  the  execution  order. 

• 

Prog 

si 

L2 

L3 

s5 

s2 

s3 

s4 

Figure  11.44:  Hierarchical  structure  of the  program  in  Example  11.53. 

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 

so 
Li 

i  =  0 

si 
L2 

j  =  0 

3  =  1 

s2 

S3 
s2 
S3 

L3 

k  =  0  S4 
k  =  1  S4 

S5 
Si 

i  =  1 

Figure  11.45:  Execution  order  of the  program  in  Example  11.53. 

We  can  resolve t he  ordering  of two  instances  from  two  different  statements  in 
a  hierarchical  manner.  If t he  statements  share  common  loops,  we  compare  t he 
values  of their  common  loop  indexes,  starting  with  the  outermost  loop.  As  soon 
as  we  find  a  difference  between  their  index  values,  t he  difference  determines  t he 
ordering.  Only  if t he  index  values  for  t he  outer  loops  are  t he  same  do  we  need 
to  compare  t he  indexes  of  t he  next  inner  loop.  This  process  is  analogous  to 
how  we  would  compare  time  expressed  in  terms  of hours,  minutes  and  seconds. 
To  compare  two  times,  we  first  compare  the  hours,  and  only  if  they  refer  to 

11.8. 

SYNCHRONIZATION  BETWEEN  PARALLEL  LOOPS 

859 

t he  same  hour  would  we  compare  the  minutes  and  so  forth.  If  t he  index  values 
are  the  same  for  all  common  loops,  then  we  resolve  the  order  based  on  their 
relative  lexical  placement.  Thus,  the  execution  order  for  the  simple  nested-loop 
programs  we  have  been  discussing  is  often  referred  to  as  "hierarchical  time." 

Let  si  be  a  statement  nested  in  a  di-deep  loop,  and  s2  in  a  d2-deep  loop, 
sharing  d  common  (outer)  loops;  note  d  <  d\  and  d  <  d2  certainly.  Suppose 
i  =  [*i,«2,  •  •  •  ,«di] 
s2. 

is  an  instance  of  s\  and  j  =  [ji,  j2,

..  , jd2]  is  an  instance  of 

.

i  -<Sls2  $  ^  and  only  if  either 

1.  [h,i2,.  •  • 

, « dH  \juJ2,--  • 

,  jd],  or 

2.  [h,i2,... 

,id]  =  [ji,J2,  ••• 

,jd],  and  si  appears  lexically  before  s2. 

T he  predicate  [ii,  i2,...  ,id]  -<  [ji, h,  •  •  •  , 3d]  can  be  written  as  a  disjunction 

of  linear  inequalities: 

(*i  <  j i)  V  (h  =  ji  A  i2  <  j2)  V  . ..  V  (ii  =  ji  A  . ..  A 

=  jd-i  A  id  <  jd) 

A  P DG  edge  from  si  to  s2  exists  as  long  as  the  data-dependence  condition 
and  one  of  the  disjunctive  clauses  can  be  made  true  simultaneously.  Thus, 
we  may  need  to  solve  up  to  d  or  d  +  1  linear  integer  programs,  depending  on 
whether  si  appears  lexically  before  s2,  to  determine  the  existence  of  one  edge. 

11.8.4  The  Parallelization  Algorithm 

We  now  present  a  simple  algorithm  t h at  first  splits  up  the  computation  into  as 
many  different  loops  as  possible,  then  parallelizes  t h em  independently. 

A l g o r i t hm  1 1. 5 4:  Maximize  the  degree  of  parallelism  allowed  by  0 ( 1)  syn 
chronizations. 

INPUT:  A  program  with  array  accesses. 

OUTPUT:  SPMD  code  with  a  constant  number  of  synchronization  barriers. 

METHOD: 

1.  Construct  the  program-dependence  graph  and  partition  the  statements 
into  strongly  connected  components  (SCC's).  Recall  from  Section  10.5.8 
t h at  a  strongly  connected  component  is  a  maximal  subgraph  of  the  orig 
inal  whose  every  node  in  t he  subgraph  can  reach  every  other  node. 

2.  Transform  the  code  to  execute  SCC's  in  a  topological  order  by  applying 

fission  if  necessary. 

3.  Apply  Algorithm  11.43  to  each  SCC  to  find  all  of  its  synchronization-free 
parallelism.  Barriers  are  inserted  before  and  after  each  parallelized  SCC. 

• 

860 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

While  Algorithm 11.54  finds  all  degrees  of  parallelism  with 0(1)  synchro 
nizations,  it  has  a  number  of  weaknesses.  First,  it  may  introduce  unnecessary 
synchronizations.  As  a  m a t t er  of  fact,  if  we  apply  this  algorithm  to  a  program 
t h at  can  be  parallelized  without  synchronization,  the  algorithm  will  parallelize 
each  statement  independently  and  introduce  a  synchronization  barrier  between 
the  parallel  loops  executing  each  statement.  Second,  while  there  may  only  be  a 
constant  number  of  synchronizations,  the  parallelization  scheme  may  transfer 
a  lot  of  d a ta  among  processors  with  each  synchronization.  In  some  cases,  t he 
cost  of  communication  makes  t he  parallelism  too  expensive,  and  we  may  even 
be  better  off  executing  the  program  sequentially  on  a  uniprocessor.  In  t he  fol 
lowing  sections,  we  shall  next  take  up  ways  to  increase  d a ta  locality,  and  thus 
reduce  the  amount  of  communication. 

11.8.5  Exercises  for  Section  11.8 

Exercise 11.8.1:  Apply  Algorithm 11.54  to  the  code  of  Fig. 11.46. 

for  (i=0;  i<100;  i++) 

A[i]  = A[i]  + X [ i ];  /*  (si)  */ 

for  (i=0;  i<100;  i++) 

for  (j=0;  j<100;  j++) 

B[i,j]  = Y[i,j]  + A[i]  + A [ j ];  /*  (s2)  */ 

Figure 11.46:  Code  for  Exercise 11.8.1 

Exercise  1 1 . 8 . 2:  Apply  Algorithm 11.54  to  the  code  of Fig. 11.47. 

for  (i=0;  i<100;  i++) 

A[i]  = A[i]  + X [ i ];  /*  (si)  */ 

for  (i=0;  i<100;  i++)  { 

B[i]  = B[i]  + A [ i ];  /*  (s2)  */ 
for  (j=0;  j<100;  j++) 

C[j]  = Y[j]  + B [ j ];  /*  (s3)  */ 

} 

Figure 11.47:  Code  for  Exercise 11.8.2 

Exercise 11.8.3:  Apply  Algorithm 11.54  to  the  code  of Fig. 11.48. 

11.9. 

PIPELINING 

861 

f or 

i++) 

i < 1 0 0; 
( i = 0; 
A [ i]  =  A [ i]  +  X [ i ]; 
i++)  { 

i < 1 0 0; 

f or  ( i = 0; 

/*  ( s i)  */ 

f or 

( j = 0; 
j < 1 0 0; 
B [ j]  =  A [ i]  +  Y [ j ]; 

j++) 

/*  ( s 2)  */ 

C [ i]  =  B [ i]  +  Z [ i ]; 
f or 

j < 1 0 0; 

( j = 0; 
D [ i , j]  =  A [ i]  +  B [ j ]; 

j++) 

/*  ( s 3)  */ 

/* 

( s 4)  */ 

} 

Figure  11.48:  Code  for  Exercise  11.8.3 

11.9  Pipelining 

In  pipelining,  a  task  is  decomposed  into  a  number  of  stages  to  be  performed  on 
different  processors.  For  example,  a  task  computed  using  a  loop  of  n  iterations 
can  be  structured  as  a  pipeline  of n  stages.  Each  stage  is  assigned  to  a  different 
processor;  when  one  processor  is  finished  with  its  stage,  the  results  are  passed 
as  input  to  t he  next  processor  in  the  pipeline. 

In  t he  following,  we  start  by  explaining  the  concept  of  pipelining  in  more 
detail.  We  then  show  a  real-life  numerical  algorithm,  known  as  successive  over-
relaxation,  to  illustrate  the  conditions  under  which  pipelining  can  be  applied,  in 
Section  11.9.2.  We  then  formally  define  the  constraints  t h at  need  to  be  solved 
in  Section  11.9.6,  and  describe  an  algorithm  for  solving  them  in  Section  11.9.7. 
Programs  t h at  have  multiple  independent  solutions  to  t he  time-partition  con 
straints  are  known  as  having  outermost  fully  permutable  loops;  such  loops  can 
be  pipelined  easily,  as  discussed  in  Section  11.9.8. 

11.9.1  What  is  Pipelining? 

Our  initial  a t t e m p ts  to  parallelize  loops  partitioned  the  iterations  of  a  loop  nest 
so  t h at  two  iterations  t h at  shared  d a ta  were  assigned  to  the  same  processor. 
Pipelining  allows  processors  to  share  data,  b ut  generally  does  so  only  in  a 
"local,"  way,  with  d a ta  passed  from  one  processor  to  another  t h at  is  adjacent 
in  the  processor  space.  Here  is  a  simple  example. 

E x a m p le  1 1. 55  :  Consider  the  loop: 

f or  (i  =  1; 

i  <=  m; 

i++) 

f or  (j  =  1; 

j  <=  n; 
X [ i]  =  X [ i]  +  Y [ i , jl  ; 

j++) 

This  code  sums  up  t he  i th  row  of  Y  and  adds  it  to  t he  ith  element  of  X.  T he 
inner  loop,  corresponding  to  the  summation,  must  be  performed  sequentially 

862 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

1 
x[i]+=r[i,i] 
X[2]+=Y[2,1] 
X[3]+=Y[3,1) 
X[4]+=Y[4,1] 

Time 

1 
2 
3 
4 
5 
6 

Processors 
2 

3 

X[l] + : 
X[2} + : 
X[3}+: 
X[4] + : 

:Y[1,2] 
Y%2] 
Y[3,2] 
Y[4:2] 

X[l]+ 
X[2}+. 
X[3] + : 

:y[i,3] 

•Y[2,3] 

Y[4,3] 

Fi  gure  11.49:  Pipelined  execution  of  Example  11.55  with  m  =  4  and  n  =  3. 

because  of  the  d a ta  dependence;6  however,  the  different  summation  tasks  are 
independent.  We  can  parallelize  this  code  by  having  each  processor  perform 
a  separate  summation.  Processor  i  accesses  row  i  of  Y  and  updates  the  ith 
element  of  X. 

Alternatively,  we  can  structure  the  processors  to  execute  the  summation  in  a 
pipeline,  and  derive  parallelism  by  overlapping the  execution  of the  summations, 
as  shown  in  Fig.  11.49.  More  specifically,  each  iteration  of  t he  inner  loop  can 
be  treated  as  a  stage  of  a  pipeline:  stage  j  takes  an  element  of  X  generated 
in  t he  previous  stage,  adds  to  it  an  element  of  Y,  and  passes  the  result  to  the 
next  stage.  Notice  t h at  in  this  case,  each  processor  accesses  a  column,  instead 
of  a  row,  of  Y.  If  Y  is  stored  in  column-major  form,  there  is  a  gain  in  locality 
by  partitioning  according  to  columns,  rather  t h an  by  rows. 

We  can  initiate  a  new  task  as  soon  as  the  first  processor  is  done  with  t he  first 
stage  of the  previous  task.  At  the  beginning,  the  pipeline  is  empty  and  only  the 
first  processor  is  executing  the  first  stage.  After  it  completes,  the  results  are 
passed  to  the  second  processor,  while  the  first  processor  starts  on  the  second 
task,  and  so  on.  In  this  way,  the  pipeline  gradually fills until  all  the  processors 
are  busy.  When  t he  first  processor finishes with  t he  last  task,  t he  pipeline  starts 
to  drain,  with  more  and  more  processors  becoming  idle  until  the  last  processor 
finishes  the  last  task.  In  the  steady  state,  n  tasks  can  be  executed  concurrently 
in  a  pipeline  of  n  processors. 

• 

It  is  interesting  to  contrast  pipelining  with  simple  parallelism,  where  differ 

ent  processors  execute  different  tasks: 

•  Pipelining  can  only  be  applied  to  nests  of  depth  at  least  two.  We  can 
treat  each  iteration  of  the  outer  loop  as  a  task  and  t he  iterations  in  t he 
inner  loop  as  stages  of  t h at  task. 

•  Tasks  executed  on  a  pipeline  may  share  dependences. 

Information  per 
taining  to  the  same  stage  of each  task  is  held  on  the  same  processor;  thus 
results  generated  by  t he  i th  stage  of  a  task  can  be  used  by  the  i th  stage 

6Remember that  we  do  not  take  advantage  of the  assumed  commutativity  and  associativity 

of  addition. 

11.9.  PIPELINING 

863 

of  subsequent  tasks  with  no  communication  cost.  Similarly,  each  input 
d a ta  element  used  by  a  single  stage  of  different  tasks  needs  to  reside  only 
on  one  processor,  as  illustrated  by  Example  11.55. 

•  If the  tasks  are  independent,  then  simple  parallelization  has  better  proces 
sor  utilization  because  processors  can  execute  all  at  once  without  having 
to  pay  for  the  overhead  of  filling  and  draining  the  pipeline.  However, 
as  shown  in  Example  11.55,  t he  p a t t e rn  of  d a ta  accesses  in  a  pipelined 
scheme  is  different  from  t h at  of  simple  parallelization.  Pipelining  may  be 
preferable  if  it  reduces  communication. 

11.9.2 

Successive  Over-Relaxation  (SOR):  An  Example 

Successive  over-relaxation  (SOR) 
is  a  technique  for  accelerating  the  conver 
gence  of  relaxation  methods  for  solving  sets  of  simultaneous  linear  equations. 
A  relatively  simple  template  illustrating  its  data-access  p a t t e rn  is  shown  in 
Fig.  11.50(a).  Here,  t he  new  value  of  an  element  in  the  array  depends  on  the 
values  of  elements  in  its  neighborhood.  Such  an  operation  is  performed  repeat 
edly,  until  some  convergence  criterion  is  met. 

f or  (i  =  0; 

i  <=  m; 

i++) 

f or  (j  =  0; 

j  <=  n; 

j++) 

X[j+1]  =  1/3  *  ( X [ j]  +  X[j+1]  +  XCj+2]) 

(a)  Original  source. 

(b)  D a ta  dependences  in  the  code. 

j 

Figure  11.50:  An  example  of  successive  over-relaxation  (SOR) 

Shown  in  Fig.  11.50(b)  is  a  picture  of the  key  d a ta  dependences.  We  do  not 
show  dependences  t h at  can  be  inferred  by  the  dependences  already  included  in 
the  figure.  For  example,  iteration  [i,j]  depends  on  iterations  [i,j  —  1],  [i,j  —  2] 
and  so  on.  It  is  clear  from  the  dependences  t h at  there  is  no  synchronization-
free  parallelism.  Since  the  longest  chain  of  dependences  consists  of  0(m  +  n) 
edges,  by  introducing  synchronization,  we  should  be  able  to  find  one  degree  of 
parallelism  and  execute  t he  0(mn)  operations  in  0(m  +  n)  unit  time. 

864 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

In  particular,  we  observe  t h at  iterations  t h at  lie  along  t he  150°  diagonals7  in 
Fig.  11.50(b)  do  not  share  any  dependences.  They  Only  depend  on the  iterations 
t h at  lie  along  diagonals  closer  to  the  origin.  Therefore  we  can  parallelize  this 
code  by  executing  iterations  on  each  diagonal  in  order,  starting  at  the  origin 
and  proceeding  outwards.  We  refer  to  t he  iterations  along  each  diagonal  as  a 
wavefront,  and  such  a  parallelization  scheme  as  wavefronting. 

11.9.3  Fully  Permutable  Loops 

We  first  introduce  the  notion  of full  permutability,  a  concept  useful  for  pipelining 
and  other  optimizations.  Loops  are  fully  permutable  if  they  can  be  permuted 
arbitrarily  without  changing  the  semantics  of  the  original  program.  Once  loops 
are  put  in  a  fully  permutable  form,  we  can  easily  pipeline  t he  code  and  apply 
transformations  such  as  blocking  to  improve  d a ta  locality. 

The  SOR  code,  as  it  it  written  in  Fig.  11.50(a),  is  not  fully  permutable. 
As  shown  in  Section  11.7.8,  permuting  two  loops  means  t h at  iterations  in  t he 
original  iteration  space  are  executed  column  by  column  instead  of  row  by  row. 
For  instance,  the  original  computation  in  iteration  [2,3]  would  execute  before 
t h at  of  [1,4],  violating  t he  dependences  shown  in  Fig.  11.50(b). 

We  can,  however,  transform  t he  code  to  make  it  fully  permutable.  Applying 

the  affine  transform 

" 1 0" 
1 
1 

to  the  code  yields  the  code  shown  in  Fig.  11.51(a).  This  transformed  code 
is  fully  permutable,  and  its  permuted  version  is  shown  in  Fig.  11.51(c).  We 
also  show  the  iteration  space  and  d a ta  dependences  of  these  two  programs  in 
Fig.  11.51(b)  and  (d),  respectively.  From  the  figure,  we  can  easily  see  t h at  this 
ordering  preserves  the  relative  ordering  between  every  data-dependent  pair  of 
accesses. 

When  we  permute  loops,  we  change  t he  set  of  operations  executed  in  each 
iteration  of  the  outermost  loop  drastically.  T he  fact  t h at  we  have  this  degree 
of  freedom  in  scheduling  means  t h at  there  is  a  lot  of  slack  in  the  ordering 
of  operations  in  the  program.  Slack  in  scheduling  means  opportunities  for 
parallelization.  We  show  later  in  this  section  t h at  if  a  loop  has  k  outermost 
fully  permutable  loops,  by  introducing  just  0(n)  synchronizations,  we  can  get 
0(k  -  1)  degrees  of  parallelism  (n  is  the  number  of  iterations  in  a  loop). 

11.9.4  Pipelining  Fully  Permutable  Loops 

A  loop  with  k  outermost  fully  permutable  loops  can  be  structured  as  a  pipeline 
with  0(k  -  1)  dimensions.  In  the  SOR  example,  k  =  2,  so  we  can  structure  the 
processors  as  a  linear  pipeline. 

7I.e.,  the  sequences  of points  formed  by  repeatedly  moving  down  1  and  right  2. 

11.9. 

PIPELINING 

865 

f or  (i  =  0; 

f or  (j  = 

i  <=  m; 

i++) 
j  <=  i + n; 
X [ j - i + l]  =  1/3  * 

i; 

( X [ j - i]  +  X [ j - i + l]  +  X [ j - i + 2 ]) 

(a)  T he  code  in  Fig.  11.50  transformed  by 

i A 

(b)  D a ta  dependences  of the  code  in  (a). 

f or  (j  =  0; 
f or 

j  <=  m+n; 
(i  =  m a x ( 0 , j ); 
X [ j - i + l]  =  1/3  * 

j++) 
i  <=  m i n ( m , j ), 

i++) 
( X [ j - i]  +  XCj-i+1]  +  X [ j - i + 2 ]) 

(c)  A  permutation  of  the  loops  in  (a). 

(d)  D a ta  dependences  of  the  code  in  (b). 

Figure  11.51:  Fully  permutable  version  of  the  code  Fig.  11.50 

866 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

We  can  pipeline  the  SOR  code  in  two  different  ways,  shown  in  Fig.  11.52(a) 
and  Fig.  11.52(b),  corresponding  to  the  two  possible  permutations  shown  in 
Fig.  11.51(a)  and  (c),  respectively.  In  each  case,  every  column  of  t he  iteration 
space  constitutes  a  task,  and  every  row  constitutes  a  stage.  We  assign  stage  i 
to  processor  i,  thus  each  processor  executes  t he  inner  loop  of the  code.  Ignoring 
boundary  conditions,  a  processor  can  execute  iteration  i  only  after  processor 
p —  1  has  executed  iteration  i  —  1. 

j  <=  p+n; 

/*  0  <=  p  <=  m  */ 
f or  (j  =  p; 
if 
(p  >  0)  w a it 
X [ j - p + l]  =  1/3  * 
if 

j + +)  { 

( p - 1 ); 

(p  <  min  ( m , j ))  s i g n al  ( p + 1 ); 

( X [ j - p]  +  X [ j - p + l]  +  X [ j - p + 2 ] ); 

} 

(a)  Processors  assigned  to  rows. 

/*  0  <=  p  <=  m+n  */ 

f or  (i  =  m a x ( 0 , p ); 

i  <=  m i n ( m , p ); 

i++)  { 

(p  >  m a x ( 0 , i ))  w a it 

if 
X [ p - i + l]  =  1/3  *  ( X [ p - i]  +  X [ p - i + l]  +  XCp-i+2]) 
if  (p  <  m+n)  &  (p  >  i)  s i g n al  ( p + 1 ); 

( p - 1 ); 

} 

(b)  Processors  assigned  to  columns. 

Figure  11.52:  Two  pipelining  implementations  of  t he  code  from  Fig.  11.51 

Suppose  every  processor  takes  exactly  t he  same  amount  of  time  to  execute 
an  iteration  and  synchronization  happens  instantaneously.  Both  these  pipelined 
schemes  would  execute  t he  same  iterations  in  parallel;  the  only  difference  is 
t h at  they  have  different  processor  assignments.  All  t he  iterations  executed  in 
parallel  lie  along  the  135°  diagonals  in  the  iteration  space  in  Fig.  11.51(b), 
which  corresponds  to  the  150°  diagonals  in  the  iteration  space  of  the  original 
code;  see  Fig.  11.50(b). 

However,  in  practice,  processors  with  caches  do  not  always  execute  the  same 
code  in  t he  same  amount  of time,  and  t he  time  for  synchronization  also  varies. 
Unlike  the  use  of  synchronization  barriers  which  forces  all  processors  to  operate 
in  lockstep,  pipelining  requires  processors  to  synchronize  and  communicate  with 
at  most  two  other  processors.  Thus,  pipelining  has  relaxed  wavefronts,  allowing 
some  processors  to  surge  ahead  while  others  lag  momentarily.  This  flexibility 
reduces  the  time  processors  spend  waiting  for  other  processors  and  improves 
parallel  performance. 

T he  two  pipelining  schemes  shown  above  are  but  two  of  the  many  ways 
in  which  the  computation  can  be  pipelined.  As  we  said,  once  a  loop  is  fully 

11.9. 

PIPELINING 

867 

permutable,  we  have  a  lot  of  freedom  in  how  we  wish  to  parallelize  the  code. 
T he  first  pipeline  scheme  maps  iteration 
to  processor  i;  the  second  maps 
to  processor  j.  We  can  create  alternative  pipelines  by  mapping 
iteration 
iteration 
to  processor  CQI  +  cij,  provided  CQ  and  c\  are  positive  constants. 
Such  a  scheme  would  create  pipelines  with  relaxed  wavefronts  between  90°  and 
180°,  b o th  exclusive. 

11.9.5  General  Theory 

T he  example  just  completed  illustrates  the  following  general  theory  underlying 
pipelining:  if  we  can  come  up  with  at  least  two  different  outermost  loops  for  a 
loop  nest  and  satisfy  all  the  dependences,  then  we  can  pipeline  the  computation. 
A  loop  with  k  outermost  fully  permutable  loops  has  k  —  1  degrees  of  pipelined 
parallelism. 

Loops  t h at  cannot  be  pipelined  do  not  have  alternative  outermost  loops. 
Example  11.56  shows  one  such  instance.  To  honor  all  the  dependences,  each 
iteration  in  the  outermost  loop  must  execute  precisely  the  computation  found 
in  the  original  code.  However,  such  code  may  still  contain  parallelism  in  the 
inner  loops,  which  can  be  exploited  by  introducing  at  least n  synchronizations, 
where n  is  the  number  of  iterations  in  the  outermost  loop. 

for  (i  =  0;  i  <  100;  i++)  { 

for  (j  =  0;  j  <  100;  j++) 
X[j]  =  X[j]  +  Y[i,j]; 

Z[i]  =  X[A[i]]; 

/*  (si)  */ 

/*  (s2)  */ 

} 

(a) 

(b) 

Figure  11.53:  A  sequential  outer  loop  (a)  and  its  P DG  (b) 

E x a m p le  1 1. 56  :  Figure  11.53  is  a more  complex  version  of the  problem  we  saw 
in  Example  11.50.  As  shown  in  the  program  dependence  graph  in  Fig.  11.53(b), 
statements  s\  and  s2  belong  to  the  same  strongly  connected  component.  Be 
cause  we  do  not  know  the  contents  of  matrix  A,  we  must  assume  t h at  the 
access  in  statement  s2  may  read  from  any  of the  elements  of  X.  There  is  a  true 
to  statement  s2  and  an  antidependence  from 
dependence  from  statement  si 

868 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

statement  s2  to  statement  sx.  There  is  no  opportunity  for  pipelining  either, 
because  all  operations  belonging  to  iteration  i  in  the  outer  loop  must  precede 
those  in  iteration  i  + 
To  find  more  parallelism,  we  repeat  the  parallelization 
process  on  the  inner  loop.  The  iterations  in  the  second  loop  can  be  parallelized 
without  synchronization.  Thus,  200  barriers  are  needed,  with  one  before  and 
one  after  each  execution  of  the  inner  loop. 

• 

11.9.6  Time-Partition  Constraints 

We  now  focus  on  the  problem  of  finding  pipelined  parallelism.  Our  goal  is  to 
t u rn  a  computation  into  a  set  of pipelinable  tasks.  To  find  pipelined  parallelism, 
we  do  not  solve  directly  for  what  is  to  be  executed  on  each  processor,  like  we 
did  with  loop  parallelization.  Instead,  we  ask  the  following  fundamental  ques 
tion:  W h at  are  all  t he  possible  execution  sequences  t h at  honor  the  original  d a ta 
dependences  in  the  loop?  Obviously  the  original  execution  sequence  satisfies  all 
the  d a ta  dependences.  The  question  is  if  there  are  affine  transformations  t h at 
can  create  an  alternative  schedule,  where  iterations  of  the  outermost  loop  exe 
cute  a  different  set  of  operations  from  the  original,  and  yet  all  the  dependences 
are  satisfied. 
If  we  can  find  such  transforms,  we  can  pipeline  t he  loop.  T he 
key  point  is  t h at  if  there  is  freedom  in  scheduling  operations,  there  is  paral 
lelism;  details  of  how  we  derive  pipelined  parallelism  from  such  transforms  will 
be  explained  later. 

To  find  acceptable  reorderings  of  the  outer  loop,  we  wish  to  find  one-
dimensional  affine  transforms,  one  for  each  statement,  t h at  m ap  the  original 
loop  index  values  to  an  iteration  number  in  the  outermost  loop.  T he  trans 
forms  are  legal  if  t he  assignment  can  satisfy  all  the  d a ta  dependences  in  the 
program.  T he  "time-partition  constraints,"  shown  below,  simply  say  t h at  if 
one  operation  is  dependent  upon  the  other,  then  the  first  must  be  assigned 
an  iteration  in  the  outermost  loop  no  earlier  t h an  t h at  of  the  second.  If  they 
are  assigned  in  the  same  iteration,  then  it  is  understood  t h at  the  first  will  be 
executed  after  t h an  the  second  within  the  iteration. 

An  affine-partition  mapping  of  a  program  is  a  legal-time  partition  if  and  only 

if  for  every  two  (not  necessarily  distinct)  accesses  sharing  a  dependence,  say 

•Fi  =  < F i , f i , B i , b i) 

in  statement  s\,  which  is  nested  in  d\  loops,  and 

T2  = 

( F 2 , f 2 , B 2 , b 2) 

in  statement  s2  nested  in  d2  loops,  t he  one-dimensional  partition  mappings 
( C i , c i)  and  ( C2, c2)  for  statements  si  and  s2,  respectively,  satisfy  the  time-
partition 

constraints: 

•  For  all  ii  in  Zdl  and  i2  in  Zd*  such  t h at 

a) 

ii 

- <S

ls2 

h, 

11.9. 

PIPELINING 

869 

b)  B i ii  + bi  >  0, 

c)  B2i2  +  b2  >  0,  and 

d)  F i ii  +  fi  =  F2i2  +  f2, 

it  is  the  case  t h at  C i ii  +  ci  <  C2i2  +  c2. 

This  constraint,  illustrated  in  Fig.  11.54,  looks  remarkably  similar  to  t he 
space-partition  constraints.  It  is  a  relaxation  of the  space-partition  constraints, 
in  t h at  if two  iterations  refer  to  the  same  location,  they  do  not  necessarily  have 
to  be  m a p p ed  to  the  same  partition;  we  only  require  t h at  the  original  relative 
execution  order  between  t he  two  iterations  is  preserved.  T h at  is,  t he  constraints 
here  have  <  where  the  space-partition  constraints  have  =. 

Array 

Time  steps 

Figure  11.54:  Time-Partition  Constraints 

We  know  t h at  there  exists  at  least  one  solution  to  the  time-partition  con 
straints.  We  can  m ap  operations  in  each  iteration  of  the  outermost  loop  back 
to  t he  same  iteration,  and  all  the  d a ta  dependences  will  be  satisfied.  This  so 
lution  is  t he  only  solution  to  t he  time-partition  constraints  for  programs  t h at 
cannot  be  pipelined.  On  t he  other  hand,  if  we  can  find  several  independent 
solutions  to  time-partition  constraints,  the  program  can  be  pipelined.  Each 
independent  solution  corresponds  to  a  loop  in  the  outermost  fully  permutable 
nest.  As  you  can  expect,  there  is  only  one  independent  solution  to  the  timing 
constraints  extracted  from  the  program  in  Example  11.56,  where  there  is  no 
pipelined  parallelism,  and  t h at  there  are  two  independent  solutions  to  t he  SOR 
code  example. 

E x a m p le  1 1 . 5 7:  Let  us  consider  Example  11.56,  and  in  particular  the  d a ta 
dependences  of  references  to  array  X  in  statements  si  and  s2.  Because  the 

870 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

access  is  not  affine  in  statement  s2,  we  approximate  the  access  by  modeling 
matrix  X  simply  as  a  scalar  variable  in  dependence  analysis  involving  statement 
s2.  Let 
be  the  index  value  of  a  dynamic  instance  of  si  and  let  %'  be  t he 
index  value  of  a  dynamic  instance  of  s2.  Let  t he  computation  mappings  of 
statements  s\,  and  s2  be  ([Cn,C12],c\)  and  ([C2i],C2),  respectively. 

Let  us  first  consider  the  time-partition  constraints  imposed  by  dependences 
from  statement  s\  to  s2.  Thus,  i  <  i',  the  transformed  (i,j)th  iteration  of  si 
must  be  no  later  t h an  t he  transformed  i'th  iteration  of  s2;  t h at  is, 

Cn  C12 

+  ci  <  C2ii'  +  c2. 

Expanding,  we  get 

Cni  +  C12J  +  ci  <  C2i «'  +  c2. 

Since  j  can  be  arbitrarily  large,  independent  of i  and  i',  it  must  be  t h at  C\2  =  0. 
Thus,  one  possible  solution  to  the  constraints  is 

Cn  =  C2\  =  1  and  C\2  =  c\  =  c2  =  0. 

Similar  arguments  about  the  d a ta  dependence  from  s2  to  si  and  s2  back  to 
In  this  particular  solution,  the  zth  iteration 

itself  will  yield  a  similar  answer. 
of  the  outer  loop,  which  consists  of  the  instance  i  of  s2  and  all  instances 
of  si,  are  all  assigned  to  timestep  i.  Other  legal  choices  of  Cn,  C2i,  c i,  and C2 
yield  similar  assignments,  although  there  might  be  timesteps  at  which  nothing 
happens.  T h at  is,  all  ways  to  schedule  the  outer  loop  require  t he  iterations 
to  execute  in  the  same  order  as  in  the  original  code.  This  statement  holds 
whether  all  100  iterations  are  executed  on  t he  same  processor,  on  100  different 
• 
processors,  or  anything  in  between. 

E x a m p le  1 1 . 5 8:  In  t he  SOR  code  shown  in  Fig.  11.50(a),  the  write  reference 
X[j  +  1]  shares  a  dependence  with  itself  and  with  the  three  read  references  in 
the  code.  We  are  seeking  computation  mapping  ([C±,  C2],  c)  for  the  assignment 
statement  such  t h at 

[  Ci  C2  ' 

+  [  c  ]  <  [  d 

C2] 

+ 

[c] 

to 
if there  is  a  dependence  from 
is,  either  i  <  i'  or  (i  =  i'  A  j  <  j')). 

By  definition, 

X 

t h at 

Let  us  consider  three  of  the  pairs  of  d a ta  dependences: 

1.  True  dependence  from  write  access  X[j  + 1]  to  read  access  X[j  +  2].  Since 
the  instances  must  access  the  same  location,  j  +  1  =  j'  +  2  or  j  =  j'  +  1. 
Substituting  j  =  j'  +  1  into  the  timing  constraints,  we  get 

dii' 

-i)-C2 

> 0. 

11.9. 

PIPELINING 

871 

Since  j  =  j'  +  1,  j  >  j ',  the  precedence  constraints  reduce  to  i  <  i'. 
Therefore, 

Ci  -  C2  >  0. 

2.  Antidependence  from  read  access  X[j  +  2]  to  write  access  X[j  +1].  Here, 
j  +  2  =  j'  +  1,  or  j  =  j'  -  1.  Substituting  j  =  j'  —  1  into  the  timing 
constraints,  we  get 

When  i  =  i',  we  get 

C i ( i ' - i)  +  C2  > 0. 

C2> 0. 

W h en  i  <i',  since  C2  >  0,  we  get 

d 

> 0. 

3.  O u t p ut  dependence  from  write  access  X[j  +1]  back  to  itself.  Here  j  =  j '. 

T he  timing  constraints  reduce  to 

C i ( i ' - i)  > 0. 

Since  only  i  <  i'  is  relevant,  we  again  get 

Ci  > 0. 

T he  rest  of  the  dependences  do  not  yield  any  new  constraints. 

In  total, 

there  are  three  constraints: 

Ci  >  0 
C2  >0 
Ci  -  C2  >  0 

Here  are  two  independent  solutions  to  these  constraints: 

"  1" 
0 

'  1" 

1 

I

—

1

T he  first  solution  preserves  t he  execution  order  of  t he  iterations  in  t he  outer 
most  loop.  Both  the  original  SOR  code  in  Fig.  11.50(a)  and  the  transformed 
code  shown  in  Fig.  11.51(a)  are  examples  of  such  an  arrangement.  T he  second 
solution  places  iterations  lying  along  t he  135°  diagonals  in  t he  same  outer  loop. 
The  code  shown  in  Fig.  11.51(b)  is  an  example  of  a  code  with  t h at  outermost 
loop  composition. 

Notice  t h at  there  are  many  other  possible  pairs  of  independent  solutions. 

For  example, 

'  1  ' 
1 

"  2  " 
1 

5 

would  also  be  an  independent  solutions  to  t he  same  constraints.  We  choose  t he 
simplest  vectors  to  simplify  code  transformation. 

• 

 
872 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

11.9.7  Solving  Time-Partition  Constraints  by  Farkas' 

Lemma 

Since  time-partition  constraints  are  similar  to  space-partition  constraints,  can 
we  use  a  similar  algorithm  to  solve  them?  Unfortunately,  t he  slight  difference 
between  the  two  problems  translates  into  a  big  technical  difference  between  the 
two  solution  methods.  Algorithm  11.43  simply  solves  for  C i , c i , C2,  and  c2, 
such  t h at  for  all  ii  in  Zdl  and  i2  in  Zd2  if 

then 

F i ii  +  fi  =  F2i2  +  f2 

C i ii  4-  ci  =  C2i2  4-  c2. 

The  linear  inequalities  due  to  t he  loop  bounds  are  only  used  in  determining  if 
two  references  share  a  d a ta  dependence,  and  are  not  used  otherwise. 

To  find  solutions  to  the  time-partition  constraints,  we  cannot  ignore  the 
linear  inequalities  i  -<  i';  ignoring  them  often  would  allow  only  the  trivial  so 
lution  of  placing  all  iterations  in  the  same  partition.  Thus,  t he  algorithm  to 
find  solutions  to  the  time-partition  constraints  must  handle  b o th  equalities  and 
inequalities. 

The  general  problem  we  wish  to  solve  is:  given  a  m a t r ix  A,  find  a  vector 

c  such  t h at  for  all  vectors  x  such  t h at  Ax  >  0,  it  is  the  case  t h at  cTx  >  0. 
In  other  words,  we  are  seeking  c  such  t h at  the  inner  product  of  c  and  any 
coordinates  in  t he  polyhedron  defined  by  t he  inequalities  Ax  >  0  always  yields 
a  nonnegative  answer. 

This  problem  is  addressed  by  Farkas'  Lemma.  Let  A  be  an  m  x  n  matrix 
of  reals,  and  let  c  be  a  real,  nonzero  n-vector.  Farkas'  lemma  says  t h at  either 
the  primal  system  of  inequalities 

Ax  >  0, 

cTx  <  0 

has  a  real-valued  solution  x,  or  the  dual  system 

ATy  =  c, 

y  >  0 

has  a  real-valued  solution  y,  but  never  both. 

The  dual  system  can  be  handled  by  using  Fourier-Motzkin  elimination  to 
project  away  t he  variables  of  y.  For  each  c  t h at  has  a  solution  in  t he  dual 
system,  the  lemma  guarantees  t h at  there  are  no  solutions  to  the  primal  system. 
P ut  another  way,  we  can  prove  the  negation  of  t he  primal  system,  i.e.,  we  can 
prove  t h at  cTx  >  0  for  all  x  such  t h at  Ax  >  0,  by  finding  a  solution  y  to  the 
dual  system:  ATy  =  c  and  y  >  0. 

A l g o r i t hm  1 1 . 5 9:  Finding  a  set  of  legal,  maximally  independent  affine  time-
partition  mappings  for  an  outer  sequential  loop. 

11.9. 

PIPELINING 

873 

About  Farkas'  Lemma 

T he  proof  of  t he  lemma  can  be  found  in  many  standard  texts  on  linear 
programming.  Farkas'  Lemma,  originally  proved  in  1901,  is  one  of  the 
theorems  of  the  alternative.  These  theorems  are  all  equivalent  but,  despite 
a t t e m p ts  over  the  years,  a  simple,  intuitive  proof for  this  lemma  or  any  of 
its  equivalents  has  not  been  found. 

INPUT:  A  loop  nest  with  array  accesses. 

OUTPUT:  A  maximal  set  of  linearly  independent  time-partition  mappings. 

METHOD:  T he  following  steps  constitute  the  algorithm: 

1.  Find  all  data-dependent  pairs  of  accesses  in  a  program. 

2.  For  each  pair  of  data-dependent  accesses,  T\  =  ( F i, f i, B i, b i)  in  state 
ment  si  nested  in  d\  loops  and  T2  —  ( F2,  f2,  B2,  b2)  in  statement  s2  nested 
in  d2  loops,  let  ( C i, C i)  and  ( C2, c2)  be  the  (unknown)  time-partition 
mappings  of  statements  si  and  s2,  respectively.  Recall  the  time-partition 
constraints  state  t h at 

•  For  all  ii  in  Zdl  and  i2  in  Zd2  such  t h at 

a) 

ii 

- < s i s2 

h, 

b)  B Ji  + bi  >  0, 

c)  B2i2  +  b2  >  0,  and 

d)  F1i1+ f1= F2i2+ f2, 

it  is  the  case  t h at  C i ii  +  ci  <  C2i2  +  c2. 

Since  ii  -<gl S2  h  is  a  disjunctive  union  of  a  number  of  clauses,  we  can 
create  a  system  of  constraints  for  each  clause  and  solve  each  of  t h em 
separately,  as  follows: 

(a)  Similarly  to  step  (2a)  in  Algorithm  11.43,  apply  Gaussian elimination 

to  the  equations 

Fiii  +  fi  =  F2i2  +  f2 

to  reduce  the  vector 

ii 
h 
1 

to  some  vector  of  unknowns,  x. 

874 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

(b)  Let  c  be  all  the  unknowns  in  the  partition  mappings.  Express  t he 
linear  inequality  constraints  due  to  t he  partition  mappings  as 

cTDx  >  0 

for  some  matrix  D. 

(c)  Express  the  precedence  constraints  on  t he  loop  index  variables  and 

t he  loop  bounds  as 

for  some  matrix  A. 

Ax  >  0 

(d)  Apply  F a r k a s ' L e m m a.  Finding  x  to  satisfy  the  two  constraints  above 

is  equivalent  to  finding  y  such  t h at 

ATy  =  DTc  and  y  >  0. 

Note  t h at  cTD  here  is  cT  in  the  statement  of  Farkas'  Lemma,  and 
we  are  using  the  negated  form  of  the  lemma. 

(e)  In  this  form,  apply  Fourier-Motzkin  elimination  to  project  away  the  y 
variables,  and  express  the  constraints  on  the  coefficients  c  as  Ec  >  0. 

(f)  Let  E'c'  >  0  be  the  system  without  t he  constant  terms. 

3.  Find  a  maximal  set  of  linearly  independent  solutions  to  E'c'  >  0  using 
Algorithm  B.I  in  Appendix  B.  T he  approach  of  t h at  complex  algorithm 
is  to  keep  track  of  t he  current  set  of  solutions  for  each  of  t he  statements, 
then  incrementally  look  for  more  independent  solutions  by  inserting  con 
straints  t h at  force  the  solution  to  be  linearly  independent  for  at  least  one 
statement. 

4.  From  each  solution  of  c'  found,  derive  one  affine  time-partition  mapping. 

The  constant  terms  are  derived  using  Ec  >  0. 

• 

E x a m p le  1 1 . 6 0:  T he  constraints  for  Example  11.57  can  be  written  as 

[  -Cn 

- C i2 

C2i 

(c2  -  ci)  ] 

>  0 

[  -1  0  1  0  ] 

>  0 

11.9. 

PIPELINING 

875 

Farkas'  lemma  says  t h at  these  constraints  are  equivalent  to 

"  - 1" 
0 
1 
0 

[ *]  = 

—Cn 
— C\2 
C21 
_  c2  -  Ci 

Solving  this  system,  we  get 

Cn  =  C21  >  0  and  C12  =  c2  -  ci  =  0. 

Notice  t h at  these  constraints  are  satisfied  by  the  particular  solution  we  obtained 
in  Example  11.57. 

• 

11.9.8  Code  Transformations 

If  there  exist  k  independent  solutions  to  t he  time-partition  constraints  of  a  loop 
nest,  then  it  is  possible  to  transform  the  loop  nest  to  have  k  outermost  fully 
permutable  loops,  which  can  be  transformed  to  create  k—1  degrees  of pipelining, 
or  to  create  k — 1  inner  parallelizable  loops.  Furthermore,  we  can  apply  blocking 
to  fully  permutable  loops  to  improve  d a ta  locality  of  uniprocessors  as  well  as 
reducing  synchronization  among  processors  in  a  parallel  execution. 

E x p l o i t i ng  F u l ly  P e r m u t a b le  L o o ps 

We  can  create  a  loop  nest  with  k  outermost  fully  permutable  loops  easily  from 
k  independent  solutions  to  the  time-partition  constraints.  We  can  do  so  by 
simply  making  the  kth.  solution  the  kih  row  of  t he  new  transform.  Once  t he 
affine  transform  is  created,  Algorithm  11.45  can  be  used  to  generate  t he  code. 

E x a m p le  1 1 . 6 1:  The  solutions  found  in  Example  11.58  for  our  SOR  example 
were 

"  1  " 
0 

"  1  " 
1 

Making  the  first  solution  the  first  row  and  the  second  solution  the  second  row, 
we  get  t he  transform 

'1  0  " 
1 

1 

which  yields  the  code  in  Fig.  11.51(a). 

Making  t he  second  solution  the  first  row  instead,  we  get  the  transform 

"1 
1 

1  ' 
0 

which  yields  the  code  in  Fig.  11.51(c). 

• 

876 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

It  is  easy  to  see  t h at  such  transforms  produce  a  legal  sequential  program. 
T he  first  row  partitions  the  entire  iteration  space  according  to  the  first  solution. 
The  timing  constraints  guarantee  t h at  such  a  decomposition  does  not  violate 
any  d a ta  dependences.  Then,  we  partition  the  iterations  in  each  of  t he  outer 
most  loop  according to  the  second  solution.  Again  this  must  be  legal  because  we 
are  dealing  with  just  subsets  of  the  original  iteration  space.  T he  same  goes  for 
the  rest  of  the  rows  in  the  matrix.  Since  we  can  order  t he  solutions  arbitrarily, 
the  loops  are  fully  permutable. 

E x p l o i t i ng  P i p e l i n i ng 

We  can  easily  transform  a  loop  with  k  outermost  fully  permutable  loops  into  a 
code  with  k  —  1  degrees  of  pipeline  parallelism. 

E x a m p le  1 1 . 6 2:  Let  us  return  to  our  SOR  example.  After  the  loops  are 
transformed  to  be  fully  permutable,  we  know  t h at  iteration  [k,  i2]  can  be  exe 
cuted  provided  iterations  [k,k  —  1]  and  [k  —  1,^]  have  been  executed.  We  can 
guarantee  this  order  in  a  pipeline  as  follows.  We  assign  iteration  k  to  processor 
pi.  Each  processor  executes  iterations  in  t he  inner  loop  in  the  original  sequen 
tial  order,  thus  guaranteeing  t h at  iteration  [k,i2]  executes  after  [ii,i2  —  1].  In 
addition,  we  require  t h at  processor  p  waits  for  the  signal  from  processor  p  —  1 
t h at  it  has  executed  iteration  [p  —  l,i2]  before  it  executes  iteration  [p,«V|.  This 
technique  generates  the  pipelined  code  Fig.  11.52(a)  and  (b)  from  t he  fully 
permutable  loops  Fig.  11.51(a)  and  (c),  respectively. 

• 

In  general,  given  k  outermost  fully  permutable  loops,  the  iteration  with 
,ik)  can  be  executed  without  violating  data-dependence 

index  values 
(ii,... 
constraints,  provided  iterations 

[k  -l,i2,..- 

[«i,«2  -  1, « 3, •  •  •  ,ik],  •  •  •  , [k, •  •  •  ,ik-i,h  -  1] 

have  been  executed.  We  can  thus  assign  the  partitions  of the  first  k  —  1  dimen 
sions  of  the  iteration  space  to  0 ( nf e _ 1)  processors  as  follows.  Each  processor  is 
responsible  for  one  set  of iterations  whose  indexes  agree  in  the  first  k — 1  dimen 
sions,  and  vary  over  all  values  of  the  kth  index.  Each  processor  executes  t he 
iterations  in  the  kth  loop  sequentially.  T he  processor  corresponding  to  values 
[ p i , p2,  •  •  •  ,Pk-i]  for  t he  first  k  —  1  loop  indexes  can  execute  iteration  i  in  the 
feth  loop  as  long  as  it  receives  a  signal  from  processors 

[pi  -  l,p2,  •  •  •  ,Pk-l],  •••  ,  [Pi,  •  •  •  , P f c- 2, P * -l  -  1] 

t h at  they  have  executed  their  ith  iteration  in  the  kth  loop. 

Wavefr ont  i ng 

It  is  also  easy  to  generate  k  —  1  inner  parallelizable  loops  from  a  loop  with  k 
outermost  fully  permutable  loops.  Although  pipelining  is  preferable,  we  include 
this  information  here  for  completeness. 

11.9. 

PIPELINING 

877 

We  partition  t he  computation  of  a  loop  with  k  outermost  fully  permutable 
loops  using  a  new  index  variable  i':  where  i'  is  defined  to  be  some  combination 
of  all  the  indices  in  the  k  permutable  loop  nest.  For  example,  i'  =  i±  +  ...  +  ik 
is  one  such  combination. 

We  create  an  outermost  sequential  loop  t h at  iterates  through  t he  i'  par 
titions  in  increasing  order;  the  computation  nested  within  each  partition  is 
ordered  as  before.  The  first  k  -  1  loops  within  each  partition  are  guaranteed 
to  be  parallelizable.  Intuitively,  if  given  a  two-dimensional  iteration  space,  this 
transform  groups  iterations  along  135°  diagonals  as  an  execution  of  t he  outer 
most  loop.  This  strategy  guarantees  t h at  iterations  within  each  iteration  of t he 
outermost  loop  have  no  d a ta  dependence. 

B l o c k i ng 

A  k-deep,  fully  permutable  loop  nest  can  be  blocked  in  ^-dimensions.  Instead 
of  assigning  t he  iterations  to  processors  based  on  t he  value  of t he  outer  or  inner 
loop  indexes,  we  can  aggregate  blocks  of  iterations  into  one  unit.  Blocking  is 
useful  for  enhancing  d a ta  locality  as  well  as  for  minimizing  the  overhead  of 
pipelining. 

Suppose  we  have  a  two-dimensional  fully  permutable  loop  nest,  as  in  Fig. 
11.55(a),  and  we  wish  to  break the  computation  into  b x b  blocks.  The  execution 
order  of  the  blocked  code  is  shown  in  Fig.  11.56,  and  the  equivalent  code  is  in 
Fig.  11.55(b). 

If we  assign  each  block  to  one  processor,  then  all  the  passing  of d a ta from  one 
iteration  to  another  t h at  is  within  a  block  requires  no  interprocessor  communi 
cation.  Alternatively,  we  can  coarsen  the  granularity  of  pipelining  by  assigning 
a  column  of  blocks  to  one  processor.  Notice  t h at  each  processor  synchronizes 
with  its  predecessors  and  successors  only  at  block  boundaries.  Thus,  another 
advantage  of  blocking  is  t h at  programs  only  need  to  communicate  d a ta  ac 
cessed  at  the  boundaries  of  the  block  with  their  neighbor  blocks.  Values  t h at 
are  interior  to  a  block  are  managed  by  only  one  processor. 

E x a m p le  1 1 . 6 3:  We  now  use  a  real  numerical  algorithm  —  Cholesky  decom 
position  —  to  illustrate  how  Algorithm  11.59  handles  single  loop  nests  with  only 
pipelining  parallelism.  T he  code,  shown  in  Fig.  11.57,  implements  an  0 ( n3)  al 
gorithm,  operating  on  a  2-dimensional  d a ta  array.  The  executed  iteration  space 
is  a  triangular  pyramid,  since  j  only  iterates  up  to  the  value  of  the  outer  loop 
index  i,  and  k  only  iterates  to  the  value  of j.  The  loop  has  four  statements,  all 
nested  in  different  loops. 

Applying  Algorithm  11.59  to  this  program  finds  three  legitimate  time  di 
mensions.  It  nests  all  the  operations,  some  of  which  were  originally  nested  in 
1-  and  2-deep  loop  nests  into  a  3-dimensional,  fully  permutable  loop  nest.  The 
code,  together  with  the  mappings,  is  shown  in  Fig.  11.58. 

The  code-generation  routine  guards  the  execution  of the  operations  with  the 
original  loop  bounds  to  ensure  t h at  the  new  programs  execute  only  operations 

878 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

f or 

( i = 0; 

i < n; 

i++) 

j < n; 

{ 

f or  ( j = l; 
<S> 

} 

(a)  A  simple  loop  nest. 

f or  ( ii  =  0; 

i i < n; 

i+=b) 

f or 

( jj  =  0; 
f or  (i  = 

j j < n; 

j j + = b) 

i i * b; 

i  <=  m i n ( i i * b - l,  n ); 

i++) 

f or  (j  =  i i * b; 

j  <=  m i n ( j j * b - l,  n ); 

{ 

<S> 

} 

(b)  A  blocked  version  of  this  loop  nest. 

Figure  11.55:  A  2-dimensional  loop  nest  and  its  blocked  version 

(a) Before. 

(b)  After. 

Figure  11.56:  Execution  order  before  and  after  blocking  a  2-deep  loop  nest. 

9. 

PIPELINING 

for  (i =  1;  i  <= N;  i++)  { 

for  (j  =  1;  j  <= i-1;  j++)  { 

for  (k  =  1;  k  <=  j-1;  k++) 

X[i,j]  = X[i,j]  - X[i,k]  * X [ j , k ]; 

X[i,j]  = X[i,j]  / X[j,j]; 

} 
for  (m =  1;  m <=  i-1;  m++) 

X[i,i]  = X[i,i]  " X[i,m]  * X [ ism ]; 

X[i,i]  = sqrt(X[i,i]); 

Figure 11.57: Cholesky decomposition 

for  (i2 =  1;  i2  <= N;  i2++) 

for  (j2 =  1;  j2 <= i2;  J2++)  { 

/*  beginning of  code  for processor  (i2,j2)  */ 
for  (k2 =  1;  k2  <=  i2;  k2++)  { 

// Mapping:  i2 =  i,  j2 = j,  k2 = k 
if  (j2<i2  kk  k2<j2) 

X[i2,j2]  = X[i2,j2]  - X[i25k2]  * X[j2,k2]; 

// Mapping:  i2 =  i,  j2 = j ,  k2 = j 
if  (j2==k2  kk  j2<i2) 

X[i2,j2] = X[i2,j2]  / X[j2,j2] ; 

//  Mapping:  i 2 = i,  j 2 = i,  k 2 =m 
if  (i2==j2  kk  k2<i2) 

X[i2,i2]  = X[i2,i2]  - X[i2,k2]  * X[i2,k2]; 

//  Mapping:  i 2 = i,  j 2 = i,  k 2 =i 
if  (i2==j2  kk  j2==k2) 

X[k2,k2]  = sqrt(X[k2,k2]); 

} 

/*  ending of  code  for processor  (i2,j2)  */ 

Figure 11.58: Figure 11.57 written as a fully permutable loop nest 

880 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

t h at  are  in  the  original  code.  We  can  pipeline  this  code  by  mapping  the  3-
dimensional  structure  to  a  2-dimensional  processor  space.  Iterations  (i2,j2,  k2) 
are  assigned  to  the  processor  with  ID  (i2,j2).  Each  processor  executes  t he 
innermost  loop,  the  loop  with  the  index  k2.  Before  it  executes  t he  kth  iteration, 
the  processor  waits  for  signals  from  the  processors  with  ID's  (%2  —  l,j2)  and 
(i2,j2  -  1).  After  it  executes  its  iteration,  it  signals  processors  (12  +  l , j 2)  and 
(*2,j2  +  l ). 

• 

11.9.9  Parallelism  With  Minimum  Synchronization 

We  have  described  three  powerful  parallelization  algorithms  in  the  last  three 
sections:  Algorithm  11.43  finds  all  parallelism  requiring  no  synchronizations, 
Algorithm  11.54  finds  all  parallelism  requiring  only  a  constant  number  of  syn 
chronizations,  and  Algorithm  11.59  finds  all  the  pipelinable  parallelism  requir 
ing  0(n)  synchronizations  where  n  is  the  number  of  iterations  in  t he  outermost 
loop.  As  a  first  approximation,  our  goal  is  to  parallelize  as  much  of the  compu 
tation  as  possible,  while  introducing  as  little  synchronization  as  necessary. 

Algorithm  11.64,  below,  finds  all  the  degrees  of  parallelism  in  a  program, 
starting  with  the  coarsest  granularity  of parallelism.  In  practice,  to  parallelize  a 
code  for  a  multiprocessor,  we  do  not  need  to  exploit  all  the  levels  of parallelism, 
just  the  outermost  possible  ones  until  all  the  computation  is  parallelized  and 
all  the  processors  are  fully  utilized. 

A l g o r i t hm  1 1 . 6 4:  Find  all  the  degrees  of  parallelism  in  a  program,  with  all 
the  parallelism  being  as  coarse-grained  as  possible. 

INPUT:  A  program  to  be  parallelized. 

OUTPUT:  A  parallelized  version  of  t he  same  program. 

METHOD:  Do  the  following: 

1.  Find  the  maximum  degree  of  parallelism  requiring  no  synchronization: 

Apply  Algorithm  11.43  to  t he  program. 

2.  Find  the  maximum  degree  of  parallelism  t h at  requires  0 ( 1)  synchroniza 
tions:  Apply  Algorithm  11.54  to  each  of  the  space  partitions  found  in 
step  1.  (If no  synchronization-free  parallelism  is  found,  t he  whole  compu 
tation  is  left  in  one  partition). 

3.  Find  the  maximum  degree  of  parallelism  t h at  requires  0(n)  synchroniza 
tions.  Apply  Algorithm  11.59  to  each  of  t he  partitions  found  in  step  2 
to  find  pipelined  parallelism.  Then  apply  Algorithm  11.54  to  each  of  the 
partitions  assigned  to  each  processor,  or  t he  body  of  t he  sequential  loop 
if  no  pipelining  is  found. 

4.  Find  the  maximum  degree  of parallelism  with  successively  greater  degrees 
of  synchronizations:  Recursively  apply  Step  3  to  computation  belonging 
to  each  of  t he  space  partitions  generated  by  the  previous  step. 

11.9. 

PIPELINING 

• 

881 

E x a m p le  1 1 . 6 5:  Let  us  now  return  to  Example  11.56.  No  parallelism  is 
found  by  Steps  1  and  2  of  Algorithm  11.54;  t h at  is,  we  need  more  t h an  a 
constant  number  of synchronizations to  parallelize this  code.  In  Step  3,  applying 
Algorithm  11.59  determines  t h at  there  is  only  one  legal  outer  loop,  which  is  the 
one  in  t he  original  code  of Fig.  11.53.  So,  the  loop  has  no  pipelined  parallelism. 
In  the  second  part  of  Step  3,  we  apply  Algorithm  11.54  to  parallelize  the  inner 
loop.  We  treat  the  code  within  a  partition  like  a  whole  program,  the  only 
difference  being  t h at  the  partition  number  is  treated  like  a  symbolic  constant. 
In  this  case  the  inner  loop  is  found  to  be  parallelizable  and  therefore  the  code 
can  be  parallelized  with  n  synchronization  barriers. 

• 

Algorithm  11.64  finds  all  t he  parallelism  in  a  program  at  each  level  of  syn 
chronization.  T he  algorithm  prefers  parallelization  schemes  t h at  have  less  syn 
chronization,  but  less  synchronization  does  not  mean  t h at  the  communication 
is  minimized.  Here  we  discuss  two  extensions  to  the  algorithm  to  address  its 
weaknesses. 

C o n s i d e r i ng  C o m m u n i c a t i on  C o st 

Step  2  of  Algorithm  11.64  parallelizes  each  strongly  connected  component  in 
dependently  if  no  synchronization-free  parallelism  is  found.  However,  it  may 
be  possible  to  parallelize  a  number  of  the  components  without  synchronization 
and  communication.  One  solution  is  to  greedily  find  synchronization-free  par 
allelism  among  subsets  of  the  program  dependence  graph  t h at  share  the  most 
data. 

If  communication  is  necessary  between  strongly  connected  components,  we 
note  t h at  some  communication  is  more  expensive  t h an  others.  For  example, 
the  cost  of transposing  a  matrix  is  significantly  higher  t h an  just  having  to  com 
municate  between  neighboring  processors.  Suppose  si  and  s2  are  statements  in 
two  separate  strongly  connected  components  accessing  the  same  d a ta  in  itera 
tions  ii  and  i2,  respectively.  If  we  cannot  find  partition  mappings  ( C i , c i)  and 
( C2, c2)  for  statements  si  and  s2,  respectively,  such  t h at 

C i ii  +  ci  -  C2i2  +  c2  =  0, 

we  instead  try  to  satisfy  the  constraint 

C i ii  +  ci  -  C2i2  +  c2  <  6 

where  S  is  a  small  constant. 

T r a d i ng  C o m m u n i c a t i on  for  S y n c h r o n i z a t i on 

Sometimes  we  would  rather  perform  more  synchronizations  to  minimize  com 
munication.  Example  11.66  discusses  one  such  example.  Thus,  if  we  cannot 

882 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

parallelize  a  code  with  just  neighborhood  communication  among  strongly  con 
nected  components,  we  should  a t t e m pt  to  pipeline  t he  computation  instead 
of  parallelizing  each  component  independently.  As  shown  in  Example  11.66, 
pipelining  can  be  applied  to  a  sequence  of  loops. 

E x a m p le  1 1 . 6 6:  For  t he  ADI  integration  algorithm  in  Example  11.49,  we 
have  shown  t h at  optimizing  the  first  and  second  loop  nests  independently  finds 
parallelism  in  each  of  t he  nests.  However,  such  a  scheme  would  require  t h at 
If 
the  matrix  be  transposed  between  t he  loops,  incurring  0 ( n2)  d a ta  traffic. 
we  use  Algorithm  11.59  to  find  pipelined  parallelism,  we  find  t h at  we  can  t u rn 
the  entire  program  into  a  fully  permutable  loop  nest,  as  in  Fig.  11.59.  We  then 
can  apply  blocking  to  reduce  the  communication  overhead.  This  scheme  would 
• 
incur  0(n)  synchronizations  b ut  would  require  much  less  communication. 

f or  (j  =  0; 

f or  (i  =  1; 

j  <  n; 

j + +) 
i  <  n + 1; 

i++)  { 
(i  <  n)  X[ i , j]  =  f( X[ i , j]  +  X[ i - l , j ]) 
(j  >  0)  X[ i - l , j]  =  g( X[ i - l , j] , X[ i - l , j - l ] ); 

if 
if 

} 

Figure  11.59:  A  fully  permutable  loop  nest  for  the  code  of  Example  11.49 

11.9.10  Exercises  for  Section  11.9 

E x e r c i se  1 1 . 9 , 1:  In  Section  11.9.4,  we  discussed  the  possibility  of  using  di 
agonals  other  t h an  the  horizontal  and  vertical  axes  to  pipeline  t he  code  of 
Fig.  11.51.  Write  code  analogous  to  the  loops  of  Fig.  11.52  for  the  diagonals: 
(a)  135°  (b)  120°. 

E x e r c i se  1 1 . 9 . 2:  Figure  11.55(b)  can  be  simplified  if  b  divides  n  evenly. 
Rewrite  the  code  under  t h at  assumption. 

for  (i=0;  i<100;  i++)  { 

P[i,0]  =  1;  /* si */ 
P[i,i]  =  1;  /* s2 */ 

} 
for  (i=2;  i<100;  i++) 

for  (j=l;  j<i;  j++) 

P[i,j]  = P[i-l,j-l]  + P[i-l,j];  /*  s3  */ 

Figure  11.60:  Computing  Pascal's  triangle 

11.9. 

PIPELINING 

883 

E x e r c i se  1 1 . 9 . 3:  In  Fig.  11.60  is  a  program  to  compute  the  first  100  rows  of 
Pascal's  triangle.  T h at  is,  P[i,j]  will  become  the  number  of  ways  to  choose  j 
things  out  of  i,  for  0  <  j  <  i  <  100. 

a)  Rewrite  the  code  as  a  single,  fully  permutable  loop  nest. 

b)  Use  100 processors in  a pipeline to implement  this  code.  Write t he  code for 
each  processor p,  in  terms  of p,  and  indicate  the  synchronization  necessary. 

c)  Rewrite  the  code  using  square  blocks  of  10  iterations  on  a  side.  Since  the 
h  10  =  55  blocks. 

iterations  form  a  triangle,  there  will  be  only  1  +  2-1 
Show  the  code  for  a  processor  ( p i, P 2)  assigned  to  the  p i th  block  in  the  i 
direction  and  the  p2th  block  in  the  j  direction,  in  terms  of pi  and  p2. 

f or  ( i = 0; 

i < 1 0 0;  1++)  { 

A [ i,  0 , 0]  =  B l [ i]  ; 
A [ i , 9 9 , 0]  =  B 2 [ i]  ; 

/*  si  */ 
/*  s2  */ 

} 
f or 

j < 9 9; 

( j = l; 
j++)  { 
A[  0 , j , 0]  =  B 3 [ j]  ; 
A C 9 9 , j , 0]  =  B 4 [ j]  ; 

/*  s3  */ 
/*  s4  */ 

} 
f or  ( i = 0; 

i < 9 9; 

i++) 

f or 

( j = 0; 
f or 

j < 9 9; 

j++) 

( k = l;  k<100;  k++) 
A C i , j , k]  =  ( 4 * A [ i , j , k - l]  +  A C i - l , j , k - l]  + 

A C i + l , j , k - l]  +  A C i , j - l , k - l]  + 
A [ i, j + l , k - l ]; 

/*  s5  */ 

Figure  11.61:  Code  for  Exercise  11.9.4 

!  E x e r c i se  1 1 . 9 . 4:  Repeat  Exercise  11.9.2  for  the  code  of  Fig.  11.61.  However, 
note  t h at  the  iterations  for  this  problem  form  a  3-dimensional  cube  of  side  100. 
Thus,  t he  blocks  for  p a rt  (c)  should  be  10  x  10  x  10,  and  there  are  1000  of them. 

!  E x e r c i se  1 1 . 9 . 5:  Let  us  apply  Algorithm  11.59  to  a  simple  example  of  the 

time-partition  constraints.  In  what  follows,  assume  t h at  the  vector  ii  is 
and  vector  i2  is  (i2,j2); 
condition  ii  -<Sls2  *2  consists  of  the  following  disjunction: 

technically,  b o th  these  vectors  are  transposed.  T he 

i.  i\  <  z2,  or 

ii. 

ii=  i2  and  ji  <  j2. 

T he  other  equalities  and  inequalities  are 

884 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

2 n + j ' i - 10 
i2  +  2j2  -  20 
h 
h 

> 
0 
>  o 
= 
= 

h  +  h  ~  50 
h  +  40 

Finally,  the  time-partition  inequality,  with  unknowns  c\,  d\,  e\,  c2,  d2,  and  e2, 
is 

cih  +  diji  +  ei  <  c2i2  +  d2j2  +  e2. 

a)  Solve  the  time-partition  constraints  for  case  i  —  t h at  is,  where  i\  <  i2.  In 
particular,  eliminate  as  many  of  i\,  j±,  i2,  and  j2  as  you  can,  and  set  up 
the  matrices  D  and  A  as  in  Algorithm  11.59.  Then,  apply  Farkas'  Lemma 
to  the  resulting  matrix  inequalities. 

b)  Repeat  part  (a)  for  the  case  ii,  where  i\  —  i2  and  ji  <  j2. 

11.10  Locality  Optimizations 

The  performance  of  a  processor,  be  it  a  part  of  a  multiprocessor  or  not,  is 
highly  sensitive  to  its  cache  behavior.  Misses  in  the  cache  can  take  tens  of clock 
cycles,  so  high  cache-miss  rates  can  lead  to  poor  processor  performance.  In  the 
context  of  a  multiprocessor  with  a  common  memory  bus,  contention  on  t he  bus 
can  further  add  to  t he  penalty  of  poor  d a ta  locality. 

As  we  shall  see,  even  if we just  wish  to  improve  t he  locality  of uniprocessors, 
the  affine-partitioning  algorithm  for  parallelization  is  useful  as  a  means  of  iden 
tifying  opportunities  for  loop  transformations.  In  this  section,  we  describe  three 
techniques  for  improving  d a ta  locality  in  uniprocessors  and  multiprocessors. 

1.  We  improve  the  temporal  locality  of computed  results  by  trying  to  use  the 
results  as  soon  as  they  are  generated.  We  do  so  by  dividing  a  computation 
into  independent  partitions  and  executing  all  the  dependent  operations  in 
each  partition  close  together. 

2.  Array  contraction  reduces  the  dimensions  of  an  array  and  reduces  t he 
number  of memory  locations  accessed.  We  can  apply  array  contraction  if 
only  one  location  of  the  array  is  used  at  a  given  time. 

3.  Besides  improving  temporal  locality  of  computed  results,  we  also  need 
to  optimize  for  the  spatial  locality  of  computed  results,  and  for  b o th  the 
temporal  and  spatial  locality  of  read-only  data.  Instead  of  executing  each 
partition  one  after  t he  other,  we  interleave  a  number  of  the  partitions  so 
t h at  reuses  among  partitions  occur  close  together. 

11.10. 

LOCALITY  OPTIMIZATIONS 

885 

11.10.1  Temporal  Locality  of  Computed  Data 

The  affine-partitioning  algorithm  pulls  all  the  dependent  operations  together; 
by  executing  these  partitions  serially  we  improve  temporal  locality  of computed 
data.  Let  us  return  to  t he  multigrid  example  discussed  in  Section  11.7.1.  Ap 
plying  Algorithm  11.43  to  parallelize  the  code  in  Fig  11.23  finds  two  degrees 
of  parallelism.  The  code  in  Fig  11.24  contains  two  outer  loops  t h at  iterate 
through  the  independent  partitions  serially.  This  transformed  code  has  im 
proved  temporal  locality,  since  computed  results  are  used  immediately  in  the 
same  iteration. 

Thus,  even  if  our  goal  is  to  optimize  for  sequential  execution,  it  is  profitable 
to  use  parallelization  to  find  these  related  operations  and  place  t h em  together. 
T he  algorithm  we  use  here  is  similar  to  t h at  of  Algorithm  11.64,  which  finds  all 
the  granularities  of  parallelism  starting  with  the  outermost  loop.  As  discussed 
in  Section  11.9.9,  the  algorithm  parallelizes  strongly  connected  components  in 
dividually,  if we  cannot  find  synchronization-free  parallelism  at  each  level.  This 
parallelization  tends  to  increase  communication.  Thus,  we  combine  separately 
parallelized  strongly  connected  components  greedily,  if  they  share  reuse. 

11.10.2  Array  Contraction 

The  optimization  of array  contraction  provides  another  illustration  of the  trade 
off between  storage  and  parallelism,  which  was  first  introduced  in  the  context  of 
instruction-level  parallelism  in  Section  10.2.3.  Just  as  using  more  registers  al 
lows  for  more  instruction-level  parallelism,  using  more  memory  allows  for  more 
loop-level  parallelism.  As  shown  in  the  multigrid  example  in  Section  11.7.1, 
expanding  a  temporary  scalar  variable  into  an  array  allows  different  iterations 
to  keep  different  instances  of  the  temporary  variables  and  to  execute  at  the 
same  time.  Conversely,  when  we  have  a  sequential  execution  t h at  operates  on 
one  array  element  at  a  time  serially,  we  can  contract  the  array,  replace  it  with 
a  scalar,  and  have  each  iteration  use  the  same  location. 

In  the  transformed  multigrid  program  shown  in  Fig.  11.24,  each  iteration  of 
the  inner  loop  produces  and  consumes  a  different  element  of  AP,  AM,  T,  and  a 
row  of D.  If these  arrays  are  not  used  outside  of the  code  excerpt,  t he  iterations 
can  serially  reuse  the  same  d a ta  storage  instead  of putting  the  values  in  different 
elements  and  rows,  respectively.  Figure  11.62  shows  t he  result  of  reducing  t he 
dimensionality  of  the  arrays.  This  code  runs  faster  t h an  the  original,  because 
it  reads  and  writes  less  data.  Especially  in  t he  case  when  an  array  is  reduced 
to  a  scalar  variable,  we  can  allocate  the  variable  to  a  register  and  eliminate  the 
need  to  access  memory  altogether. 

As  less  storage  is  used,  less  parallelism  is  available.  Iterations  in  the  trans 
formed  code  in  Fig.  11.62  now  share  d a ta  dependences  and  no  longer  can  be 
executed  in  parallel.  To  parallelize  the  code  on  P  processors,  we  can  expand 
each  of  the  scalar  variables  by  a  factor  of  P  and  have  each  processor  access 
its  own  private  copy.  Thus,  the  amount  by  which  the  storage  is  expanded  is 

886 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

for  (j  = 2,  j  <= jl,  j++) 

for  (i = 2,  i  <=  il,  i++)  { 

AP 

T 

= 1.0/(1.0 + A P ); 

D[2] 

=  T*AP; 

DW[l,2,j,i] = T*DW[l,2,j,i]; 

for  (k=3,  k <= kl-1,  k++)  { 

AM 

AP 

T 

=  AP; 

=  ...; 

= . . .AP -AM*D[k-l] . . . ; 

D[k] 

=  T*AP; 

DW[l,k,j,i]  = T*(DW[l,k,j,i]+DW[l,k-l,j,i])...; 

} 

for  (k=kl-l,  k>=2,  k —) 

DW[l,k,j,i] = DW[l,k,j,i] +D[k] *DW[1 ,k+l, j ,i] ; 

} 

Fi  gure 11.62:  Code  of  Fig. 11.23  after  partitioning  (Fig. 11.24)  and  array  con 
traction 

directly  correlated  to  t he  amount  of  parallelism  exploited. 

There  are  three  reasons  it  is  common  to  find  opportunities  for  array  con 

traction: 

1.  Higher-level  programming  languages  for  scientific  applications,  such  as 
Matlab  and  Fortran 90,  support  array-level  operations.  Each  subexpres 
sion  of  array  operations  produces  a  temporary  array.  Because  the  arrays 
can  be  large,  every  array  operation  such  as  a  multiply  or  add  would  require 
reading  and  writing  many  memory  locations,  while  requiring  relatively  few 
arithmetic  operations.  It  is  important  t h at  we  reorder  operations  so  t h at 
d a ta  is  consumed  as  it  is  produced  and  t h at  we  contract  these  arrays  into 
scalar  variables. 

2. Supercomputers  built  in  t he 80's  and 90's  are  all  vector  machines,  so 
many  scientific  applications  developed  then  have  been  optimized  for  such 
machines.  Even  though  vectorizing  compilers  exist,  many  programmers 
still  write  their  code  to  operate  on  vectors  at  a  time.  T he  multigrid  code 
example  of this  chapter  is  an  example  of this  style. 

3. Opportunities  for  contraction  are  also  introduced  by  the  compiler.  As 
illustrated  by  variable  T  in  the  multigrid  example,  a  compiler  would  ex 
pand  arrays  to  improve  parallelization.  We  have  to  contract  t h em  when 
t he  space  expansion  is  not  necessary. 

E x a m p le  1 T . 6 7:  T he  array  expression  Z  =  W  +  X  +  Y  translates  to 

11.10. 

LOCALITY  OPTIMIZATIONS 

887 

for (i=0;  i<n;  i++) T[i]  = W[i]  + X[i] ; 
for (i=0;  i<n;  i++)  Z[i]  = T[i]  + Y [ i ]; 

Rewriting  the  code  as 

for  (i=0;  i<n;  i++)  { T = W[i]  + X [ i ];  Z[i]  = T + Y[i]  } 

can  speed  it  up  considerably.  Of  course  at  the  level  of  C  code,  we  would  not 
even  have  to  use  the  temporary  T,  but  could  write  the  assignment  to  Z[i]  as  a 
single  statement.  However,  here  we  are  trying  to  model  the  intermediate-code 
level  at  which  a  vector  processor  would  deal  with  the  operations. 

• 

A l g o r i t hm  1 1 . 6 8:  Array  contraction. 

INPUT:  A  program  transformed  by  Algorithm  11.64. 

OUTPUT:  An  equivalent  program  with  reduced  array  dimensions. 

METHOD:  A  dimension  of  an  array  can  be  contracted  to  a  single  element  if 

1.  Each  independent  partition  uses  only  one  element  of  t he  array, 

2.  T he  value  of  the  element  upon  entry  to  the  partition  is  not  used  by  t he 

partition,  and 

3.  T he  value  of  t he  element  is  not  live  on  exit  from  the  partition. 

Identify  the  contractable  dimensions  —  those  t h at  satisfy  t he  three  condi 

tions  above  —  and  replace  them  with  a  single  element. 

• 

Algorithm  11.68  assumes  t h at  t he  program  has  first  been  transformed  by  Al 
gorithm  11.64  to  pull  all  t he  dependent  operations  into  a  partition  and  execute 
t he  partitions  sequentially.  It  finds  those  array  variables  whose  elements'  live 
ranges  in  different  iterations  are  disjoint.  If these  variables  are  not  live  after  the 
loop,  it  contracts  the  array  and  has  the  processor  operate  on  the  same  scalar 
location.  After  array  contraction,  it  may  be  necessary  to  selectively  expand 
arrays  to  accommodate  for  parallelism  and  other  locality  optimizations. 

T he  liveness  analysis  required  here  is  more  complex  t h an  t h at  described  in 
Section  9.2.5.  If the  array  is  declared  as  a  global  variable,  or  if it  is  a  parameter, 
interprocedural  analysis  is  required  to  ensure  t h at  the  value  on  exit  is  not  used. 
Furthermore,  we  need  to  compute  the  liveness  of  individual  array  elements, 
conservatively  treating  t he  array  as  a  scalar  would  be  too  imprecise. 

11.10.3  Partition  Interleaving 

Different  partitions  in  a  loop  often  read  the  same  data,  or  read  and  write  the 
same  cache  lines.  In  this  and  the  next  two  sections,  we  discuss  how  to  optimize 
for  locality  when  reuse  is  found  across  partitions. 

888 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

R e u se  in  I n n e r m o st  B l o c ks 

We  adopt  the  simple  model  t h at  d a ta  can  be  found  in  the  cache  if  it  is  reused 
within  a  small  number  of  iterations.  If  the  innermost  loop  has  a  large  or  un 
known  bound,  only  reuse  across  iterations  of  the  innermost  loop  translates  into 
a  locality  benefit.  Blocking  creates  inner  loops  with  small  known  bounds,  al 
lowing  reuse  within  and  across  entire  blocks  of  computation  to  be  exploited. 
Thus,  blocking  has  the  effect  of  capitalizing  on  more  dimensions  of  reuse. 

E x a m p le  1 1 . 6 9:  Consider  the  matrix-multiply  code  shown  in  Fig.  11.5  and 
its  blocked  version  in  Fig.  11.7.  Matrix  multiplication  has  reuse  along  every 
dimension  of  its  three-dimensional  iteration  space.  In  the  original  code,  the  in 
nermost  loop  has  n  iterations,  where  n  is  unknown  and  can  be  large.  Our  simple 
model  assumes  t h at  only  the  d a ta  reused  across  iterations  in  the  innermost  loop 
is  found  in  the  cache. 

In  the  blocked  version,  the  three  innermost  loops  execute  a  three-dimension 
al  block  of  computation,  with  B  iterations  on  each  side.  The  block  size  B  is 
chosen  by  the  compiler  to  be  small  enough  so  t h at  all  t he  cache  lines  read  and 
written  within  the  block  of  computation  fit  into  the  cache.  Thus  reused  d a ta 
across  iterations  in  the  third  outermost  loop  can  be  found  in  the  cache. 

• 

We  refer  to  the  innermost  set  of loops  with  small  known  bounds  as  the  inner 
most  block.  It  is  desirable  t h at  the  innermost  block  include  all  the  dimensions 
of  the  iteration  space  t h at  carry  reuse,  if  possible.  Maximizing  the  lengths  of 
each  side  of t he  block  is  not  as  important.  For  the  matrix-multiply  example,  3-
dimensional  blocking  reduces  t he  amount  of  d a ta  accessed  for  each  matrix  by  a 
factor  of  B2.  If  reuse  is  present,  it  is  better  to  accommodate  higher-dimensional 
blocks  with  shorter  sides  t h an  lower-dimensional  blocks  with  longer  sides. 

We  can  optimize  locality  of  the  innermost  fully  permutable  loop  nest  by 
blocking  the  subset  of  loops  t h at  share  reuse.  We  can  generalize  the  notion  of 
blocking  to  exploit  reuses  found  among  iterations  of  outer  parallel  loops,  also. 
Observe  t h at  blocking  primarily  interleaves  the  execution  of  a  small  number 
of  instances  of  the  innermost  loop.  In  matrix  multiplication,  each  instance  of 
the  innermost  loop  computes  one  element  of  the  array  answer;  there  are  n2  of 
them.  Blocking  interleaves  the  execution  of  a  block  of  instances,  computing  B 
iterations  from  each  instance  at  a  time.  Similarly,  we  can  interleave  iterations 
in  parallel  loops  to  take  advantage  of  reuses  between  them. 

We  define  two  primitives  below  t h at  can  reduce  t he  distance  between  reuses 
across  different  iterations.  We  apply  these  primitives  repeatedly,  starting  from 
the  outermost  loop  until  all  t he  reuses  are  moved  adjacent  to  each  other  in  the 
innermost  block. 

I n t e r l e a v i ng  I n n er  L o o ps  in  a  P a r a l l el  L o op 

Consider  the  case  where  an  outer  parallelizable  loop  contains  an  inner  loop.  To 
exploit  reuse  across  iterations  of the  outer  loop,  we  interleave  the  executions  of 

11.10. 

LOCALITY  OPTIMIZATIONS 

889 

a  fixed  number  of instances  of the  inner  loop,  as  shown  in  Fig.  11.63.  Creating 
two-dimensional  inner  blocks,  this  transformation  reduces  the  distance  between 
reuse  of  consecutive  iterations  of  the  outer  loop. 

f or  ( i = 0; 

i < n; 

i++) 

f or  ( j = 0; 
<S> 

j < n; 

f or 

( i i = 0; 

f or 

( j = 0; 

i i < n; 
j < n; 

i i + = 4) 

f or 

( i = i i; 

i i < m i n ( n, 

i i + 4 ); 

i i + = 4) 

<S> 

(a)  Source  program. 

(b)  Transformed  code. 

Figure  11.63:  Interleaving  4  instances  of  the  inner  loop 

The  step  t h at  turns  a  loop 

f or 

( i = 0; 
<S> 

i < n; 

i++) 

into 

f or 

( i i = 0; 
f or 

i i < n; 

i i + = 4) 
i i < m i n ( n, 

( i = i i; 
<S> 

i i + 4 ); 

i i + = 4) 

is  known  as  stripmining.  In  the  case  where  the  outer  loop  in  Fig.  11.63  has  a 
small  known  bound,  we  need  not  stripmine  it,  but  can  simply  permute  the  two 
loops  in  the  original  program. 

I n t e r l e a v i ng  S t a t e m e n ts  in  a  P a r a l l el  L o op 

Consider  the  case  where  a  parallelizable  loop  contains  a  sequence  of statements 
si, S2,  •  •  •  ,  sm. 
If  some  of  these  statements  are  loops  themselves,  statements 
from  consecutive  iterations  may  still  be  separated  by  many  operations.  We 
can  exploit  reuse  between  iterations  by  again  interleaving  their  executions,  as 
shown  in  Fig.  11.64.  This  transformation  distributes  a  stripmined  loop  across 
the  statements.  Again,  if the  outer  loop  has  a  small  fixed  number  of  iterations, 
we  need  not  stripmine  the  loop  but  simply  distribute  the  original  loop  over  all 
the  statements. 

We  use  Si(j)  to  denote  the  execution  of statement  si  in  iteration j.  Instead  of 
the  original  sequential  execution  order  shown  in  Fig.  11.65(a),  the  code  executes 
in  the  order  shown  in  Fig.  11.65(b). 

E x a m p le  1 1 . 7 0:  We  now  return  to  the  multigrid  example  and  show  how 
we  exploit  reuse  between  iterations  of  outer  parallel  loops.  We  observe  t h at 
references  DW[1,  k,j,  i],  DW[1,  k-l,j,i],  and  DW[l,k+l,j,i]m 
loops  of  t he  code  in  Fig.  11.62  have  rather  poor  spatial  locality.  From  reuse 
analysis,  as  discussed  in  Section  11.5,  the  loop  with  index  i  carries  spatial 

innermost 

t he 

890 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

f or  ( i = 0; 
<S1> 
<S2> 

} 

i < n; 

i++)  { 

f or 

( i i = 0; 

i i < n; 

i i + = 4)  { 
i < m i n ( n , i i + 4 ); 

i++) 

f or 

( i = i i; 

<S1> 

f or 

( i = i i; 

i < r a i n ( n , i i + 4 ); 

i++) 

<S2> 

} 

(a)  Source  program. 

(b)  Transformed  code. 

Figure  11.64:  The  statement-interleaving  transformation 

locality  and  the  loop  with  index  k  carries  group  reuse.  T he  loop  with  index  k 
is  already  the  innermost  loop,  so  we  are  interested  in  interleaving  operations  on 
DW  from  a  block  of  partitions  with  consecutive  i  values. 

We  apply  the  transform  to  interleave  statements  in  t he  loop  to  obtain  the 
code  in  Fig.  11.66,  then  apply  the  transform  to  interleave  inner  loops  to  obtain 
the  code  in  Fig.  11.67.  Notice  t h at  as  we  interleave  B  iterations  from  loop  with 
index  i,  we  need  to  expand  variables  AP,  AM,T  into  arrays  t h at  hold  B  results 
at  a  time. 

• 

11.10.4  Putting  it  All  Together 

Algorithm  11.71  optimizes  locality  for  a  uniprocessor,  and  Algorithm  11.72 
optimizes  b o th  parallelism  and  locality  for  a  multiprocessor. 

A l g o r i t hm  1 1 . 7 1:  Optimize  d a ta  locality  on  a  uniprocessor. 

INPUT:  A  program  with  affine  array  accesses. 

OUTPUT:  An  equivalent  program  t h at  maximizes  d a ta  locality. 

METHOD:  Do  the  following  steps: 

1.  Apply  Algorithm  11.64  to  optimize  t he  temporal  locality  of  computed 

results. 

2.  Apply  Algorithm  11.68  to  contract  arrays  where  possible. 

3.  Determine  the  iteration  subspace  t h at  may  share  the  same  d a ta  or  cache 
lines  using  the  technique  described  in  Section  11.5.  For  each  statement, 
identify  those  outer  parallel  loop  dimensions  t h at  have  d a ta  reuse. 

4.  For  each  outer  parallel  loop  carrying  reuse,  move  a  block  of t he  iterations 
into  the  innermost  block  by  applying  the  interleaving  primitives  repeat 
edly. 

11.10. 

LOCALITY  OPTIMIZATIONS 

891 

si(0), 

52(0), 
52(1), 
*i(2),  52(2), 
«i(3),  52(3), 
s i( 4 ), 
52(4), 
5l(5),  52(5), 
5l(6),  «2(6), 
82(1), 
*i(7), 

•  , 

sm( 0 ), 

•  j  5m(l), 
• 5  5TO(2), 
.. • 5  5m(3), 
• 5  5TO(4), 
• 5  5m(5), 
•  ,  3m( 6 ), 
•  • 5  5TO(7), 

(a)  Original  order. 

si  (1), 
82  (1), 

(0), 
(0), 

81 
S2 
. . . , 
Sm  (0),  Sm( l ), 
81 

8i  (5), 

(4), 

si  (2), 
S2  (2), 

si  (3), 
82  (3), 

Sm( 2 ), 
81  (6), 

8m( 3 ), 

8i  (7), 

82 

(4), 

82  (5), 

82  (6), 

82  (7), 

•  •  •  j 
sm 

(4), 

8T O( 5 ), 

8m( 6 ), 

sm( 7) 

(b)  Transformed  order. 

Figure  11.65:  Distributing  a  stripmined  loop 

5.  Apply  blocking  to  t he  subset  of  dimensions  in  the  innermost  fully  per 

mutable  loop  nest  t h at  carries  reuse. 

6.  Block  outer  fully  permutable  loop  nest  for  higher  levels  of  memory  hier 

archies,  such  as  the  third-level  cache  or  the  physical  memory. 

7.  E x p a nd  scalars  and  arrays  where  necessary  by  the  lengths  of  the  blocks. 

• 

A l g o r i t hm  1 1 . 7 2:  Optimize  parallelism  and  d a ta  locality  for  multiprocessors. 

INPUT:  A  program  with  affine  array  accesses. 

OUTPUT:  An  equivalent  program  t h at  maximizes  parallelism  and  d a ta  locality. 

METHOD:  Do  t he  following: 

1.  Use  the  Algorithm  11.64  to  parallelize  the  program  and  create  an  S P MD 

program. 

892 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

for (j = 2, j <= jl, 

for  (ii = 2,  ii  <= il,  ii+=b)  { 

for  (i  =  ii;  i  <= min(ii+b-l,il);  i++)  { 

ib 

=  i-ii+1; 

AP[ib] 

=  ...; 

T 

= 1 . 0 / ( 1 .0 +AP[ib]); 

D[2,ib] 
DW[l,2,j,i] = T*DW[l,2,j,i] J 

= T*AP[ib] ; 

} 
for  (i  =  ii;  i  <= min(ii+b-l,il);  i++)  { 

for (k=3, k <= kl-1, k++) 

ib 

AM 

=  i-ii+1; 

= AP [ib]; 

AP[ib] 

=  ...; 

T 

= . . .AP[ib]-AM*D[ib,k-l] . . .; 

D[ib,k] 

=  T*AP; 

DW[l,k,j,i]  = T*(DW[l,k,j,i]+DW[l,k-l,j,i])...; 

} 

for  (i  =  ii;  i  <= min(ii+b-l,il);  i++) 

for  (k=kl-l,  k>=2,  k ~)  { 

DW[l,k,j,i] = DW[l,k,j,i] +D[iw,k]*DW[l,k+l,j ,i] ; 

/*  Ends  code  to  be  executed by  processor  (j,i)  */ 

} 

} 

Figure 11.66:  Excerpt  of  Fig. 11.23  after  partitioning,  a r r ay  contraction,  a nd 

blocking 

2.  Apply  Algorithm 11.71  to  t he  S P MD  program  produced  in  Step 1  to 

optimize  its  locality. 

11.10.5  Exercises  for  Section  11.10 

E x e r c i se  1 1 . 1 0 . 1:  Perform array contraction on the following vector opera 

tions: 

for (i=0; i<n; i++) T[i] = A[i] * B [ i ]; 
for (i=0; i<n; i++) D[i] = T[i] + C [ i ]; 

E x e r c i se  1 1 . 1 0 . 2:  Perform array contraction on the following vector opera 

tions: 

11.11. 

OTHER  USES  OF  AFFINE  TRANSFORMS 

893 

for (j =  2, j <= jl, j++) 

for  (ii  =  2,  ii  <=  il,  ii+=b)  { 

for  (i  =  ii;  i  <= min(ii+b-l,il);  i++)  { 

ib 
AP[ib] 
T 
D[2,ib] 
DW[l,2,j,i]  = T*DW[l,2,j,i] ; 

=  i-ii+1; 
=  ...; 
= 1 . 0 / ( 1 .0 +AP[ib]); 
= T*AP[ib] ; 

} 
for (k=3, k <= kl-1, k++) 

for  (i  =  ii;  i  <= min(ii+b-l,il);  i++)  { 
=  i-ii+1; 

ib 
AM 
AP[ib] 
T 
D[ib,k] 
DW[l,k,j,i] = T*(DW[l,k,j,i]+DW[l,k-l,j,i])...; 

= AP [ib]; 
=  ...; 
= . . .AP[ib]-AM*D[ib,k-l] . . .; 
=  T*AP; 

} 

for  (k=kl-l,  k>=2,  k —)  { 

for  (i  =  ii;  i  <= min(ii+b-l,il);  i++) 

DW[l,k,j,i] = DW[l,k,j,i] +D[iw,k]*DW[l,k+l,j,i] ; 

/*  Ends  code  to  be  executed by processor  (j,i)  */ 

} 

} 

Figure  11.67:  Excerpt of Fig.  11.23 after partitioning, array contraction, and 
blocking 

for (i=0; i<n; i++) T[i] = A[i] + B [ i ]; 
for (i=0; i<n; i++) S[i] = C[i] + D [ i ]; 
for (i=0; i<n; i++) E[i] = T[i] * S [ i ]; 

Exercise  1 1 . 1 0 . 3:  Stripmine the outer loop 

for  (i=n-l;  i>=0;  i —) 

for (j=0; j<n; j++) 

into strips of width  10. 

11.11  Other  Uses  of Affine  Transforms 

So far we have focused on the architecture of shared m e m o ry machines, but 
the theory of affine loop transforms has m a ny other applications.  We can ap 
ply affine transforms to other forms of parallelism including distributed m e m o ry 

894 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

machines,  vector  instructions,  SIMD  (Single  Instruction  Multiple  Data)  instruc 
tions,  as  well  as  multiple-instruction-issue  machines.  The  reuse  analysis  intro 
duced  in  this  chapter  also  is  useful  for  d a ta  prefetching,  which  is  an  effective 
technique  for  improving  memory  performance. 

11.11.1  Distributed  Memory  Machines 

For  distributed  memory  machines,  where  processors  communicate  by  sending 
messages  to  each  other,  it  is  even  more  important  t h at  processors  be  assigned 
large,  independent  units  of  computation,  such  as  those  generated  by  the  affine-
partitioning  algorithm.  Besides  computation  partitioning,  a  number  of  addi 
tional  compilation  issues  remain: 

1.  Data  allocation.  If  processors  use  different  portions  of  an  array,  they  each 
only  have  to  allocate  enough  space  to  hold  the  portion  used.  We  can  use 
projection  to  determine  the  section  of  arrays  used  by  each  processor.  The 
input  is  the  system  of linear  inequalities  representing  the  loop  bounds,  the 
array  access  functions,  and  the  affine  partitions  t h at  m ap  the  iterations 
to  processor  IDs.  We  project  away  the  loop  indices  and  find  for  each 
processor  ID  the  set  of  array  locations  used. 

2.  Communication  code.  We  need  to  generate  explicit  code  to  send  and 
receive  d a ta  to  and  from  other  processors.  At  each  synchronization  point 

(a)  Determine  the  d a ta  residing  on  one  processor  t h at  is  needed  by  other 

processors. 

(b)  Generate  the  code  t h at  finds  all  the  d a ta  to  be  sent  and  packs  it  into 

a  buffer. 

(c)  Similarly,  determine  the  d a ta  needed  by  the  processor,  unpack  re 
ceived  messages,  and  move  the  d a ta  to  the  right  memory  locations. 

Again,  if  all  accesses  are  affine,  these  tasks  can  be  performed  by  the 
compiler,  using  the  affine  framework. 

3.  Optimization.  It  is  not  necessary  for  all  the  communications  to  take  place 
at  the  synchronization  points.  It  is  preferable  t h at  each  processor  sends 
d a ta  as  soon  as  it  is  available,  and  t h at  each  processor  does  not  start 
waiting  for  d a ta  until  it  is  needed.  Such  optimizations  must  be  balanced 
by  the goal  of not  generating too  many  messages,  since  there  is  a nontrivial 
overhead  associated  with  processing  each  message. 

Techniques  described  here  have  other  applications  as  well.  For  example,  a 
special-purpose  embedded  system  may  use  coprocessors  to  offload  some  of  its 
computations.  Or,  instead  of demand  fetching  d a ta  into  the  cache,  an  embedded 
system  may  use  a  separate  controller  to  load  and  unload  d a ta  into  and  out  of 
the  cache,  or  other  d a ta  buffers,  while  the  processor  operates  on  other  data.  In 
these  cases,  similar  techniques  can  be  used  to  generate  the  code  to  move  d a ta 
around. 

11.11. 

OTHER  USES  OF  AFFINE  TRANSFORMS 

895 

11.11.2  Multi-Instruction-Issue  Processors 

We  can  also  use  affine  loop  transforms  to  optimize  the  performance  of  multi-
instruction-issue  machines.  As  discussed  in  Chapter  10.5,  t he  performance  of 
a  software-pipelined  loop  is  limited  by  two  factors:  cycles  in  precedence  con 
straints  and  t he  usage  of  the  critical  resource.  By  changing  the  makeup  of  the 
innermost  loop,  we  can  improve  these  limits. 

First,  we  may  be  able  to  use  loop  transforms  to  create  innermost  paralleliz-

able  loops,  thus  eliminating  precedence  cycles  altogether.  Suppose  a  program 
has  two  loops,  with  the  outer  being  parallelizable  and  t he  inner  not.  We  can 
p e r m u te  t he  two  loops  to  make  t he  inner  loop  parallelizable  and  so  create  more 
opportunities  for  instruction-level  parallelism.  Notice  t h at  it  is  not  necessary 
for  iterations  in  the  innermost  loop  to  be  completely  parallelizable.  It  is  suffi 
cient  t h at  the  cycle  of  dependences  in  the  loop  be  short  enough  so  t h at  all  the 
hardware  resources  are  fully  utilized. 

We  can  also  relax  t he  limit  due  to  resource  usage  by  improving  t he  usage 
balance  inside  a  loop.  Suppose  one  loop  only  uses  the  adder,  and  another  uses 
only  the  multiplier.  Or,  suppose  one  loop  is  memory  bound  and  another  is 
compute  bound. 
It  is  desirable  to  fuse  each  pair  of  loops  in  these  examples 
together  so  as  to  utilize  all  the  functional  units  at  the  same  time. 

11.11.3  Vector  and  SIMD  Instructions 

Besides  multiple-instruction  issue,  there  are  two  other  important  forms  of  in 
In  both  cases,  the 
struction-level  parallelism:  vector  and  SIMD  operations. 
issue  of just  one  instruction  causes  the  same  operation  to  be  applied  to  a  vector 
of  data. 

As  mentioned  previously,  many  early  supercomputers  used  vector  instruc 
tions.  Vector  operations  are  performed  in  a  pipelined  manner;  t he  elements 
in  the  vector  are  fetched  serially  and  computations  on  different  elements  are 
overlapped. 
In  advanced  vector  machines,  vector  operations  can  be  chained: 
as  the  elements  of  t he  vector  results  are  produced,  they  are  immediately  con 
sumed  by  operations  of  another  vector  instruction  without  having  to  wait  for 
all  the  results  to  be  ready.  Moreover,  in  advanced  machines  with  scatter/gather 
hardware,  the  elements  of  the  vectors  need  not  be  contiguous;  an  index  vector 
is  used  to  specify  where  t he  elements  are  located. 

SIMD  instructions  specify  t h at  the  same  operation  be  performed  on  contigu 
ous  memory  locations.  These  instructions  load  d a ta  from  memory  in  parallel, 
store  them  in  wide  registers,  and  compute  on  t h em  using  parallel  hardware. 
Many  media,  graphics,  and  digital-signal-processing  applications  can  benefit 
from  these  operations.  Low-end  media  processors  can  achieve  instruction-level 
parallelism  simply  by  issuing  one  SIMD  instruction  at  a  time.  Higher-end  pro 
cessors  can  combine  SIMD  with  multiple-instruction  issue  to  achieve  higher 
performance. 

SIMD  and  vector  instruction  generation  share  many  similarities  with  locality 

896 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

optimization.  As  we  find  independent  partitions  t h at  operate  on  contiguous 
memory  locations,  we  stripmine  those  iterations  and  interleave  these  operations 
in  innermost  loops. 

SIMD  instruction  generation  poses  two  additional  difficulties.  First,  some 
machines  require  t h at  the  SIMD  d a ta  fetched  from  memory  be  aligned.  For 
example,  they  might  require  t h at  25,6-byte  SIMD  operands  be  placed  in  ad 
dresses  t h at  are  multiples  of  256.  If  the  sdurce  loop  operates  on  just  one  array 
of  data,  we  can  generate  one  main  loop  t h at  operates  on  aligned  d a ta  and  ex 
t ra  code  before  and  after  the  loop  to  handle  those  elements  at  the  boundary. 
For  loops  operating  on  more  t h an  one  array,  however,  it  may  not  be  possible 
to  align  all  the  d a ta  at  t he  same  time.  Second,  d a ta  used  by  consecutive  it 
erations  in  a  loop  may  not  be  contiguous.  Examples  include  many  important 
digital-signal-processing  algorithms,  such  as  Viterbi  decoders  and  fast  Fourier 
transforms.  Additional  operations  to  shuffle  the  d a ta  around  may  be  necessary 
to  take  advantage  of  the  SIMD  instructions. 

11.11.4  Prefetching 

No  data-locality  optimization  can  eliminate  all  memory  accesses;  for  one,  d a ta 
used  for  the  first  time  must  be  fetched  from  memory.  To  hide  t he  latency 
of  memory  operations,  prefetch  instructions  have  been  adopted  in  many  high-
performance  processors.  Prefetch  is  a  machine  instruction  t h at  indicates  to  t he 
processor  t h at  certain  d a ta  is  likely  to  be  used  soon,  and  t h at  it  is  desirable  to 
load  the  d a ta  into  t he  cache  if  it  is  not  present  already. 

The  reuse  analysis  described  in  Section  11.5  can  be  used  to  estimate  when 
caches  misses  are  likely.  There  are  two  important  considerations  when  gener 
ating  prefetch  instructions.  If  contiguous  memory  locations  are  to  be  accessed, 
we  need  to  issue  only  one  prefetch  instruction  for  each  cache  line.  Prefetch 
instructions  should  be  issued  early  enough  so  t h at  the  d a ta  is  in  the  cache  by 
the  time  it  are  used.  However,  we  should  not  issue  prefetch  instructions  too 
far  in  advance.  The  prefetch  instructions  can  displace  d a ta  t h at  may  still  be 
needed;  also  the  prefetched  d a ta  may  be  flushed  before  it  is  used. 

E x a m p le  1 1 . 7 3:  Consider  the  following  code: 

f or 

( i = 0; 
f or 

i i < 3; 

i++) 
j < 1 0 0; 

( j = 0; 
A [ i , j]  = 

. . .; 

j++) 

Suppose  t he  target  machine  has  a  prefetch  instruction  t h at  can  fetch  two  words 
of  d a ta  at  a  time,  and  t h at  the  latency  of  a  prefetch  instruction  takes  about 
t he  time  to  execute  six  iterations  of  t he  loop  above.  T he  prefetch  code  for  the 
above  example  is  shown  in  Fig.  11.68. 

We  unroll t he  innermost  loop  twice,  so  a  prefetch  can  be  issued  for  each  cache 
line.  We  use  t he  concept  of  software  pipelining  to  prefetch  d a ta  six  iterations 
before  it  is  used.  The  prolog fetches  the  d a ta used  in  the  first  six  iterations.  T he 

11.12. 

SUMMARY  OF  CHAPTER  11 

897 

i i < 3; 

i++)  { 

j < 6; 

j < 9 4; 

j+=2) 

( j = 0; 
p r e f e t c h ( & A [ i , j ] ); 
( j = 0; 
p r e f e t c h ( & A [ i , j + 6 ] ); 
A[ i,  j]  =  .  .  .  ; 
A [ i , j + 1]  = 

j+=2)  { 

( i = 0; 
f or 

f or 

} 
f or 

f or 

} 

j < 1 0 0; 

( j = 9 4; 
A[ i , j]  = 

j++) 

Figure  11.68:  Code  modified  to  prefetch  d a ta 

steady  state  loop  prefetches  six  iterations  ahead  as  it  performs  its  computation. 
T he  epilog  issues  no  prefetches,  but  simply  executes  the  remaining  iterations. 
• 

11.12  Summary  of Chapter  11 

•  Parallelism  and  Locality  from  Arrays.  T he  most  important  opportunities 
for  both  parallelism  and  locality-based  optimizations  come  from  loops 
t h at  access  arrays.  These  loops  tend  to  have  limited  dependences  among 
accesses  to  array  elements  and  tend  to  access  arrays  in  a  regular  pattern, 
allowing  efficient  use  of  the  cache  for  good  locality. 

•  Affine  Accesses.  Almost  all  theory  and  techniques  for  parallelism  and 
locality  optimization  assume  accesses  to  arrays  are  affine:  the  expressions 
for  the  array  indexes  are  linear  functions  of  the  loop  indexes. 

4-  Reration  Spaces.  A  loop  nest  with  d  nested  loops  defines  a  d-dimensional 
iteration  space.  The  points  in  the  space  are  the  d-tuples  of  values  t h at 
t he  loop  indexes  can  assume  during  the  execution  of the  loop  nest.  In  the 
affine  case,  t he  limits  on  each  loop  index  are  linear  functions  of  t he  outer 
loop  indexes,  so  the  iteration  space  is  a  polyhedron. 

•  Fourier-Motzkin  Elimination.  A  key  manipulation  of  iteration  spaces  is 
to  reorder  the  loops  t h at  define  t he  iteration  space.  Doing  so  requires  t h at 
a  polyhedral  iteration  space  be  projected  onto  a  subset  of  its  dimensions. 
The  Fourier-Motzkin  algorithm  replaces  the  upper  and  lower  limits  on  a 
given  variable  by  inequalities  between  the  limits  themselves. 

•  Data  Dependences  and  Array  Accesses.  A  central  problem  we  must  solve 
in  order  to  manipulate  loops  for  parallelism  and  locality  optimizations 
is  whether  two  array  accesses  have  a  d a ta  dependence  (can  touch  t he 

8 98 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

same  array  element).  When  the  accesses  and  loop  bounds  are  affine,  t he 
problem  can  be  expressed  as  whether  there  are  solutions  to  a matrix-vector 
equation  within  the  polyhedron  t h at  defines  the  iteration  space. 

•  Matrix  Rank  and  Data  Reuse.  T he  matrix  t h at  describes  an  array  access 
can  tell  us  several  important  things  about  t h at  access.  If  t he  rank  of  t he 
matrix is  as  large  as  possible  (minimum  of the  number  of rows  and  number 
of  columns),  then  the  access  never  touches  the  same  element  twice  as  the 
loops  iterate.  If the  array  is  stored  in  row-  (column-)major  form,  then  t he 
rank  of  the  matrix  with  the  last  (first)  row  deleted  tells  us  whether  the 
access  has  good  locality;  i.e.,  elements  in  a  single  cache  line  are  accessed 
at  about  the  same  time. 

•  Data  Dependence  and  Diophantine  Equations. 

Just  because  two  accesses 

to  the  same  array  touch  the  same  region  of t he  array  does  not  mean  t h at 
they  actually  access  any  element  in  common.  T he  reason  is  t h at  each 
may  skip  some  elements;  e.g.,  one  accesses  even  elements  and  t he  other 
accesses  odd  elements.  In  order to  be  sure  t h at  there  is  a  d a ta  dependence, 
we  must  solve  a  Diophantine  (integer  solutions  only)  equation. 

4-  Solving  Diophantine  Linear  Equations.  The  key  technique  is  to  compute 
the  greatest  common  divisor  (GCD)  of  the  coefficients  of  the  variables. 
Only  if t h at  GCD  divides  the  constant  term  will  there  be  integer  solutions. 

•  Space-Partition  Constraints.  To  parallelize  t he  execution  of  a  loop  nest, 
we  need  to  m ap  t he  iterations  of  the  loop  to  a  space  of  processors,  which 
can  have  one  or  more  dimensions.  The  space-partition  constraints  say 
t h at  if  two  accesses  in  two  different  iterations  share  a  d a ta  dependence 
(i.e.,  they  access  the  same  array  element),  then  they  must  m ap  to  t he 
same  processor.  As  long  as  the  mapping  of  iterations  to  processors  is 
affine,  we  can  formulate  the  problem  in  matrix-vector  terms. 

•  Primitive  Code  Transformations.  T he  transformations  used  to  parallelize 
programs  with  affine  array  accesses  are  combinations  of  seven  primitives: 
loop  fusion,  loop  fission,  re-indexing  (adding  a  constant  to  loop  indexes), 
scaling  (multiplying loop  indexes  by  a  constant),  reversal  (of a  loop  index), 
permutation  (of  the  order  of  loops),  and  skewing  (rewriting  loops  so  the 
line  of  passage  through  the  iteration  space  is  no  longer  along  one  of  t he 
axes). 

•  Synchronization  of  Parallel  Operations.  Sometimes  more  parallelism  can 
be  obtained  if  we  insert  synchronization  operations  between  steps  of  a 
program.  For  example,  consecutive  loop  nests  may  have  d a ta  depen 
dences,  but  synchronizations  between  t he  loops  can  allow  t he  loops  to  be 
parallelized  separately. 

•  Pipelining.  This  parallelization  technique  allows  processors  to  share  data, 
by  synchronously  passing  certain  d a ta  (typically  array  elements)  from  one 

11.13. 

REFERENCES  FOR  CHAPTER  11 

899 

processor  to  an  adjacent  processor  in  the  processor  space.  T he  method 
can  improve  t he  locality  of  the  d a ta  accessed  by  each  processor. 

4  Time-Partition  Constraints.  To  discover  opportunities  for  pipelining,  we 
need  to  discover  solutions  to  the  time-partition  constraints.  These  say 
t h at  whenever  two  array  accesses  can  touch  the  same  array  element,  then 
the  access  in  the  iteration  t h at  occurs  first  must  be  assigned  to  a  stage 
in  the  pipeline  t h at  occurs  no  later  t h an  the  stage  to  which  the  second 
access  is  assigned. 

4-  Solving  Time-Partition  Constraints. 

Farkas'  Lemma  provides  a  power 
ful  technique  for  finding  all  the  affine  time-partition  mappings  t h at  are 
allowed  by  a  given  loop  nest  with  array  accesses.  T he  technique  is  es 
sentially  to  replace  the  primal  formulation  of  the  linear  inequalities  t h at 
express  the  time-partition  constraints  by  their  dual. 

•  Blocking.  This  technique  breaks  each  of  several  loops  in  a  loop  nest  into 
two  loops  each.  The  advantage  is  t h at  doing  so  may  allow  us  to  work  on 
small  sections  (blocks)  of  a  multidimensional  array,  one  block  at  a  time. 
T h a t,  in  turn,  improves  t he  locality  of the  program,  letting  all  the  needed 
d a ta  reside  in  the  cache  while  working  on  a  single  block. 

•  Stripmining.  Similar  to  blocking,  this  technique  breaks  only  a  subset  of 
the  loops  of  a  loop  nest  into  two  loops  each.  A  possible  advantage  is  t h at 
a  multidimensional  array  is  accessed  a  "strip"  at  a  time,  which  may  lead 
to  the  best  possible  cache  utilization. 

11.13  References  for  Chapter  11 

For  detailed  discussions  of  multiprocessor  architectures,  we  refer  t he  reader  to 
the  text  by  Hennessy  and  Patterson  [9]. 

Lamport  [13]  and  Kuck,  Muraoka,  and  Chen  [6]  introduced  the  concept  of 
data-dependence  analysis.  Early  data-dependence  tests  used  heuristics  to  prove 
a  pair  of references  to  be  independent  by  determining  if there  are  no  solutions  to 
Diophantine  equations  and  systems  of  real  linear  inequalities:  [5,  6,  26].  May-
dan,  Hennessy,  and  Lam  [18]  formulated  the  data-dependence  test  as  integer 
linear  programming  and  showed  t h at  the  problem  can  be  solved  exactly  and 
efficiently  in  practice.  T he  data-dependence  analysis  described  here  is  based 
on  work  by  Maydan,  Hennessy,  and  Lam  [18]  and  P u gh  and  Wonnacott  [23], 
which  in  t u rn  use  techniques  of  Fourier-Motzkin  elimination  [7]  and  Shostak's 
algorithm  [25]. 

T he  70's  and  early  80's  saw  the  use  of  loop  transformations  to  improve 
loop  fusion  [3],  loop  fission  [1],  stripmining 
vectorization  and  parallelization: 
[17],  and  loop  interchange  [28].  There  were  three  major  experimental  paral-
lelizer/vectorizing  projects  going  on  at  the  time:  Parafrase  led  by  Kuck  at  the 
University  of Illinois  Urbana-Champaign  [21],  the  P FC  project  led  by  Kennedy 

900 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

at  Rice  University  [4],  and  t he  P T R AN  project  led  by  Allen  at  IBM  Research 
[2]-

McKellar  and  Coffman  [19]  first  discussed  using  blocking  to  improve  d a ta 
locality.  Lam,  Rothbert,  and  Wolf  [12]  provided  the  first  in-depth  empirical 
analysis  of  blocking  on  caches  for  modern  architectures.  Wolf  and  Lam  [27] 
used  linear-algebra  techniques  to  compute  d a ta  reuse  in  loops.  Sarkar  and  Gao 
[24]  introduced  the  optimization  of  array  contraction. 

Lamport  [13]  was  t he  first  to  model  loops  as  iteration  spaces  and  used  hyper-
planing  (a  special  case  of  an  affine  transform)  to  find  parallelism  for  multipro 
cessors.  Affine  transforms  have  their  root  in  systolic-array  algorithm  design  [11]. 
Intended  as  parallel  algorithms  directly  implemented  in  VLSI,  systolic  arrays 
require  communication  to  be  minimized  along  with  parallelization.  Algebraic 
techniques  were  developed  to  m ap  the  computation  onto  space  and  time  coordi 
nates.  The  concept  of an  affine  schedule  and  t he  use  of Farkas'  Lemma  in  affine 
transformations  were  introduced  by  Feautrier  [8].  T he  affine-transformation 
algorithm  described  here  is  based  on  work  by  Lim  et  al.  [15,  14,  16]. 

Porterfield  [22]  proposed  one  of  the  first  compiler  algorithms  to  prefetch 
data.  Mowry,  Lam,  and  G u p ta  [20]  applied  reuse  analysis  to  minimize  t he 
prefetch  overhead  and  gain  an  overall  performance  improvement. 

1.  Abu-Sufah,  W.,  D.  J.  Kuck,  and  D.  H.  Lawrie,  "On  the  performance 
enhancement  of  paging  systems  through  program  analysis  and  transfor 
mations,"  IEEE  Trans,  on  Computing  C-30:5  (1981),  pp.  341-356. 

2.  Allen,  F.  E.,  M.  Burke,  P.  Charles,  R.  Cytron,  and  J.  Ferrante,  "An 
overview  of  t he  P T R AN  analysis  system  for  multiprocessing,"  J.  Parallel 
and  Distributed  Computing  5:5  (1988),  pp.  617-640. 

3.  Allen,  F.  E.  and  J.  Cocke,  "A  Catalogue  of  optimizing  transformations," 
(R.  Rustin,  ed.),  p p.  1-30, 

in  Design  and  Optimization  of  Compilers 
Prentice-Hall,  1972. 

4.  Allen,  R.  and  K.  Kennedy,  "Automatic  translation  of Fortran  programs  to 

vector  form,"  ACM  Transactions  on  Programming  Languages  and  Systems 
9:4  (1987),  pp.  491-542. 

5.  Banerjee,  U.,  Data  Dependence 

in  Ordinary  Programs,  Master's  thesis, 
Department  of  Computer  Science,  University  of  Illinois  Urbana-Cham-
paign,  1976. 

6.  Banerjee,  U.,  Speedup  of  Ordinary  Programs,  P h . D.  thesis,  Department 
of  Computer  Science,  University  of  Illinois  Urbana-Champaign,  1979. 

7.  Dantzig,  G.  and  B.  C.  Eaves,  "Fourier-Motzkin  elimination  and  its  dual," 

J.  Combinatorial  Theory,  A ( 1 4)  (1973),  pp.  288-297. 

8.  Feautrier,  P.,  "Some  efficient  solutions  to  t he  affine  scheduling  problem: 
International  J.  Parallel  Programming  21:5 

time," 

I.  One-dimensional 
(1992),  p p.  313-348, 

11.13. 

REFERENCES  FOR  CHAPTER  11 

901 

9.  Hennessy,  J.  L.  and  D.  A.  Patterson,  Computer  Architecture:  A  Quanti 
tative  Approach,  Third  Edition,  Morgan  Kaufman,  San  Francisco,  2003. 

10.  Kuck,  D.,  Y.  Muraoka,  and  S.  Chen,  "On  the  number  of  operations 
simultaneously  executable  in  Fortran-like  programs  and  their  resulting 
speedup," 
IEEE  Transactions  on  Computers  C-21:12  (1972),  pp.  1293¬ 
1310. 

11.  Kung,  H.  T.  and  C.  E.  Leiserson,  "Systolic  arrays  (for  VLSI),"  in  Duff, 
I.  S.  and  G.  W.  Stewart  (eds.),  Sparse  Matrix  Proceedings  pp.  256-282. 
Society  for  Industrial  and  Applied  Mathematics,  1978. 

12.  Lam,  M.  S.,  E.  E.  Rothberg,  and  M.  E.  Wolf,  "The  cache  performance  and 

optimization  of  blocked  algorithms,"  Proc.  Sixth  International  Conference 
on  Architectural  Support  for  Programming  Languages  and  Operating  Sys 
tems  (1991),  pp.  63-74. 

13.  Lamport,  L.,  "The  parallel  execution  of  DO  loops,"  Comm.  ACM  17:2 

(1974),  pp.  83-93. 

14.  Lim,  A.  W.,  G.  I.  Cheong,  and  M.  S.  Lam,  "An  affine  partitioning  algo 

rithm  to  maximize  parallelism  and  minimize  communication,"  Proc.  13th 
International  Conference  on  Supercomputing  (1999),  pp.  228-237. 

15.  Lim,  A.  W.  and  M.  S.  Lam,  "Maximizing  parallelism  and  minimizing 
synchronization  with  affine  transforms,"  Proc.  24th  ACM  SIGPLAN-SIG-
ACT  Symposium  on  Principles  of  Programming  Languages 
(1997),  pp. 
201-214. 

16.  Lim,  A.  W.,  S.-W.  Liao,  and  M.  S.  Lam,  "Blocking  and  array  contrac 

tion  across  arbitrarily  nested  loops  using  affine  partitioning,"  Proc.  ACM 
of  Parallel  Program 
SIGPLAN  Symposium 
ming  (2001),  pp.  103-112. 

on  Principles 

and  Practice 

17.  Loveman.  D.  B.,  "Program  improvement  by  source-to-source  transforma 

tion,"  J.  ACM  24:1  (1977),  pp.  121-145. 

18.  Maydan,  D.  E.,  J.  L.  Hennessy,  and  M.  S.  Lam,  "An  efficient  method  for 

exact  dependence  analysis,"  Proc.  ACM  SIGPLAN  1991  Conference  on 
Programming  Language  Design  and  Implementation,  pp.  1-14. 

19.  McKeller,  A.  C.  and  E.  G.  Coffman,  "The  organization  of  matrices  and 
matrix  operations  in  a  paged  multiprogramming  environment,"  Comm. 
ACM,  12:3  (1969),  pp.  153-165. 

20.  Mowry,  T.  C,  M.  S.  Lam,  and  A.  Gupta,  "Design  and  evaluation  of a  com 

piler  algorithm  for  prefetching,"  Proc.  Fifth  International  Conference  on 
Architectural  Support  for  Programming  Languages  and  Operating  Systems 
(1992),  pp.  62-73. 

902 

CHAPTER  11. 

OPTIMIZING  FOR  PARALLELISM  AND  LOCALITY 

21.  P a d u a,  D.  A.  and  M.  J.  Wolfe,  "Advanced  compiler  optimziations  for 

supercomputers,"  Comm.  ACM,  29:12  (1986),  p p.  1184-1201. 

22.  Porterfield,  A.,  Software  Methods  for  Improving  Cache  Performance  on 

Supercomputer  Applications,  P h . D.  Thesis,  Department  of  Computer  Sci 
ence,  Rice  University,  1989. 

23.  Pugh,  W.  and  D.  Wonnacott,  "Eliminating false  positives  using  t he  omega 

test,"  Proc.  ACM  SIGPLAN  1992  Conference  on  Programming  Language 
Design  and  Implementation,  pp.  140-151. 

24.  Sarkar,  V.  and  G.  Gao,  "Optimization  of array  accesses  by  collective  loop 

transformations,"  Proc.  5th  International  Conference  on  Supercomputing 
(1991),  pp.  194-205. 

25.  R.  Shostak,  "Deciding  linear  inequalities  by  computing  loop  residues,"  J. 

ACM,  28:4  (1981),  pp.  769-779. 

26.  Towle,  R.  A.,  Control  and  Data  Dependence  for  Program  Transforma 
tion,  P h . D.  thesis,  Department  of  Computer  Science,  University  of Illinois 
Urbana-Champaign,  1976. 

27.  Wolf,  M.  E.  and  M.  S.  Lam,  "A  d a ta  locality  optimizing  algorithm," 

Proc.  SIGPLAN  1991  Conference  on  Programming  Language  Design  and 
Implementation,  p p.  30-44. 

28.  Wolfe,  M.  J.,  Techniques  for  Improving 

in  Pro 
grams,  Master's  thesis,  Department  of  Computer  Science,  University  of 
Illinois  Urbana-Champaign,  1978. 

the  Inherent  Parallelism 

Chapter  12 

Interprocedural  Analysis 

In  this  chapter,  we  motivate  the  importance  of interprocedural  analysis  by  dis 
cussing  a  number  of  important  optimization  problems  t h at  cannot  be  solved 
with  intraprocedural  analysis.  We  begin  by  describing  the  common  forms  of 
interprocedural  analysis  and  explaining  the  difficulties  in  their  implementation. 
We  then  describe  applications  for  interprocedural  analysis.  For  widely  used 
programming  languages  like  C  and  Java,  pointer  alias  analysis  is  key  to  any 
interprocedural  analysis.  Thus,  for  much  of  the  chapter,  we  discuss  techniques 
needed  to  compute  pointer  aliases.  To  start,  we  present  Datalog,  a  notation 
t h at  greatly  hides  the  complexity  of  an  efficient  pointer  analysis.  We  then  de 
scribe  an  algorithm  for  pointer  analysis,  and  show  how  we  use  the  abstraction 
of  binary  decision  diagrams  (BDD's)  to  implement  the  algorithm  efficiently. 

Most  compiler  optimizations,  including  those  described  in  Chapters  9,  10, 
and  11,  are  performed  on  procedures  one  at  a  time.  We  refer  to  such  analyses  as 
intraprocedural.  These  analyses  conservatively  assume  t h at  procedures  invoked 
may  alter  the  state  of  all  the  variables  visible  to  the  procedures  and  t h at  they 
may  create  all  possible  side  effects,  such  as  modifying  any  of the  variables  visible 
to  the  procedure  or  generating  exceptions  t h at  cause  the  unwinding  of  the 
call  stack.  Intraprocedural  analysis  is  thus  relatively  simple,  albeit  imprecise. 
Some  optimizations  do  not  need  interprocedural  analysis,  while  others  may  yield 
almost  no  useful  information  without  it. 

An  interprocedural  analysis  operates  across  an  entire  program,  flowing  in 
formation  from  the  caller  to  its  callees  and  vice  versa.  One  relatively  simple  but 
useful  technique  is  to  inline  procedures,  t h at  is,  to  replace  a  procedure  invoca 
tion  by  the  body  of  the  procedure  itself  with  suitable  modifications  to  account 
for  parameter  passing  and  the  return  value.  This  method  is  applicable  only  if 
we  know  t he  target  of  the  procedure  call. 

If  procedures  are  invoked  indirectly  through  a  pointer  or  via  the  method-
dispatch  mechanism  prevalent  in  object-oriented  programming,  analysis  of  the 
program's  pointers  or  references  can  in  some  cases  determine  the  targets  of 
If  there  is  a  unique  target,  inlining  can  be  applied. 
t he  indirect  invocations. 

903 

904 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

Even  if  a  unique  target  is  determined  for  each  procedure  invocation,  inlining 
must  be  applied  judiciously. 
In  general,  it  is  not  possible  to  inline  recursive 
procedures  directly,  and  even  without  recursion,  inlining  can  expand  the  code 
size  exponentially. 

12.1  Basic  Concepts 

In  this  section,  we  introduce  call  graphs  —  graphs  t h at  tell  us  which  procedures 
can  call  which.  We  also  introduce  the  idea  of  "context  sensitivity,"  where  data 
flow  analyses  are  required  to  take  cognizance  of what  the  sequence  of procedure 
calls  has  been.  T h at  is,  context-sensitive  analysis  includes  (a  synopsis  of)  the 
current  sequence  of  activation  records  on  t he  stack,  along  with  the  current  point 
in  the  program,  when  distinguishing  among  different  "places"  in  the  program. 

12.1.1  Call  Graphs 

A  call  graph  for  a  program  is  a  set  of  nodes  and  edges  such  t h at 

1.  There  is  one  node  for  each  procedure  in  the  program. 

•2,..  There  is  one  node  for  each  call  site,  t h at  is,  a  place  in  the  program  where 

a  procedure  is  invoked. 

3.  If  call  site  c  may  call  procedure p,  then  there  is  an  edge  from  t he  node  for 

c  to  t he  node  for  p. 

Many  programs  written  in  languages  like  C  and  Fortran  make  procedure  calls 
directly,  so  the  call  target  of  each  invocation  can  be  determined  statically.  In 
t h at  case,  each  call  site  has  an  edge  to  exactly  one  procedure  in  the  call  graph. 
However,  if  the  program  includes  t he  use  of  a  procedure  parameter  or  function 
pointer,  the  target  generally  is  not  known  until  the  program  is  run  and,  in  fact, 
may  vary  from  one  invocation  to  another.  Then,  a  call  site  can  link  to  many  or 
all  procedures  in  the  call  graph. 

Indirect  calls  are  the  norm  for  object-oriented  programming  languages.  In 
particular,  when  there  is  overriding  of  methods  in  subclasses,  a  use  of  method 
m  may  refer  to  any  of  a  number  of  different  methods,  depending  on  the  subclass 
of  t he  receiver  object  to  which  it  was  applied.  The  use  of  such  virtual  method 
invocations  means  t h at  we  need  to  know  the  type  of  the  receiver  before  we  can 
determine  which  method  is  invoked. 

E x a m p le  1 2 . 1:  Figure  12.1  shows  a  C  program  t h at  declares  pf  to  be  a  global 
pointer  to  a  function  whose  type  is  "integer  to  integer."  There  are  two  functions 
of  this  type,  f  u nl  and  f  un2,  and  a  main  function  t h at  is  not  of  t he  type  t h at  pf 
points  to.  T he  figure  shows  three  call  sites,  denoted  c l,  c2,  and  c3;  t he  labels 
are  not  part  of  the  program. 

12.1. 

BASIC  CONCEPTS 

905 

i nt 

( * p f ) ( i n t ); 

i nt  f u n l ( i nt  x)  { 

c l: 

if 

(x  <  10) 
r e t u rn 

e l se 

( * p f ) ( x + 1 ); 

r e t u rn  x; 

} 

i nt  f u n 2( i nt  y)  { 

pf  =  fefunl; 
r e t u rn 

( * p f )( y ); 

c2: 

} 

v o id  m a i nO  { 

pf  =  &fun2; 
( * p f) ( 5 ); 

c3: 

} 

Figure  12.1:  A  program  with  a  function  pointer 

T he  simplest  analysis  of  what  pf  could  point  to  would  simply  observe  t he 
types  of  functions.  Functions  f u nl  and  fun2  are  of  the  same  type  as  what 
pf  points  to,  while  main  is  not.  T h u s,  a  conservative  call  graph  is  shown  in 
Fig.  12.2(a).  A  more  careful  analysis  of  the  program  would  observe  t h at  pf  is 
made  to  point  to  fun2  in  main  and  is  m a de  to  point  to  f u nl  in  fun2.  But  there 
are  no  other  assignments  to  any  pointer,  so,  in  particular,  there  is  no  way  for 
pf  to  point  to  main.  This  reasoning  yields  the  same  call  graph  as  Fig.  12.2(a). 

An  even  more  precise  analysis  would  say  t h at  at  c 3,  it  is  only  possible  for  pf 
to  point  to  f  un2,  because  t h at  call  is  preceded  immediately  by  t h at  assignment 
to  pf.  Similarly,  at  c2  it  is  only  possible  for  pf  to  point  to  f u n l.  As  a  result, 
the  initial  call  to  f u nl  can  come  only  from  fun2,  and  f u nl  does  not  change  pf, 
so  whenever  we  are  within  f u n l,  pf  points  to  f u n l. 
In  particular,  at  c l,  we 
can  be  sure  pf  points  to  f u n l.  Thus,  Fig.  12.2(b)  is  a  more  precise,  correct  call 
graph. 

• 

In  general,  the  presence  of  references  or  pointers  to  functions  or  methods 
requires  us  to  get  a  static  approximation  of the  potential  values  of all  procedure 
parameters,  function  pointers,  and  receiver  object  types.  To  make  an  accurate 
approximation,  interprocedural  analysis  is  necessary.  T he  analysis  is  iterative, 
starting  with  the  statically  observable  targets.  As  more  targets  are  discov 
ered,  the  analysis  incorporates  t he  new  edges  into  t he  call  graph  and  repeats 
discovering  more  targets  until  convergence  is  reached. 

906 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

(a) 

(b) 

Figure  12.2:  Call  graphs  derived  from  Fig.  12.1 

12.1.2  Context  Sensitivity 

Interprocedural  analysis  is  challenging  because  t he  behavior  of each  procedure  is 
dependent  upon  the  context  in  which  it  is  called.  Example  12.2  uses  t he  problem 
of  interprocedural  constant  propagation  on  a  small  program  to  illustrate  the 
significance  of  contexts. 

E x a m p le  12*2:  Consider  the  program  fragment  in  Fig.  12.3.  Function  /  is 
invoked  at  three  call  sites:  c l,  c2  and  c 3.  Constant  0  is  passed  in  as  t he 
actual  parameter  at  c l,  and  constant  243  is  passed  in  at  c2  and  c3  in  each 
iteration;  t he  constants  1  and  244  are  returned,  respectively.  Thus,  function  / 
is  invoked  with  a  constant  in  each  of t he  contexts,  but  the  value  of t he  constant 
is  context-dependent. 

As  we  shall  see,  it  is  not  possible  to  tell  t h at  t l,  t 2,  and  t3  each  are  assigned 
constant  values  (and  thus  so  is  X[i)),  unless  we  recognize  t h at  when  called  in 
context  c l,  /  returns  1,  and  when  called  in  the  other  two  contexts,  /  returns 
244.  A  naive  analysis  would  conclude  t h at  /  can  return  either  1  or  244  from 
any  call. 

• 

One  simplistic  but  extremely  inaccurate  approach  to  interprocedural  anal 
ysis,  known  as  context-insensitive  analysis, 
to  treat  each  call  and  return 
statement  as  "goto"  operations.  We  create  a  super  control-flow  graph  where, 
besides  t he  normal  intraprocedural  control flow edges,  additional  edges  are  cre 
ated  connecting 

is 

1.  Each  call  site  to  t he  beginning  of  t he  procedure  it  calls,  and 

2.  T he  return  statements  back  to  the  call  sites.1 

^ he  return  is  actually  to  the  instruction  following  the  call  site. 

12.1. 

BASIC 

CONCEPTS 

907 

for  (i  =  0; 

i  <  n; 

i++)  { 

cl: 

c2: 

c3: 

} 

tl  = f( 0 ); 
t2  =  f(243); 

t3  =  f(243); 

X[i]  =  tl+t2+t3; 

int  f  (int  v)  { 

return  (v+1); 

} 

Figure  12.3:  A  program  fragment  illustrating  t he  need  for  context-sensitive 
analysis 

Assignment  statements  are  added  to  assign  each  actual  parameter  to  its 
corresponding  formal  parameter  and  to  assign  the  returned  value  to  the  variable 
receiving  the  result.  We  can  then  apply  a  standard  analysis  intended  to  be  used 
within  a  procedure  to  t he  super  control-flow  graph  to  find  context-insensitive 
interprocedural  results.  While  simple,  this  model  abstracts  out  the  important 
relationship  between  input  and  output  values  in  procedure  invocations,  causing 
t he  analysis  to  be  imprecise. 

E x a m p le  1 2 . 3:  The  super  control-flow  graph  for  the  program  in  Fig.  12.3  is 
shown  in  Figure  12.4.  Block  BQ  is  the  function  /.  Block  B3  contains  the  call 
site  c l;  it  sets  t he  formal  parameter  v  to  0  and  then  j u m ps  to  t he  beginning  of 
/,  at  BQ.  Similarly,  B4  and £5  represent  t he  call  sites  c2  and  c 3,  respectively. 
In £4,  which  is  reached  from  the  end  of  /  (block  BQ),  we  take  t he  return  value 
from  /  and  assign  it  to  t l.  We  then  set  formal  parameter  v  to  243  and  call  / 
again,  by  jumping  to  B6.  Note  t h at  there  is  no  edge  from  B3  to  B4.  Control 
must  flow  through  /  on  the  way  from  B3  to  B4. 

B5  is  similar  to  B4.  It  receives  the  return  from  /,  assigns  the  return  value 
to  t 2,  and  initiates  the  third  call  to  /.  Block  B7  represents  the  return  from  the 
third  call  and  the  assignment  to  X[i], 

If  we  t r e at  Fig.  12.4  as  if  it  were  t he  flow  graph  of  a  single  procedure,  then 
we  would  conclude  t h at  coming  into  BQ,  V  can  have  the  value  0  or  243.  Thus, 
the  most  we  can  conclude  about  r e t v al  is  t h at  it  is  assigned  1  or  244,  but  no 
other  value.  Similarly,  we  can  only  conclude  about  t l,  t 2,  and  t3  t h at  they  can 
each  be  either  1  or  244.  Thus,  X[i]  appears  to  be  either  3,  246,  489,  or  732.  In 
contrast,  a  context-sensitive  analysis  would  separate  t he  results  for  each  of  t he 
calling  contexts  and  produces  the  intuitive  answer  described  in  Example  12.2: 
tl  is  always  1,  t2  and  t3  are  always  244,  and  X[i]  is  489. 

• 

908 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

t3  =  retval 
t4 = tl+t2 
t5 = t4+t3 
x[i]  = t5 
i = i + 1 

Bl  \  i = 0 

if  i<n goto  L 

cl: v = 0 

tl  =  retval 

c2 

: v = 243 

t2  =  retval 

c3 

: v = 243 

( ) 

f : retval  =  v+1 

Figure  12.4:  T he  control-flow  graph  for  Fig.  12.3,  treating  function  calls  as 
control flow 

12.1.3  Call  Strings 

In  Example  12.2,  we  can  distinguish  among  t he  contexts  by  just  knowing  the 
call  site  t h at  calls  the  procedure  /.  In  general,  a  calling  context  is  defined  by 
t he  contents  of  t he  entire  call  stack.  We  refer  to  the  string  of  call  sites  on  t he 
stack  as  t he  call  string. 

E x a m p le  1 2 . 4:  Figure  12.5  is  a  slight  modification  of Fig.  12.3.  Here  we  have 
replaced  the  calls  to  /  by  calls  to  g,  which  then  calls  /  with  t he  same  argument. 
There  is  an  additional  call  site,  c4,  where  g  calls  /. 

There  are  three  call  strings  to  /:  ( c l,  c4),  (c2,  c4),  and  (c3,  c4).  As  we  see 
in  this  example,  the  value  of  v  in  function  /  depends  not  on  the  immediate  or 
last  site  c4  on  the  call  string.  Rather,  the  constants  are  determined  by  t he  first 
• 
element  in  each  of  the  call  strings. 

Example  12.4  illustrates  t h at  information  relevant  to  the  analysis  can  be 
introduced  early  in  the  call  chain.  In  fact,  it  is  sometimes  necessary  to  consider 
t he  entire  call  string  to  compute  t he  most  precise  answer,  as  illustrated  in 
Example  12.5. 

12.1. 

BASIC  CONCEPTS 

909 

f or  (i  =  0; 

i  <  n; 

i++)  { 

c l: 
c 2: 
c 3: 

} 

tl  =  g ( 0 ); 
t2  =  g ( 2 4 3 ); 
t3  =  g ( 2 4 3 ); 
X [ i]  =  t l + t 2 + t 3; 

i nt  g 

( i nt  v)  { 
r e t u rn  f ( v ); 

c 4: 

} 

i nt  f 

( i nt  v)  { 

r e t u rn 

( v + 1 ); 

} 

Figure  12.5:  Program  fragment  illustrating  call  strings 

c l: 
c 2: 
c 3: 

c 4: 

c 5: 

f or  (i  =  0; 

i  <  n; 

i++)  { 

tl  =  g ( 0 ); 
t2  =  g ( 2 4 3 ); 
t3  =  g ( 2 4 3 ); 
X [ i]  = 

t l + t 2 + t 3; 

} 

i nt  g 
if 

( i nt  v)  { 
(v  >  1)  { 

r e t u rn  g ( v - l ); 

}  e l se  { 

r e t u rn 

f ( v ); 

} 

i nt  f 

( i nt  v)  { 

r e t u rn 

( v + 1 ); 

} 

Fi  gure  12.6:  Recursive  program  requiring  analysis  of  complete  call  strings 

910 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

E x a m p le  1 2 . 5:  This  example  illustrates  how  the  ability  to  reason  about  un 
bounded  call  strings  can  yield  more  precise  results.  In  Fig.  12.6  we  see  t h at  if 
g  is  called  with  a  positive  value  c,  then  g  will  be  invoked  recursively  c  times. 
Each  time  g  is  called,  the  value  of  its  parameter  v  decreases  by  1.  Thus,  the 
value  of  g's  parameter  v  in  the  context  whose  call  string  is  c 2 ( c 4 )n  is  243  -  n. 
The  effect  of  g  is  thus  to  increment  0  or  any  negative  argument  by  1,  and  to 
return  2  on  any  argument  1  or  greater. 

There  are  three  possible  call  strings  for  /.  If  we  start  with  the  call  at  c l, 
then  g  calls  /  immediately,  so  ( c l,  c5)  is  one  such  string.  If  we  start  at  c2  or 
c 3,  then  we  call  g  a  total  of  243  times,  and  then  call  /.  These  call  strings  are 
(c2, c4,  c 4 , . ..  ,  c5)  and  (c3,  c4,  c 4 , . ..  ,  c5),  where  in  each  case  there  are  242 
c4's  in  the  sequence.  In  the  first  of  these  contexts,  the  value  of  / 's  parameter 
v  is  0,  while  in  the  other  two  contexts  it  is  1. 

• 

In  designing  a  context-sensitive  analysis,  we  have  a  choice  in  precision.  For 
example,  instead  of  qualifying  the  results  by  the  full  call  string,  we  may  just 
choose  to  distinguish  between  contexts  by  their  k  most  immediate  call  sites. 
This  technique  is  known  as  fc-limiting  context  analysis.  Context-insensitive 
analysis  is  simply  a  special  case  of  fc-limiting  context  analysis,  where  k  is  0.  We 
can  find  all  the  constants  in  Example  12.2  using  a  1-limiting  analysis  and  all  the 
constants  in  Example  12.4  using  a  2-limiting  analysis.  However,  no  ^-limiting 
analysis  can  find  all  the  constants  in  Example  12.5,  provided  the  constant  243 
were  replaced  by  two  different  and  arbitrarily  large  constants. 

Instead  of  choosing  a  fixed  value  k,  another  possibility  is  to  be  fully  con 
text  sensitive  for  all  acyclic  call  strings,  which  are  strings  t h at  contain  no  re 
cursive  cycles.  For  call  strings  with  recursion,  we  can  collapse  all  recursive 
cycles,  in  order  to  bound  the  number  of  different  contexts  analyzed. 
In  Ex 
ample  12.5,  the  calls  initiated  at  call  site  c2  may  be  approximated  by  t he  call 
string:  ( c 2 , c 4 * , c 5 ).  Note  t h a t,  with  this  scheme,  even  for  programs  without 
recursion,  the  number  of  distinct  calling  contexts  can  be  exponential  in  the 
number  of  procedures  in  t he  program. 

12.1.4  Cloning-Based  Context-Sensitive  Analysis 

Another  approach  to  context-sensitive  analysis  is  to  clone  the  procedure  con 
ceptually,  one  for  each  unique  context  of interest.  We  can  then  apply  a  context-
insensitive  analysis  to  the  cloned  call  graph.  Examples  12.6  and  12.7  show  the 
equivalent  of  a  cloned  version  of  Examples  12.4  and  12.5,  respectively.  In  real 
ity,  we  do  not  need  to  clone  t he  code,  we  can  simply  use  an  efficient  internal 
representation  to  keep  track  of  the  analysis  results  of  each  clone. 

E x a m p le  1 2 .6  :  T he  cloned  version  of Fig.  12.5  is  shown  in  Fig.  12.7.  Because 
every  calling  context  refers  to  a  distinct  clone,  there  is  no  confusion.  For  ex 
ample,  gl  receives  0  as  input  and  produces  1  as  output,  and  g2  and  g3  both 
receive  243  as  input  and  produce  244  as  output. 

• 

12.1. 

BASIC  CONCEPTS 

911 

c l: 
c 2: 
c 3: 

c 4 . 1: 

f or  (i  =  0; 

i++)  { 

i  <  n; 
tl  =  g l ( 0 ); 
t2  =  g 2 ( 2 4 3 ); 
t3  =  g 3 ( 2 4 3 ); 
X [ i]  = 

t l + t 2 + t 3; 

} 

i nt  gl 

( i nt  v)  { 
r e t u rn 

f l( v ); 

} 
i nt  g2  ( i nt  v)  { 

c 4 . 2: 

r e t u rn 

f 2( v ); 

} 
i nt  g3  ( i nt  v)  { 

c 4 . 3: 

r e t u rn 

f 3( v ); 

} 

i nt  fl 

( i nt  v)  { 
r e t u rn  (v+1); 

} 
i nt  f2 

( i nt  v)  { 
r e t u rn  (v+1); 

} 
i nt  f3  ( i nt  v)  { 
r e t u rn  (v+1); 

} 

Figure  12.7:  Cloned  version  of  Fig.  12.5 

E x a m p le  1 2 . 7:  T he  cloned  version  of Example  12.5  is  shown  in  Fig.  12.8.  For 
procedure  g,  we  create  a  clone  to  represent  all  instances  of g  t h at  are  first  called 
from  sites  c l,  c2,  and  c 3.  In  this  case,  the  analysis  would  determine  t h at  the 
invocation  at  call  site  cl  returns  1,  assuming  the  analysis  can  deduce  t h at  with 
v  =  0,  t he  test  v  >  1  fails.  This  analysis  does  not  handle  recursion  well  enough 
to  produce  the  constants  for  call  sites  c2  and  c 3,  however. 

• 

12.1.5  Summary-Based  Context-Sensitive  Analysis 

Summary-based  interprocedural  analysis  is  an  extension  of  region-based  anal 
ysis.  Basically,  in  a  summary-based  analysis  each  procedure  is  represented  by 
a  concise  description  ("summary")  t h at  encapsulates  some  observable  behavior 
of  the  procedure.  The  primary  purpose  of  the  summary  is  to  avoid  reanalyzing  * 
a  procedure's  body  at  every  call  site  t h at  may  invoke  the  procedure. 

Let  us  first  consider  t he  case  where  there  is  no  recursion.  Each  procedure  is 
modeled  as  a  region  with  a  single  entry  point,  with  each  caller-callee  pair  sharing 

912 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

cl: 

c2: 

c3: 

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

tl  =  gl(0); 

t2  =.g2(243); 

t3  =  g3(243); 

X[i]  =  tl+t2+t3; 

} 

int gl (int v) { 
if (v > 1) { 

c4.1: 

return  gl(v-l); 

}  else  { 

c5.1: 

return  fl(v); 

} 

int g2 (int v) { 
if (v > 1) { 

c4.2: 

return  g2(v-l); 

}  else  { 

c5.2: 

return  f2(v); 

} 

int g3 (int v) { 

if (v > 1) { 

c4.3: 

return  g3(v-l); 

}  else  { 

c5.3: 

return  f3(v); 

} 

int fl (int v) { 
return  (v+1); 

} 
int f2 (int v) { 
return  (v+1); 

} 
int f3 (int v) { 
return  (v+1); 

} 

Figure  12.8:  Cloned  version  of  Fig.  12.6 

12.1. 

BASIC  CONCEPTS 

913 

an  outer-inner  region  relationship.  The  only  difference  from  the  intraprocedural 
version  is  t h a t,  in  the  interprocedural  case,  a  procedure  region  can  be  nested 
inside  several  different  outer  regions. 
T he  analysis  consists  of  two  parts: 

1.  A  bottom-up  phase  t h at  computes  a  transfer  function  to  summarize  the 

effect  of  a  procedure,  and 

2.  A  top-down  phase  t h at  propagates  caller  information  to  compute  results 

of  the  callees. 

To  get  fully  context-sensitive  results,  information  from  different  calling  contexts 
must  propagate  down  to  the  callees  individually.  For  a  more  efficient,  but  less 
precise  calculation,  information  from  all  callers  can  be  combined,  using  a  meet 
operator,  then  propagated  down  to  the  callees. 

E x a m p le  1 2 .8  :  For  constant  propagation,  each  procedure  is  summarized  by  a 
transfer  function  specifying  how  it  would  propagate  constants  through  its  body. 
In  Example  12.2,  we  can  summarize  /  as  a  function  t h a t,  given  a  constant  c  as 
an  actual  parameter  to  v,  returns  the  constant  c+1.  Based  on  this  information, 
the  analysis  would  determine  t h at  t l,  t 2,  and  t3  have  the  constant  values  1, 
244,  and  244,  respectively.  Note  t h at  this  analysis  does  not  suffer  the  inaccuracy 
due  to  unrealizable  call  strings. 

Recall  t h at  Example  12.4  extends  Example  12.2  by  having  g  call  /.  Thus, 
we  could  conclude  t h at  the  transfer  function  for  g  is  the  same  as  the  transfer 
function  for  /.  Again  we  conclude  t h at  t l,  t 2,  and  t3  have  the  constant  values 
1,  244,  and  244,  respectively. 

Now,  let  us  consider  what  is  the  value  of  parameter  v  in  function  /  for 
Example  12,2.  As  a  first  cut,  we  can  combine  all  the  results  for  all  calling 
contexts.  Since  v  may  have  values  0  or  243,  we  can  simply  conclude  t h at  v  is 
not  a  constant.  This  conclusion  is  fair,  because  there  is  no  constant  t h at  can 
replace  v  in  the  code. 

If we  desire  more  precise  results,  we  can  compute  specific  results  for  contexts 
of  interest. 
Information  must  be  passed  down  from  the  context  of  interest  to 
determine  the  context-sensitive  answer.  This  step  is  analogous  to  the  top-down 
pass  in  region-based  analysis.  For  example,  the  value  of  v  is  0  at  call  site  cl 
and  243  at  sites  c2  and  c3.  To  get  the  advantage  of  constant  propagation 
within  /,  we  need  to  capture  this  distinction  by  creating  two  clones,  with  the 
first  specialized  for  input  value  0  and  the  latter  with  value  243,  as  shown  in 
Fig.  12.9. 

• 

W i th  Example  12.8,  we  see  t h a t,  in  the  end,  if  we  wish  to  compile  the 
code  differently  in  different  contexts,  we  still  need  to  clone  the  code.  The 
difference  is  t h at  in  the  cloning-based  approach,  cloning  is  performed  prior  to 
the  analysis,  based  on  the  call  strings. 
In  the  summary-based  approach,  the 
cloning  is  performed  after  the  analysis,  using  the  analysis  results  as  a  basis. 

914 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

c l: 
c 2: 
c 3: 

f or  (i  =  0; 

i++)  { 

i  <  n; 
tl  =  f 0 ( 0 ); 
t2  =  f 2 4 3 ( 2 4 3 ); 
t3  =  f 2 4 3 ( 2 4 3 ); 
X [ i]  =  t l + t 2 + t 3; 

} 

i nt  fO 

( i nt  v)  { 

r e t u rn 

( 1 ); 

} 

i nt  f 2 43  ( i nt  v)  { 

r e t u rn 

( 2 4 4 ); 

} 

Figure  12.9:  Result  of propagating  all  possible  constant  arguments  to  t he  func 
tion 

/ 

Even  if cloning  is  not  applied,  in  the  summary-based  approach  inferences  about 
the  effect  of  a  called  procedure  are  made  accurately,  without  t he  problem  of 
unrealizable  paths. 

Instead  of cloning  a  function,  we  could  also  inline  the  code.  Inlining  has  the 

additional  effect  of  eliminating  the  procedure-call  overhead  as  well. 

We  can  handle  recursion  by  computing  the  fixedpoint  solution.  In  the  pres 
ence  of  recursion,  we  first  find  the  strongly  connected  components  in  the  call 
graph.  In  the  bottom-up  phase,  we  do  not  visit  a  strongly  connected  component 
unless  all  its  successors  have  been  visited.  For  a  nontrivial  strongly  connected 
component,  we  iteratively  compute  the  transfer  functions  for  each  procedure  in 
the  component  until  convergence  is  reached;  t h at  is,  we  iteratively  u p d a te  t he 
transfer  functions  until  no  more  changes  occur. 

12.1.6  Exercises  for  Section  12.1 

E x e r c i se  1 2 . 1 . 1:  In  Fig.  12.10  is  a  C  program  with  two  function  pointers,  p 
and  q.  N  is  a  constant  t h at  could  be  less  t h an  or  greater  t h an  10.  Note  t h at 
t he  program  results  in  an  infinite  sequence  of  calls,  but  t h at  is  of  no  concern 
for  the  purposes  of  this  problem. 

a)  Identify  all  the  call  sites  in  this  program. 

b)  For  each  call  site,  what  can  p  point  to?  W h at  can  q  point  to? 

c)  Draw  t he  call  graph  for  this  program. 

!  d)  Describe  all  the  call  strings  for  /  and  g. 

12.1. 

BASIC 

CONCEPTS 

915 

i nt 
i nt 

( * p ) ( i n t ); 
( * q ) ( i n t ); 

i nt  f ( i nt 
if 

i)  { 
(i  <  10) 

•Cp = &g; 

r e t u rn 

( * q ) ( i ) ;} 

fp  =  &f; 

r e t u rn 

( * p ) ( i ) ;} 

e l se 

} 

i nt  g ( i nt 
if 

j)  { 
(j  <  10) 

{q  =  &f; 

r e t u rn 

( * p ) ( j ) ;} 

e l se 

"(q  =  &g; 

r e t u rn 

( * q ) ( j ) ;} 

v o id  m a i n ()  { 

p  =  &f; 
q  =  &g; 
( * p ) ( ( * q ) ( N ) ); 

Figure  12.10:  P r o g r am  for  Exercise  12.1.1 

E x e r c i se  1 2 . 1 .2  :  In  Fig.  12.11  is  a  function  id  t h at  is  the  "identity  function"; 
it  returns  exactly  what  it  is  given  as  an  argument.  We  also  see  a  code  fragment 
consisting  of  a  branch  and  following  assignment  t h at  sums  x  +  y. 

a)  Examining  t he  code,  what  can  we  tell  about  the  value  of  z  at  the  end? 

b)  Construct  the  flow  graph  for  the  code  fragment,  treating  the  calls  to  id 

as  control  flow. 

c)  If  we  run  a  constant-propagation  analysis,  as  in  Section  9.4,  on  your  flow 

graph  from  (b),  what  constant  values  are  determined? 

d)  W h at  are  all  the  call  sites  in  Fig.  12.11? 

e)  W h at  are  all  the  contexts  in  which  id  is  called? 

f)  Rewrite  the  code  of  Fig.  12.11  by  cloning  a  new  version  of  id  for  each 

context  in  which  it  is  called. 

g)  Construct  the  flow  graph  of your  code  from  (f),  treating  the  calls  as  control 

flow. 

916 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

int  id(int  x)  {  return  x;} 

if  (a ==  1)  { 

else 

{ 

z  =  x+y; 

x  =  id(2);  y  =  id(3);  } 
=  id(3);  y  =  id(2);  } 
x 

Figure  12.11:  Code  fragment  for  Exercise  12.1.2 

h)  Perform  a  constant-propagation  analysis  on  your  flow  graph  from  (g). 

W h at  constant  values  are  determined  now? 

12.2  Why  Interprocedural  Analysis? 

Given  how  hard  interprocedural  analysis  is,  let  us  now  address  the  important 
problem  of  why  and  when  we  wish  to  use  interprocedural  analysis.  Although 
we  used  constant  propagation  to  illustrate  interprocedural  analysis,  this  inter 
procedural  optimization  is  neither  readily  applicable  nor  particularly  beneficial 
when  it  does  occur.  Most  of  t he  benefits  of  constant  propagation  can  be  ob 
tained  simply  by  performing  intraprocedural  analysis  and  inlining  procedure 
calls  of  the  most  frequently  executed  sections  of  code. 

However,  there  are  many  reasons  why  interprocedural  analysis  is  essential. 
Below,  we  describe  several  important  applications  of  interprocedural  analysis. 

12.2.1  Virtual  Method  Invocation 

As  mentioned  above,  object-oriented  programs  have  many  small  methods. 
If 
we  only  optimize  one  method  at  a  time,  then  there  are  few  opportunities  for 
optimization.  Resolving  method  invocation  enables  optimization.  A  language 
like  Java  dynamically  loads  its  classes.  As  a  result,  we  do  not  know  at  compile-
time  to  which  of  (perhaps)  many  methods  named  m  a  use  of  "m"  refers  in  an 
invocation  such  as  x.mQ. 

Many  Java  implementations  use  a just-in-time  compiler  to  compile  its  byte 
codes  at  run  time.  One  common  optimization  is  to  profile  t he  execution  and 
determine  which  are  t he  common  receiver  types.  We  can  then  inline  the  meth 
ods  t h at  are  most  frequently  invoked.  T he  code  includes  a  dynamic  check  on  the 
type  and  executes  the  inlined  methods  if  the  run-time  object  has  t he  expected 
type. 

Another  approach  to  resolving  uses  of  a  method  name  m  is  possible  as  long 
as  all  t he  source  code  is  available  at  compile  time.  Then,  it  is  possible  to 
perform  an  interprocedural  analysis  to  determine  t he  object  types.  If  t he  type 
for  a  variable  x  turns  out  to  be  unique,  then  a  use  of  x.mQ  can  be  resolved. 

12.2. 

WHY 

INTERPROCEDURAL 

ANALYSIS? 

917 

We  know  exactly  what  method  m  refers  to  in  this  context.  In  t h at  case,  we  can 
in-line  t he  code  for  this  m,  and  the  compiler  does  not  even  have  to  include  a 
test  for  t he  t y pe  of  x. 

12.2.2  Pointer  Alias  Analysis 

Even  if we  do  not  wish  to  perform  interprocedural  versions  of t he  common  data 
flow  analyses  like  reaching  definitions,  these  analyses  can  in  fact  benefit  from 
interprocedural  pointer  analysis.  All  the  analyses  presented  in  Chapter  9  apply 
only  to  local  scalar  variables  t h at  cannot  have  aliases.  However,  use  of pointers 
is  common,  especially  in  languages  like  C.  By  knowing  whether  pointers  can  be 
aliases  (can  point  to  the  same  location),  we  can  improve  the  accuracy  of  the 
techniques  from  Chapter  9. 

E x a m p le  1 2 . 9:  Consider  the  following  sequence  of  three  statements,  which 
might  form  a  basic  block: 

*p 
*q 
x 

=  i; 
=  2; 
=  * p; 

Without  knowing  if p  and  q  can  point  to  the  same  location  —  t h at  is,  whether 
they  can  be  aliases  —  we  cannot  conclude  t h at  x  is  equal  to  1  at  the  end  of the 
block. 

• 

12.2.3  Parallelization 

As  discussed  in  Chapter  11,  the  most  effective  way  to  parallelize  an  applica 
tion  is  to  find  the  coarsest  granularity  of  parallelism,  such  as  t h at  found  in 
the  outermost  loops  of  a  program.  For  this  task,  interprocedural  analysis  is 
of  great  importance.  There  is  a  significant  difference  between  scalar  optimiza 
tions  (those  based  on  values  of  simple  variables,  as  discussed  in  Chapter  9) 
and  parallelization.  In  parallelization,  just  one  spurious  d a ta  dependence  can 
render  an  entire  loop  not  parallelizable,  and  greatly  reduce  the  effectiveness 
of  the  optimization.  Such  amplification  of  inaccuracies  is  not  seen  in  scalar 
optimizations. 
In  scalar  optimization,  we  only  need  to  find  t he  majority  of 
the  optimization  opportunities.  Missing  one  opportunity  or  two  seldom  makes 
much  of  a  difference. 

12.2.4  Detection  of  Software  Errors  and  Vulnerabilities 

Interprocedural  analysis  is  not  only  important  for  optimizing  code.  The  same 
techniques  can  be  used  to  analyze  existing  software  for  many  kinds  of  coding 
errors.  These  errors  can  render  software  unreliable;  coding  errors  t h at  hackers 
can  exploit  to  take  control  of,  or  otherwise  damage,  a  computer  system  can 
pose  significant  security  vulnerability  risks. 

918 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

Static  analysis  is  useful  in  detecting  occurrences  of  many  common  error 
patterns.  For  example,  a  d a ta  item  must  be  guarded  by  a  lock.  As  another 
example,  disabling  an  interrupt  in  the  operating  system  must  be  followed  by  a 
re-enabling  of  the  interrupt.  Since  a  significant  source  of  errors  is  the  incon 
sistencies  t h at  span  procedure  boundaries,  interprocedural  analysis  is  of  great 
importance.  PREfix  and  Metal  are  two  practical  tools  t h at  use  interprocedural 
analysis  effectively  to  find  many  programming  errors  in  large  programs.  Such 
tools  find  errors  statically  and  can  improve  software  reliability  greatly.  How 
ever,  these  tools  are  both  incomplete  and  unsound,  in  t he  sense  t h at  they  may 
not  find  all  errors,  and  not  all  reported  warnings  are  real  errors.  Unfortunately, 
the  interprocedural  analysis  used  is  sufficiently  imprecise  t h a t,  were  the  tools 
to  report  all  potential  errors,  the  large  number  of  false  warnings  would  render 
the  tools  unusable.  Nevertheless,  even  though  these  tools  are  not  perfect,  their 
systematic  use  has  been  shown  to  greatly  improve  software  reliability. 

When  it  comes  to  security  vulnerabilities,  it  is  highly  desirable  t h at  we  find 
all  the  potential  errors  in  a  program.  In  2006,  two  of the  "most  popular"  forms 
of  intrusions  used  by  hackers  to  compromise  a  system  were 

1.  Lack  of input  validation  on  Web  applications:  SQL  injection  is  one  of  the 
most  popular  forms  of  such  vulnerability  whereby  hackers  gain  control  of 
a  database  by  manipulating  inputs  accepted  by  web  applications. 

2.  Buffer  overflows  in  C  and  C ++  programs.  Because  C  and  C ++  do  not 
check  if  accesses  to  arrays  are  in  bounds,  hackers  can  write  well-crafted 
strings  into  unintended  areas  and  hence  gain  control  of  the  program's 
execution. 

In  the  next  section,  we  shall  discuss  how  we  can  use  interprocedural  analysis  to 
protect  programs  against  such  vulnerabilities. 

12.2.5  SQL  Injection 

SQL  injection  refers  to  the  vulnerability  where  hackers  can  manipulate  user 
input  to  a  Web  application  and  gain  unintended  access  to  a  database.  For 
example,  banks  want  their  users  to  be  able  to  make  transactions  online,  provided 
they  supply  their  correct  password.  A  common  architecture  for  such  a  system 
is  to  have  the  user  enter  strings  into  a  Web  form,  and  then  to  have  those 
strings  form  part  of  a  database  query  written  in  the  SQL  language.  If  systems 
developers  are  not  careful,  t he  strings  provided  by  the  user  can  alter  t he  meaning 
of  the  SQL  statement  in  unexpected  ways. 

E x a m p le  1 2 . 1 0:  Suppose  a  bank  offers  its  customers  access  to  a  relation 

A c c t D a t a ( n a m e,  p a s s w o r d,  b a l a n c e) 

T h at  is,  this  relation  is  a  table  of  triples,  each  consisting  of  the  name  of  a 
customer,  t he  password,  and  t he  balance  of the  account.  The  intent  is  t h at  cus 
tomers  can  see  their  account  balance  only  if  they  provide  b o th  their  name  and 

12.2. 

WHY 

INTERPROCEDURAL  ANALYSIS? 

919 

their  correct  password.  Having  a  hacker  see  an  account  balance  is  not  the  worst 
thing  t h at  could  occur,  but  this  simple  example  is  typical  of  more  complicated 
situations  where  the  hacker  could  execute  payments  from  the  account. 

T he  system  might  implement  a  balance  inquiry  as  follows: 

1.  Users  invoke  a  Web  form  where  they  enter  their  name  and  password. 

2.  T he  name  is  copied  to  a  variable  n  and  the  password  to  a  variable  p. 

3.  Later,  perhaps  in  some  other  procedure,  the  following  SQL  query  is  exe 

cuted: 

SELECT  b a l a n ce  FROM  A c c t D a ta 
WHERE  name  = 

5: n'  and  p a s s w o rd  = 

' : p' 

For  readers  not  familiar  with  SQL,  this  query  says:  "Find  in  the  table  A c c t D a ta 
a  row  with  the  first  component  (name)  equal  to  the  string  currently  in  variable 
n  and  t he  second  component  (password)  equal  to  the  string  currently  in  variable 
p;  print  the  third  component  (balance)  of t h at  row."  Note  t h at  SQL  uses  single 
quotes,  not  double  quotes,  to  delimit  strings,  and  the  colons  in  front  of  n  and 
p  indicate  t h at  they  are  variables  of  the  surrounding  language. 

Suppose  the  hacker,  who  wants  to  find  Charles  Dickens'  account  balance, 

supplies  t he  following  values  for  the  strings  n  and  p: 

n  =  C h a r l es  D i c k e n s'  — 

p  =  who  c a r es 

The  effect  of  these  strange  strings  is  to  convert  the  query  into 

SELECT  b a l a n ce  FROM  A c c t D a ta 
WHERE  name  = 

' C h a r l es  D i c k e n s'  —'  and  p a s s w o rd  = 

'who  c a r e s' 

In  many  database  systems  —  is  a  comment-introducing  token  and  has  the  effect 
of making  whatever  follows  on  t h at  line  a  comment.  As  a  result,  t he  query  now 
asks  t he  database  system  to  print  the  balance  for  every  person  whose  name  is 
' C h a r l es  D i c k e n s ',  regardless  of  the  password  t h at  appears  with  t h at  name 
in  a  name-password-balance  triple.  T h at  is,  with  comments  eliminated,  the 
query  is: 

SELECT  b a l a n ce  FROM  A c c t D a ta 
WHERE  name  = 

' C h a r l es  D i c k e n s' 

• 

In  Example  12.10,  the  "bad"  strings  were  kept  in  two  variables,  which  might 
be  passed  between  procedures.  However,  in  more  realistic  cases,  these  strings 
might  be  copied  several  times,  or  combined  with  others  to  form  t he  full  query. 
We  cannot  hope  to  detect  coding  errors  t h at  create  SQL-injection  vulnerabilities 
without  doing  a  full  interprocedural  analysis  of  the  entire  program. 

920 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

12.2.6  Buffer  Overflow 

A  buffer  overflow  attack  occurs  when  carefully  crafted  d a ta  supplied  by  the  user 
writes  beyond  the  intended  buffer  and  manipulates  the  program  execution.  For 
example,  a  C  program  may  read  a  string  s  from  the  user,  and  then  copy  it  into 
a  buffer  b  using  the  function  call: 

strcpy(b,s); 

If  the  string  s  is  actually  longer  t h an  the  buffer  b,  then  locations  t h at  are  not 
part  of  b  will  have  their  values  changed.  T h at  in  itself  will  probably  cause  the 
program  to  malfunction  or  at  least  to  produce  the  wrong  answer,  since  some 
d a ta  used  by  the  program  will  have  been  changed. 

But  worse,  the  hacker  who  chose  the  string  s  can  pick  a  value  t h at  will  do 
more  t h an  cause  an  error.  For  example,  if  the  buffer  is  on  the  run-time  stack, 
then  it  is  near  t he  return  address  for  its  function.  An  insidiously  chosen  value 
of  s  may  overwrite  the  return  address,  and  when  the  function  returns,  it  goes 
If  hackers  have  detailed  knowledge  of  the 
to  a  place  chosen  by  the  hacker. 
surrounding  operating  system  and  hardware,  they  may  be  able  to  execute  a 
command  t h at  will  give  them  control  of  the  machine  itself.  In  some  situations, 
they  may  even  have  the  ability  to  have  the  false  return  address  transfer  control 
to  code  t h at  is  part  of  the  string  s,  thus  allowing  any  sort  of  program  to  be 
inserted  into  the  executing  code. 

To  prevent  buffer  overflows,  every  array-write  operation  must  be  statically 
proven  to  be  within  bounds,  or  a  proper  array-bounds  check  must  be  performed 
dynamically.  Because  these  bounds  checks  need  to  be  inserted  by  hand  in  C 
and  C ++  programs,  it  is  easy  to  forget  to  insert  t he  test  or  to  get  t he  test 
wrong.  Heuristic  tools  have  been  developed  t h at  will  check  if at  least  some  test, 
though  not  necessarily  a  correct  test,  has  been  performed  before  a strcpy  is 
called. 

Dynamic  bounds  checking  is  unavoidable  because  it  is  impossible  to  deter 
mine  statically  the  size  of users'  input.  All  a  static  analysis  can  do  is  assure  t h at 
the  dynamic  checks  have  been  inserted  properly.  Thus,  a  reasonable  strategy  is 
to  have  t he  compiler  insert  dynamic  bounds  checking  on  every  write,  and  use 
static  analysis  as  a  means  to  optimize  away  as  many  bounds  check  as  possible. 
It  is  no  longer  necessary  to  catch  every  potential  violation;  moreover,  we  only 
need  to  optimize  only  those  code  regions  t h at  execute  frequently. 

Inserting  bounds  checking  into  C  programs  is  nontrivial,  even  if  we  do  not 
mind  the  cost.  A  pointer  may  point  into  the  middle  of  some  array,  and  we  do 
not  know  the  extent  of  t h at  array.  Techniques  have  been  developed  to  keep 
track  of  t he  extent  of  the  buffer  pointed  to  by  each  pointer  dynamically.  This 
information  allows  the  compiler  to  insert  array  bounds  checks  for  all  accesses. 
Interestingly  enough,  it  is  not  advisable  to  halt  a  program  whenever  a  buffer 
overflow  is  detected.  In  fact,  buffer  overflows  do  occur  in  practice,  and  a  pro 
gram would  likely  fail  if we  disable  all  buffer  overflows.  T he  solution  is  to  extend 
the  size  of  the  array  dynamically  to  accommodate  for  the  buffer  overruns. 

12.3. 

A  LOGICAL  REPRESENTATION  OF  DATA  FLOW 

921 

Interprocedural  analysis  can  be  used  to  speed  up  the  cost  of  dynamic  ar 
ray  bounds  checks.  For  example,  suppose  we  are  interested  only  in  catching 
buffer  overflows  involving  user-input  strings,  we  can  use  static  analysis  to  de 
termine  which  variables  may  hold  contents  provided  by  the  user.  Like  SQL 
injection,  being  able  to  track  an  input  as  it  is  copied  across  procedures  is  useful 
in  eliminating  unnecessary  bounds  checks. 

12.3  A  Logical  Representation  of Data  Flow 

To  this  point,  our  representation  of  data-flow  problems  and  solutions  can  be 
termed  "set-theoretic."  T h at  is,  we  represent  information  as  sets  and  compute 
results  using  operators  like  union  and  intersection.  For  instance,  when  we  in 
troduced  the  reaching-definitions  problem  in  Section  9.2.4,  we  computed IN[B] 
and  OUT[J3]  for  a  block  B,  and  we  described  these  as  sets  of  definitions.  We 
represented  the  contents  of  the  block  B  by  its  gen  and  kill  sets. 

To  cope  with  the  complexity  of interprocedural  analysis,  we  now  introduce  a 
more  general  and  succinct  notation  based  on  logic.  Instead  of  saying  something 
like  "definition  D  is  in  I N [ £ ? ] ,"  we  shall  use  a  notation  like  in(B,D)  to  mean 
the  same  thing.  Doing  so  allows  us  to  express  succinct  "rules"  about  inferring 
program  facts.  It  also  allows  us  to  implement  these  rules  efficiently,  in  a  way 
t h at  generalizes  the  bit-vector  approach  to  set-theoretic  operations.  Finally, 
the  logical  approach  allows  us  to  combine  what  appear  to  be  several  indepen 
dent  analyses  into  one,  integrated  algorithm.  For  example,  in  Section  9.5  we 
described  partial-redundancy  elimination  by  a  sequence  of  four  data-flow  anal 
yses  and  two  other  intermediate  steps.  In  the  logical  notation,  all  these  steps 
could  be  combined  into  one  collection  of  logical  rules  t h at  are  solved  simulta 
neously. 

12.3.1 

Introduction  to  Datalog 

Catalog  is  a  language  t h at  uses  a  Prolog-like  notation,  but  whose  semantics  is 
far  simpler  t h an  t h at  of  Prolog.  To  begin,  the  elements  of  Datalog  are  atoms 
of  the 

form  p(X1,X2,... 

,  Xn).  Here, 

1.  p  is  a  predicate  —  a  symbol  t h at  represents  a  type  of  statement  such  as 

"a  definition  reaches  the  beginning  of  a  block." 

2.  Xi,X2,... 

,Xn  are  terms  such  as  variables  or  constants.  We  shall  also 

allow  simple  expressions  as  arguments  of  a  predicate.2 

A  ground  atom  is  a  predicate  with  only  constants  as  arguments.  Every 

ground  atom  asserts  a  particular  fact,  and  its  value  is  either  true  or  false. 

It 

2Formally,  such  terms  are  built  from  function  symbols  and  complicate  the  implementation 
of  Datalog  considerably.  However,  we  shall  use  only  a  few  operators,  such  as  addition  or 
subtraction  of constants,  in  contexts  that  do  not  complicate  matters. 

922 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

is  often  convenient  to  represent  a  predicate  by  a  relation,  or  table  of  its  true 
ground  atoms.  Each  ground  atom  is  represented  by  a  single  row,  or  tuple,  of 
the  relation.  T he  columns  of  the  relation  are  named  by  attributes,  and  each 
tuple  has  a  component  for  each  attribute.  The  attributes  correspond  to  the 
components  of  the  ground  atoms  represented  by  the  relation.  Any  ground 
atom  in  the  relation  is  true,  and  ground  atoms  not  in  t he  relation  are  false. 

E x a m p le  1 2 . 1 1:  Let  us  suppose  the  predicate  in(B,D)  means  "definition  D 
reaches  the  beginning  of block  BP  Then  we  might  suppose  t h a t,  for  a  particular 
flow  graph, 
is  true,  as  are  in(b2,di)  and  in(b2,d2).  We  might  also 
suppose  t h at  for  this  flow  graph,  all  other  in  facts  are  false.  Then  the  relation 
in  Fig.  12.12  represents  the  value  of  this  predicate  for  this  flow  graph. 

in{b\,d\) 

h 

B  D 
di 
di 
d2 

b2 

Figure  12.12:  Representing  the  value  of  a  predicate  by  a  relation 

The  attributes  of the  relation  are  B  and  D.  The  three  tuples  of  the  relation 

are  (&i,di), 

(b2,di),  and  (b2,d2). 

• 

We  shall  also  see  at  times  an  atom  t h at  is  really  a  comparison  between 
In  these 
variables  and  constants.  An  example  would  be  X  ^  Y  or  X  =  10. 
examples,  t he  predicate  is  really  t he  comparison  operator.  T h at  is,  we  can 
think  of  X  =  10  as  if  it  were  written  in  predicate  form:  equals(X,  10).  There  is 
an  important  difference  between  comparison  predicates  and  others,  however.  A 
comparison  predicate  has  its  s t a n d a rd  interpretation,  while  an  ordinary  pred 
icate  like  in  means  only  what  it  is  defined  to  mean  by  a  Datalog  program 
(described  next). 

A  literal  is  either  an  a t om  or  a  negated  a t o m.  We  indicate  negation  with 
the  word NOT  in  front  of  the  atom.  Thus,  MOT  in(B,D)  is  an  assertion  t h at 
definition  D  does  not  reach  the  beginning  of  block  B. 

12.3.2  Datalog  Rules 

Rules  are  a  way  of  expressing  logical  inferences.  In  Datalog,  rules  also  serve  to 
suggest  how  a  computation  of  the  true  facts  should  be  carried  out.  T he  form 
of  a  rule  is 

H  :  -  Bi  k  B2  k 

• 

• 

• 

&  Bn 

The  components  are  as  follows: 

•  H  and  Bi,  B2,  •  •.  ,Bn  are  literals  —  either  atoms  or  negated  atoms. 

12.3. 

A 

LOGICAL  REPRESENTATION  OF  DATA  FLOW 

923 

Datalog  Conventions 

We  shall  use  the  following  conventions  for  Datalog  programs: 

1.  Variables  begin  with  a  capital  letter. 

2.  All  other  elements  begin  with  lowercase  letters  or  other  symbols  such 
as  digits.  These  elements  include  predicates  and  constants  t h at  are 
arguments  of  predicates. 

•  H 

is  the  head  and  Bi,B2,..- 

,Bn  form 

the  body  of  the  rule. 

•  Each  of  the  IV  s  is  sometimes  called  a  subgoal  of  the  rule. 

We  should  read  the  : -  symbol  as  "if."  The  meaning  of  a  rule  is  "the  head 
is  t r ue  if  t he  body  is  true."  More  precisely,  we  apply  a  rule  to  a  given  set  of 
ground  atoms  as  follows.  Consider  all  possible  substitutions  of  constants  for 
the  variables  of  the  rule.  If  this  substitution  makes  every  subgoal  of  the  body 
true  (assuming  t h at  all  and  only  the  given  ground  atoms  are  true),  then  we  can 
infer  t h at  the  head  with  this  substitution  of  constants  for  variables  is  a  true 
fact.  Substitutions  t h at  do  not  make  all  subgoals  true  give  us  no  information; 
the  head  may  or  may  not  be  true. 

A  Datalog  program is  a  collection  of rules.  This  program  is  applied  to  "data," 
t h at  is,  to  a  set  of  ground  atoms  for  some  of  the  predicates.  The  result  of  the 
program  is  the  set  of ground  atoms  inferred  by  applying  the  rules  until  no  more 
inferences  can  be  made. 

E x a m p le  1 2 . 12  :  A  simple  example  of  a  Datalog  program  is  the  computation 
of  paths  in  a  graph,  given  its  (directed)  edges.  T h at  is,  there  is  one  predicate 
edge(X,  Y)  t h at  means  "there  is  an  edge  from  node  X  to  node  Y."  Another 
predicate path(X,  Y)  means  t h at  there  is  a  p a th  from  X  to  Y.  The  rules  defining 
paths  are: 

1) 
2) 

path(X,Y) 
path(X,  Y) 

:- 
:  - 

edge(X,Y) 
path(X,  Z)  k  path{Z,  Y) 

The  first  rule  says  t h at  a  single  edge  is  a  path.  T h at  is,  whenever  we  replace 
variable  X  by  a  constant  a  and  variable  Y  by  a  constant  6,  and  edge(a,b)  is 
true  (i.e.,  there  is  an  edge  from  node  a  to  node  b),  then  path(a,b)  is  also  true 
(i.e.,  there  is  a  p a th  from  a  to  b).  The  second  rule  says  t h at  if  there  is  a  p a th 
from  some  node  X  to  some  node  Z,  and  there  is  also  a  p a th  from  Z  to  node  Y, 
then  there  is  a  p a th  from  X  to  Y.  This  rule  expresses  "transitive  closure."  Note 
t h at  any  p a th  can  be  formed  by  taking  the  edges  along  the  p a th  and  applying 
the  transitive  closure  rule  repeatedly. 

924 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

For  instance,  suppose  t h at  the  following  facts  (ground  atoms)  are  true: 
rule  with 
edge(l,2),  edge(2,3),  and  edge(3,4). 
three  different  substitutions 
infer  path(l,2),  path(2,3),  and  path(3,4).  As 
an  example,  substituting  X  =  1  and  Y  =  2  instantiates  the  first  rule  to  be 
path(l,2) 

-  edge(l,2).  Since  edge(l,2) 

true,  we  infer  path(l,2). 

Then  we  can  use 

the  first 

to 

is 

: 

W i th  these  three  path  facts,  we  can  use  the  second  rule  several  times. 
If 
we  substitute  X  =  1,  Z  =  2,  and  Y  =  3,  we  instantiate  t he  rule  to  be 
path(l,3) 
Since  both  subgoals  of  the  body  have 
been  inferred,  they  are  known  to  be  true,  so  we  may  infer  the  head:  path(l,3). 
Then,  the  substitution  X  =  1,  Z  =  3,  and  Y  =  4  lets  us  infer  the  head 
path(l,4);  t h at  is,  there  is  a  p a th  from  node  1  to  node  4. 

:  -  path(l,2)  &  path(2,3). 

• 

12.3.3 

Intensional  and  Extensional  Predicates 

It  is  conventional  in  Datalog  programs  to  distinguish  predicates  as  follows: 

1.  E D B,  or  extensional  database,  predicates  are  those  t h at  are  defined  a-
priori.  T h at  is,  their  true  facts  are  either  given  in  a  relation  or  table,  or 
they  are  given  by  the  meaning  of  the  predicate  (as  would  be  the  case  for 
a  comparison  predicate,  e.g.). 

2.  IDB,  or  intensional  database,  predicates  are  defined  only  by  the  rules. 

A  predicate  must  be  IDB  or  E D B,  and  it  can  be  only  one  of these.  As  a  result, 
any  predicate  t h at  appears  in  t he  head  of  one  or  more  rules  must  be  an  IDB 
predicate.  Predicates  appearing  in  the  body  can  be  either  IDB  or  E D B.  For 
instance,  in  Example  12.12,  edge  is  an  E DB  predicate  and  path  is  an  IDB 
predicate.  Recall  t h at  we  were  given  some  edge  facts,  such  as  edge(l,2),  but 
the  path  facts  were  inferred  by  the  rules. 

W h en  Datalog  programs  are  used  to  express  data-flow  algorithms,  t he  E DB 
predicates  are  computed  from  the  flow  graph  itself. 
IDB  predicates  are  then 
expressed  by  rules,  and  the  data-flow  problem  is  solved  by  inferring  all  possible 
IDB  facts  from  the  rules  and  the  given  E DB  facts. 

E x a m p le  1 2 . 13  :  Let  us  consider  how  reaching  definitions  might  be  expressed 
in  Datalog.  First,  it  makes  sense  to  think  on  a  statement  level,  rather  t h an 
a  block  level;  t h at  is,  the  construction  of  gen  and  kill  sets  from  a  basic  block 
will  be  integrated  with  the  computation  of  the  reaching  definitions  themselves. 
Thus,  the  block  b\  suggested  in  Fig.  12.13  is  typical.  Notice  t h at  we  identify 
points  within  the  block  numbered  0 , 1 , . ..  , n,  if  n  is  the  number  of  statements 
in  the  block.  The  ith  definition  is  "at"  point  i,  and  there  is  no  definition  at 
point  0. 

A  point  in  the  program  must  be  represented  by  a  pair  (b,n),  where  6  is  a 
block  name  and  n  is  an  integer  between  0  and  the  number  of  statements  in 
block  b.  Our  formulation  requires  two  E DB  predicates: 

12.3. 

A  LOGICAL  REPRESENTATION  OF  DATA  FLOW 

925 

o 

x  =  y+z 
*p  =  u 
2  X  =  V 
3 

Figure  12.13:  A  basic  block  with  points  between  statements 

1.  def(B,  N,  X)  is  t r ue  if  and  only  if t he  iVth  statement  in  block  B  may  define 
variable  X.  For  instance,  in  Fig.  12.13  def(bi,l,x)  is  true,  def(bi,S,x)  is 
true,  and  def(bi,2,Y) 
is  true  for  every  possible  variable  Y  t h at  p  may 
point  to  at  t h at  point.  For  the  moment,  we  shall  assume  t h at  Y  can  be 
any  variable  of  the  type  t h at  p  points  to. 

2.  succ(B,  N,  C)  is  true  if  and  only  if  block  C  is  a  successor  of  block  B  in 
the  flow  graph,  and  B  has  N  statements.  T h at  is,  control  can  flow  from 
the  point  N  of  B  to  the  point  0  of  C.  For  instance,  suppose  t h at  b2  is 
a  predecessor  of  block  b\  in  Fig.  12.13,  and  b2  has  5  statements.  Then 
succ(b2,5,  &i) 

is  true. 

There  is  one  IDB  predicate,  rd(B,  N,  C,  M,  X).  It  is  intended  to  be  true  if 
and  only  if the  definition  of variable  X  at  the  M th  statement  of block  C  reaches 
the  point  N  in  block  B.  The  rules  defining  predicate  rd  are  in  Fig.  12.14. 

1) 

rd(B,N,B,N,X) 

2) 

rd(B,N,C,M,X) 

:- 

:- 

def(B,N,X) 

rd{B,N 

-  1,C,M,X) 

k 

def(B,  A",  Y)  k 
X  j+  Y 

3) 

rd(B,  0,  C,  M,X) 

:  - 

rd(D,  N,  C,  M,  X)  k 
succ(D,N,B) 

Figure  12.14:  Rules  for  predicate  rd 

Rule  (1)  says  t h at  if  the  Nth  statement  of  block  B  defines  X,  then  t h at 
definition  of  X  reaches  t he  Nth  point  of  B  (i.e.,  the  point  immediately  after 
the  statement).  This  rule  corresponds  to  the  concept  of  "gen"  in  our  earlier, 
set-theoretic  formulation  of  reaching  definitions. 

Rule  (2)  represents  the  idea  t h at  a  definition  passes  through  a  statement 
unless  it  is  "killed,"  and  the  only  way  to  kill  a  definition  is  to  redefine  its 
variable  with  100%  certainty. 
In  detail,  rule  (2)  says  t h at  the  definition  of 
variable  X  from  t he  M th  statement  of  block  C  reaches  t he  point  N  of  block  B 
if 

a) 

it  reaches  the  previous  point  N  —  lot  B,  and 

926 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

b) 

there  is  at  least  one  variable  Y,  other  t h an  X,  t h at  may  be  defined  at  the 
TVth  statement  of  B. 

Finally,  rule  (3)  expresses  the  flow  of  control  in  the  graph.  It  says  t h at  the 
definition  of  X  at  the  M th  statement  of  block  C  reaches  the  point  0  of  B  if 
there  is  some  block  D  with  TV  statements,  such  t h at  the  definition  of X  reaches 
the  end  of  D,  and  B  is  a  successor  of  D. 

• 

The  E DB  predicate  succ  from  Example  12.13  clearly  can  be  read  off the  flow 
graph.  We  can  obtain  deffrom  the  flow  graph  as  well,  if we  are  conservative  and 
assume  a  pointer  can  point  anywhere.  If we  want  to  limit  the  range  of a  pointer 
to  variables  of  the  appropriate  type,  then  we  can  obtain  type  information  from 
the  symbol  table,  and  use  a  smaller  relation  def.  An  option  is  to  make  def 
an  IDB  predicate  and  define  it  by  rules.  These  rules  will  use  more  primitive 
E DB  predicates,  which  can  themselves  be  determined  from  the  flow  graph  and 
symbol  table. 

E x a m p le  1 2 . 1 4:  Suppose  we  introduce  two  new  E DB  predicates: 

1.  assign(B,N,X) 

is  true  whenever  t he 

iVth  statement  of  block  B  has  X 
on  the  left.  Note  t h at  X  can  be  a  variable  or  a  simple  expression  with  an 
1-value,  like  *p. 

2.  type(X,T)  is  true  if  the  type  of  X  is  T.  Again,  X  can  be  any  expression 

with  an  1-value,  and  T  can  be  any  expression  for  a  legal  type. 

Then,  we  can  write  rules  for  def,  making  it  an  IDB  predicate.  Figure  12.15 
is  an  expansion  of  Fig.  12.14,  with  two  of  the  possible  rules  for  def.  Rule  (4) 
says  t h at  the  TVth  statement  of  block  B  defines  X,  if  X  is  assigned  by  the  TVth 
statement.  Rule  (5)  says  t h at  X  can  also  be  defined  by  t he  iVth  statement  of 
block  B  if  t h at  statement  assigns  to  * P,  and  X  is  any  of  the  variables  of  t he 
type  t h at  P  points  to.  Other  kinds  of  assignments  would  need  other  rules  for 
def. 

As  an  example  of how  we  would  make  inferences  using  the  rules  of Fig.  12.15, 
let  us  re-examine  the  block  bi  of  Fig.  12.13.  The  first  statement  assigns  a 
value  to  variable  x,  so  the  fact  assign(bi,  1,x)  would  be  in  the  E D B.  T he  third 
statement  also  assigns  to  x,  so  assign(bi,3,  x)  is  another  E DB  fact.  T he  second 
statement  assigns  indirectly  through  p,  so  a  third  E DB  fact  is  assign(b1:  2,  *p). 
Rule  (4) 

then  allows  us  to  infer  def(bi,l,x)  and  def(bi,3,x). 

Suppose  t h at  p  is  of type  pointer-to-integer  (*int),  and  x  and  y  are  integers. 
Then  we  may  use  rule  (5),  with  B  =  h,  N  =  2,  P  =  p,  T  -  int,  and  X  equal  to 
either  x  or  y,  to  infer  def(b1:2,x)  and  def(h,2,y).  Similarly,  we  can  infer  the 
same  about  any  other  variable  whose  type  is  integer  or  coerceable  to  an  integer. 
• 

12.3. 

A  LOGICAL  REPRESENTATION  OF  DATA  FLOW 

927 

1) 

rd{B,N,B,N,X) 

:- 

def{B,N,X) 

2) 

rd(B,N,C,M,X) 

:- 

rd{B,  N  -  1,  C,  M,  X)  & 

def(B,N,Y)k 

3) 

r d ( £, 0, C, M, X) 

: - 

r d ( D, iV, C, M, X)  & 

succ(D,N,B) 

4) 

5) 

def(B,N,X) 

:- 

assign(B,N,X) 

def{B,N,X) 

:- 

assign{B,  N,  *P)  & 
* y p e ( X , T )& 
type(P,*T) 

Figure  12.15:  Rules  for  predicates 

and  de/ 

12.3.4  Execution  of  Datalog  Programs 

Every  set  of Datalog  rules  defines  relations  for  its  IDB  predicates,  as  a  function 
of the  relations  t h at  are  given  for  its  E DB  predicates.  Start  with  the  assumption 
t h at  th^  IDB  relations  are  empty  (i.e.,  t he  IDB  predicates  are  false  for  all 
possible  arguments).  Then,  repeatedly  apply  the  rules,  inferring  new  facts 
whenever  the  rules  require  us  to  do  so.  When  the  process  converges,  we  are 
done,  aijid  the  resulting  IDB  relations  form  the  output  of  the  program.  This 
process  is  formalized  in  the  next  algorithm,  which  is  similar  to  the  iterative 
algorithms  discussed  in  Chapter  9. 

A l g o r i t hm  1 2 . 1 5:  Simple  evaluation  of  Datalog  programs. 

I N P U T:  A  Datalog  program  and  sets  of  facts  for  each  E DB  predicate. 

O U T P U T:  Sets  of facts  for  each  IDB  predicate. 

M E T H O D:  For  each  predicate  p  in  the  program,  let  Rp  be  the  relation  of facts 
t h at  are  true  for  t h at  predicate.  If p  is  an  E DB  predicate,  then  Rp  is  the  set  of 
facts  given  for  t h at  predicate.  If  p  is  an  IDB  predicate,  we  shall  compute  Rp. 
• 
Execute  the  algorithm  in  Fig.  12.16. 

E x a m p le  1 2 . 1 6:  The  program  in  Example  12.12  computes  paths  in  a  graph. 
To  apply  Algorithm  12.15,  we  start  with  E DB  predicate  edge  holding  all  the 
edges  of  the  graph  and  with  the  relation  for  path  empty.  On  t he  first  round, 
rule  (2)  Vields  nothing,  since  there  are  no  path  facts.  But  rule  (1)  causes  all  t he 
edge  f a cp  to  become  path  facts  as  well.  T h at  is,  after  the  first  round,  we  know 
path(a,  6)  if  and  only  if  there  is  an  edge  from  a  to  6. 

928 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

for  (each  IDB  predicate  p) 

RP  =  $; 

w h i le  (changes  to  any  Rp  occur)  { 

consider  all  possible  substitutions  of  constants  for 

variables  in  all  t he  rules; 

determine,  for  each  substitution,  whether  all  the 

subgoals  of  the  body  are  true,  using  the  current 
Rp's  to  determine  t r u th  of  E DB  and  IDB  predicates; 

if  (a  substitution  makes  the  body  of  a  rule  true) 

add  the  head  to  Rq  if  q  is  the  head  predicate; 

} 

Figure  12.16:  Evaluation  of  Datalog  programs 

On  the  second  round,  rule  (1)  yields  no  new  paths  facts,  because  t he  E DB 
relation  edge  never  changes.  However,  now  rule  (2)  lets  us  p ut  together  two 
paths  of  length  1  to  make  paths  of  length  2.  T h at  is,  after  the  second  round, 
path(a, b)  is  true  if  and  only  if  there  is  a  p a th  of  length  1  or  2  from  a  to  b. 
Similarly,  on  the  third  round,  we  can  combine  paths  of  length  2  or  less  to 
discover  all  paths  of length  4  or  less.  On  t he  fourth  round,  we  discover  paths  of 
length  up  to  to  8,  and  in  general,  after  the  i th  round,  path(a,  b)  is  true  if  and 
only  if  there  is  a  p a th  from  a  to  6  of  length  2l~1  or  less. 

• 

12.3.5 

Incremental  Evaluation  of  Datalog  Programs 

There  is  an  efficiency  enhancement  of Algorithm  12.15  possible.  Observe  t h at  a 
new  IDB  fact  can  only  be  discovered  on  round  i  if it  is  the  result  of  substituting 
constants  in  a  rule,  such  t h at  at  least  one  of  the  subgoals  becomes  a  fact  t h at 
was just  discovered  on  round  i — 
The  proof of t h at  claim  is  t h at  if all  the  facts 
among  the  subgoals  were  known  at  round  i — 2,  then  the  "new"  fact  would  have 
been  discovered  when  we  made  the  same  substitution  of  constants  on  round 

To  take  advantage  of  this  observation,  introduce  for  each  IDB  predicate  p 
a  predicate  newP  t h at  will  hold  only  t he  newly  discovered  p-facts  from  the 
previous  round.  Each  rule  t h at  has  One  or  more  IDB  predicates  among  its 
subgoals  is  replaced  by  a  collection  of  rules.  Each  rule  in  t he  collection  is 
formed  by  replacing  exactly  one  occurrence  of  some  IDB  predicate  q  in  the 
body  by  newQ.  Finally,  for  all  rules,  we  replace  the  head  predicate  h  by  newH. 
T he  resulting  rules  are  said  to  be  in  incremental  form. 

T he  relations  for  each  IDB  predicate  p  accumulates  all  the  p-facts,  as  in 

Algorithm  12.15.  In  one  round,  we 

1.  Apply  the  rules  to  evaluate  the  newP  predicates. 

12.3. 

A  LOGICAL  REPRESENTATION  OF  DATA  FLOW 

929 

Incremental  Evaluation  of  Sets 

It  is  also  possible  to  solve  set-theoretic  data-flow  problems  incrementally. 
For  example,  in  reaching  definitions,  a  definition  can  only  be  newly  dis 
covered  to  be  in  m[B]  on  t he  2th  round  if  it  was  just  discovered  to  be 
in  O U T[ P]  for  some  predecessor  P  of  B.  The  reason  we  do  not  generally 
try  to  solve  such  data-flow  problems  incrementally  is  t h at  the  bit-vector 
implementation  of  sets  is  so  efficient.  It  is  generally  easier  to  fly  through 
t he  complete  vectors  t h an  to  decide  whether  a  fact  is  new  or  not. 

2.  Then,  subtract  p  from  newP,  to  make  sure  the  facts  in  newP  are  truly 

new. 

3.  Add  the  facts  in  newP  to  p. 

4.  Set  all  the  newX  relations  to  0  for  the  next  round. 

These  ideas  will  be  formalized  in  Algorithm  12.18.  However,  first,  we  shall  give 
an  example. 

E x a m p le  1 2 . 1 7:  Consider  the  Datalog  program  in  Example  12.12  again.  The 
incremental  form  of  the  rules  is  given  in  Fig.  12.17.  Rule  (1)  does  not  change, 
except  in  the  head  because  it  has  no  IDB  subgoals  in  the  body.  However, 
rule  (2),  with  two  IDB  subgoals,  becomes  two  different  rules.  In  each  rule,  one 
of  t he  occurrences  oipath  in  t he  body  is  replaced  by  newPath.  Together,  these 
rules  enforce  the  idea  t h at  at  least  one  of  the  two  paths  concatenated  by  t he 
rule  must  have  been  discovered  on  the  previous  round. 

• 

1) 

newPath(X,Y) 

:- 

edge(X,Y) 

2a) 

newPath(X,  Y) 

:  - 

path{X,  Z)  & 
newPath(Z, 

Y) 

2b) 

newPath{X,  Y) 

:  - 

newPath(X,  Z)  k 

path{Z,  Y) 

Figure  12.17:  Incremental  rules  for  the  p a th  Datalog  program 

A l g o r i t hm  1 2 . 1 8:  Incremental  evaluation  of  Datalog  programs. 

I N P U T:  A  Datalog  program  and  sets  of facts  for  each  E DB  predicate. 

O U T P U T:  Sets  of facts  for  each  IDB  predicate. 

930 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

M E T H O D:  For  each  predicate  p  in  the  program,  let  Rp  be  the  relation  of facts 
t h at  are  true  for  t h at  predicate.  If p  is  an  E DB  predicate,  then  Rp  is  t he  set  of 
facts  given  for  t h at  predicate.  If  p  is  an  IDB  predicate,  we  shall  compute  Rp. 
In  addition,  for  each  IDB  predicate  p,  let  Rnewp  be  a  relation  of  "new"  facts 
for  predicate  p. 

1.  Modify  the  rules  into  t he  incremental  form  described  above. 

2.  Execute  the  algorithm  in  Fig.  12.18. 

• 

for  (each  IDB  predicate  p)  { 

RP  =  $; 
RnewP  —  0; 

} 
r e p e at  { 

consider  all  possible  substitutions  of  constants  for 

variables  in  all  t he  rules; 

determine,  for  each  substitution,  whether  all  t he 

subgoals  of  the  body  are  true,  using  the  current 
Rps  and  RnewP^ 
and  IDB  predicates; 

to  determine  t r u th  of  E DB 

if  (a  substitution  makes  t he  body  of  a  rule  true) 

add  t he  head  to  RnewH,  where  h  is  the  head 

predicate; 

for  (each  predicate  p)  { 
RnewP  —  RnewP 
Rp 

=  Rp  U  RnewP) 

Rp'i 

} 

}  u n t il  (all  Rnewp's  are  empty); 

Figure  12.18:  Evaluation  of  Datalog  programs 

12.3.6  Problematic  Datalog  Rules 

There  are  certain  Datalog  rules  or  programs  t h at  technically  have  no  meaning 
and  should  not  be  used.  The  two  most  important  risks  are 

1.  Unsafe  rules:  those  t h at  have  a  variable  in  the  head  t h at  does  not  appear 
in  the  body  in  a  way  t h at  constrains  t h at  variable  to  take  on  only  values 
t h at  appear  in  the  E D B. 

2.  Unstratified  programs:  sets  of  rules  t h at  have  a  recursion  involving  a  nega 

tion. 

We  shall  elaborate  on  each  of  these  risks. 

12.3. 

A  LOGICAL  REPRESENTATION  OF  DATA  FLOW 

931 

R u le  S a f e ty 

Any  variable  t h at  appears  in  the  head  of  a  rule  must  also  appear  in  the  body. 
Moreover,  t h at  appearance  must  be  in  a  subgoal  t h at  is  an  ordinary  IDB  or 
E DB  atom.  It  is  not  acceptable  if  the  variable  appears  only  in  a  negated  atom, 
or  only  in  a  comparison  operator.  T he  reason  for  this  policy  is  to  avoid  rules 
t h at  let  us  infer  an  infinite  number  of  facts. 

E x a m p le  1 2 . 1 9:  T he  rule 

p(X,Y) 

:-  q(Z)  &  NOT  r(X) 

kX^Y 

is  unsafe  for  two  reasons.  Variable  X  appears  only  in  the  negated  subgoal 
r(X)  and  t he  comparison  X 
/  Y.  Y  appears  only  in  the  comparison.  T he 
consequence  is  t h at  p  is  true  for  an  infinite  number  of  pairs  (X,  Y),  as  long  as 
r ( X)  is  false  and  Y  is  anything  other  t h an  X. 

• 

S t r a t i f i ed  D a t a l og 

In  order  for  a  program  to  make  sense,  recursion  and  negation  must  be  separated. 
T he  formal  requirement  is  as  follows.  We  must  be  able  to  divide  the  IDB 
predicates  into  strata,  so  t h at  if  there  is  a  rule  with  head  predicate  p  and  a 
subgoal  of  the  form NOT  # ( • • • ),  then  q  is  either  E DB  or  an  IDB  predicate  in 
a  lower  s t r a t um  t h an  p.  As  long  as  this  rule  is  satisfied,  we  can  evaluate  the 
strata,  lowest  first,  by  Algorithm 12.15  or 12.18,  and  then  treat  the  relations 
for  the  IDB  predicates  of  t h at  s t r a ta  as  if  they  were  E DB  for  the  computation 
of  higher  strata.  However,  if  we  violate  this  rule,  then  the  iterative  algorithm 
may  fail  to  converge,  as  the  next  example  shows. 

E x a m p le  1 2 . 20  :  Consider  the  Datalog  program  consisting  of  the  one  rule: 

p ( X) 

:-  e ( X)  &  N O T p( X) 

Suppose  e  is  an  E DB  predicate,  and  only  e ( l)  is  true.  Is  p(l)  true? 

This  program  is  not  stratified.  Whatever  s t r a t um  we  put  p  in,  its  rule  has 
a  subgoal  t h at  is  negated  and  has  an  IDB  predicate  (namely  p  itself)  t h at  is 
surely  not  in  a  lower  s t r a t um  t h an  p. 

If  we  apply  the  iterative  algorithm,  we  start  with  Rp  =  0,  so  initially,  the 
answer  is  "no;  p ( l)  is  not  true."  However,  the  first  iteration  lets  us  infer  p ( l ), 
since  both  e ( l)  and NOT  p ( l)  are  true.  But  then  the  second  iteration  tells  us 
p ( l)  is  false.  T h at  is,  substituting 1  for  X  in  the  rule  does  not  allow  us  to  infer 
p ( l ),  since  subgoal NOT  p ( l)  is  false.  Similarly,  t he  third  iteration  says  p ( l)  is 
true,  the  fourth  says  it  is  false,  and  so  on.  We  conclude  t h at  this  unstratified 
program  is  meaningless,  and  do  not  consider  it  a  valid  program. 

• 

932 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

12.3.7  Exercises  for  Section  12.3 

!  E x e r c i se  1 2 . 3 . 1: 

In  this  problem,  we  shall  consider  a  reaching-definitions 
data-flow  analysis  t h at  is  simpler t h an  t h at  in  Example  12.13.  Assume  t h at  each 
statement  by  itself  is  a  block,  and  initially  assume  t h at  each  statement  defines 
exactly  one  variable.  The  E DB  predicate  pred(I,  J)  means  t h at  statement  I  is 
a  predecessor  of  statement  J.  The  E DB  predicate  defines (I,  X)  means  t h at  the 
variable  defined  by  statement  /  is  X.  We  shall  use  IDB  predicates  in(I,  D)  and 
out(I,  D)  to  mean  t h at  definition  D  reaches  the  beginning  or  end  of  statement 
/,  respectively.  Note  t h at  a  definition  is  really  a  statement  number.  Fig.  12.19 
is  a  datalog  program  t h at  expresses  the  usual  algorithm  for  computing  reaching 
definitions. 

1) 

kill(I,D) 

:- 

defines{I,X)  k  defines(D,X) 

2) 
out{I,I) 
3)  out(I,D) 

:- 
:- 

defines (I,  X) 
in(I,D)  k  NOT  kill(I,D) 

4) 

in(I,  D) 

:  - 

out(J,  D)  k  pred(J,  I) 

Figure  12.19:  Datalog  program  for  a  simple  reaching-definitions  analysis 

Notice  t h at  rule  (1)  says  t h at  a  statement  kills  itself,  but  rule  (2)  assures 
t h at  a  statement  is  in  its  own  "out  set"  anyway.  Rule  (3)  is  the  normal  transfer 
function,  and  rule  (4)  allows  confluence,  since  I  can  have  several  predecessors. 
Your  problem  is  to  modify  the  rules  to  handle  the  common  case  where  a 
definition  is  ambiguous,  e.g.,  an  assignment  through  a  pointer.  In  this  situation, 
defines(I,X)  may  be  true  for  several  different  X 's  and  one  I.  A  definition  is 
best  represented  by  a  pair  (D,X),  where  D  is  a  statement,  and  X  is  one  of 
the  variables  t h at  may  be  defined  at  D.  As  a  result,  in  and  out  become  three-
argument  predicates;  e.g.,  in(I,  D,X)  means  t h at  t he  (possible)  definition  of  X 
at  statement  D  reaches  the  beginning  of  statement  I. 

E x e r c i se  1 2 . 3 . 2:  Write  a  Datalog  program  analogous  to  Fig.  12.19  to  com 
pute  available  expressions. 
In  addition  to  predicate  defines,  use  a  predicate 
eval (I,  X,  O,  Y)  t h at  says  statement  I  causes  expression  XOY  to  be  evaluated. 
Here,  O  is  t he  operator  in  t he  expression,  e.g.,  +. 

E x e r c i se  1 2 . 3 . 3:  Write  a Datalog program  analogous to  Fig.  12.19  to  compute 
live  variables. 
In  addition  to  predicate  defines,  assume  a  predicate  use(I,  X) 
t h at  says  statement  I  uses  variable  X. 

E x e r c i se  1 2 . 3 . 4:  In  Section  9.5,  we  defined  a  data-flow  calculation  t h at  in 
volved  six  concepts:  anticipated,  available,  earliest,  postponable,  latest,  and 
used.  Suppose  we  had  written  a  Datalog  program  to  define  each  of  these  in 

12.4. 

A 

SIMPLE  POINTER-ANALYSIS  ALGORITHM 

933 

terms  of  E DB  concepts  derivable  from  the  program  (e.g.,  gen  and  kill  infor 
mation)  and  others  of  these  six  concepts.  Which  of  the  six  depend  on  which 
others?  Which  of these  dependences  are  negated?  Would  t he  resulting  Datalog 
program  be  stratified? 

E x e r c i se  1 2 . 3 .5  :  Suppose  t h at  the  E DB  predicate  edge(X,Y)  consists  of  the 
following  facts: 

edge{l,2) 
edge(4,l) 

edge{2,3) 
edge(4,5) 

edge{2>,4) 
edge(5,6) 

a)  Simulate  the  Datalog  program  of  Example  12.12  on  this  data,  using  the 
simple  evaluation  strategy  of  Algorithm  12.15.  Show  the  path  facts  dis 
covered  at  each  round. 

b)  Simulate  the  Datalog  program  of  Fig.  12.17  on  this  data,  as  part  of  the 

incremental  evaluation  strategy  of  Algorithm  12.18.  Show  the  path  facts 
discovered  at  each  round. 

E x e r c i se  1 2 . 3 .6  :  The  following  rule 

p(X,  Y)  : -  q(X,  Z)  k  r(Z,  W)  k  NOT  p(W,  Y) 

is  part  of  a  larger  Datalog  program  P. 

a)  Identify  t he  head,  body,  and  subgoals  of  this  rule. 

b)  Which  predicates  are  certainly  IDB  predicates  of  program  PI 

!  c)  Which  predicates  are  certainly  E DB  predicates  of  P? 

d)  Is  the  rule  safe? 

e)  Is  P  stratified? 

E x e r c i se  1 2 . 3 . 7:  Convert  the  rules  of  Fig.  12.14  to  incremental  form. 

12.4  A  Simple  Pointer-Analysis  Algorithm 

In  this  section,  we  begin  the  discussion  of  a  very  simple  flow-insensitive  pointer-
alias  analysis  assuming  t h at  there  are  no  procedure  calls.  We  shall  show  in 
subsequent  sections  how  to  handle  procedures  first  context  insensitively,  then 
context  sensitively.  Flow  sensitivity  adds  a  lot  of  complexity,  and  is  less  im 
p o r t a nt  to  context  sensitivity  for  languages  like  Java  where  methods  tend  to  be 
small. 

T he  fundamental  question  t h at  we  wish  to  ask  in  pointer-alias  analysis  is 
whether  a given  pair  of pointers  may  be  aliased.  One  way  to  answer  this  question 
is  to  compute  for  each  pointer  the  answer  to  the  question  "what  objects  can 
this  pointer  point  to?"  If  two  pointers  can  point  to  the  same  object,  then  the 
pointers  may  be  aliased. 

9 34 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

12A.I  Why  is  Pointer  Analysis  Difficult 

Pointer-alias  analysis  for  C  programs  is  particularly  difficult,  because  C  pro 
grams  can  perform  arbitrary  computations  on  pointers.  In  fact,  one  can  read  in 
an  integer  and  assign  it  to  a  pointer,  which  would  render  this  pointer  a  potential 
alias  of  all  other  pointer  variables  in  t he  program.  Pointers  in  Java,  known  as 
references,  are  much  simpler.  No  arithmetic  is  allowed,  and  pointers  can  only 
point  to  the  beginning  of  an  object. 

Pointer-alias  analysis  must  be  interprocedural.  Without  interprocedural 
analysis,  one  must  assume  t h at  any  method  called  can  change  the  contents  of 
all  accessible  pointer  variables,  thus  rendering  any  intraprocedural  pointer-alias 
analysis  ineffective. 

Languages  allowing  indirect  function  calls  present  an  additional  challenge 
for  pointer-alias  analysis.  In  C,  one  can  call  a  function  indirectly  by  calling  a 
dereferenced  function  pointer.  We  need  to  know  what  the  function  pointer  can 
point  to  before  we  can  analyze  the  function  called.  And  clearly,  after  analyzing 
the  function  called,  one  may  discover  more  functions  t h at  t he  function  pointer 
can  point  to,  and  therefore  the  process  needs  to  be  iterated. 

While  most  functions  are  called  directly  in  C,  virtual  methods  in  Java  cause 
many  invocations  to  be  indirect.  Given  an  invocation  x . m ()  in  a  Java  program, 
there  may  be  many  classes  to  which  object  x  might  belong  and  t h at  have  a 
method  named  m.  T he  more  precise  our  knowledge  of the  actual  type  of  x,  the 
more  precise  our  call  graph  is.  Ideally,  we  can  determine  at  compile  time  the 
exact  class  of  x  and  thus  know  exactly  which  method  m  refers  to. 

E x a m p le  1 2 . 2 1:  Consider  the  following  sequence  of  Java  statements: 

O b j e ct  o; 
o  =  new  S t r i n g ( ); 
n  =  o . l e n g t hO  ; 

Here  o  is  declared  to  be  an  O b j e c t.  Without  analyzing  what  o  refers  to,  all 
possible  methods  called  "length"  declared  for  all  classes  must  be  considered  as 
possible  targets.  Knowing  t h at  o  points  to  a  S t r i ng  will  narrow  interprocedural 
analysis  to  precisely  the  method  declared  for  S t r i n g. 

• 

It  is  possible  to  apply  approximations  to  reduce  the  number  of targets.  For 
example,  statically  we  can  determine  what  are  all  the  types  of  objects  created, 
and  we  can  limit  the  analysis  to  those.  But  we  can  be  more  accurate  if  we  can 
discover  the  call  graph  on  the  fly,  based  on  the  points-to  analysis  obtained  at 
the  same  time.  More  accurate  call  graphs  lead  not  only  to  more  precise  results 
but  also  can  reduce  greatly  the  analysis  time  otherwise  needed. 

Points-to  analysis  is  complicated. 

It  is  not  one  of  those  "easy"  d a ta  flow 
problems  where  we  only  need  to  simulate  the  effect  of  going  around  a  loop  of 
statements  once.  Rather,  as  we  discover new targets for  a pointer,  all  statements 
assigning  the  contents  of t h at  pointer  to  another  pointer  need  to  be  re-analyzed. 

12.4. 

A 

SIMPLE  POINTER-ANALYSIS  ALGORITHM 

935 

For  simplicity,  we  shall  focus  mainly  on  Java.  We  shall  start  with  flow-
insensitive  and  context-insensitive  analysis,  assuming  for  now  t h at  no  methods 
are  called  in  the  program.  Then,  we  describe  how  we  can  discover  the  call  graph 
on  t he  fly  as  the  points-to  results  are  computed.  Finally,  we  describe  one  way 
of  handling  context  sensitivity. 

12.4.2  A  Model  for  Pointers  and  References 

Let  us  suppose  t h at  our  language  has  t he  following  ways  to  represent  and  ma 
nipulate  references: 

1.  Certain  program  variables  are  of  type  "pointer  to  T"  or  "reference  to  T," 
where  T  is  a  type.  These  variables  are  either  static  or  live  on  the  run-time 
stack.  We  call  them  simply  variables. 

2.  There  is  a  heap  of  objects.  All  variables  point  to  heap  objects,  not  to 

other  variables.  These  objects  will  be  referred  to  as  heap  objects. 

3.  A  heap  object  can  have  fields,  and  the  value  of  a  field  can  be  a  reference 

to  a  heap  object  (but  not  to  a  variable). 

Java is  modeled  well by  this  structure,  and  we  shall  use  Java syntax  in  examples. 
Note  t h at  C  is  modeled  less  well,  since  pointer  variables  can  point  to  other 
pointer  variables  in  C,  and  in  principle,  any  C  value  can  be  coerced  into  a 
pointer. 

Since  we  are  performing  an  insensitive  analysis,  we  only  need  to  assert  t h at 
a  given  variable  v  can  point  to  a  given  heap  object  h;  we  do  not  have  to  address 
the  issue  of  where  in  the  program  v  can  point  to  h,  or  in  what  contexts  v  can 
point  to  h.  Note,  however,  t h at  variables  can  be  named  by  their  full  name.  In 
Java,  this  name  can  incorporate  the  module,  class,  method,  and  block  within 
a  method,  as  well  as  the  variable  name  itself.  Thus,  we  can  distinguish  many 
variables  t h at  have  t he  same  identifier. 

Heap  objects  do  not  have  names.  Approximation  often  is  used  to  name  the 
objects,  because  an  unbounded  number  of  objects  may  be  created  dynamically. 
One  convention  is  to  refer  to  objects  by  the  statement  at  which  they  are  created. 
As  a  statement  can  be  executed  many  times  and  create  a  new  object  each  time, 
an  assertion  like  "v  can  point  to  /i"  really  means  "v  can  point  to  One  or  more 
of  the  objects  created  at  the  statement  labeled  h." 

T he  goal  of  the  analysis  is  to  determine  what  each  variable  and  each  field 
of  each  heap  object  can  point  to.  We  refer  to  this  as  a  points-to  analysis; 
two  pointers  are  aliased  if  their  points-to  sets  intersect.  We  describe  here  an 
inclusion-based  analysis;  t h at  is,  a  statement  such  as  v  =  w  causes  variable  v  to 
point  to  all  the  objects  w  points  to,  but  not  vice  versa.  While  this  approach  may 
seem  obvious,  there  are  other  alternatives  to  how  we  define  points-to  analysis. 
For  example,  we  can  define  an  equivalence-based  analysis  such  t h at  a  statement 
like  v  = w  would  t u rn  variables  v  and  w  into  one  equivalence  class,  pointing 

936 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

to  all  the  variables  t h at  each  can  point  to.  While  this  formulation  does  not 
approximate  aliases  well,  it  provides  a  quick,  and  often  good,  answer  to  the 
question  of  which  variables  point  to  the  same  kind  of  objects. 

12.4.3  Flow  Insensitivity 

We  start  by  showing  a  very  simple  example  to  illustrate  the  effect  of  ignoring 
control  flow  in  points-to  analysis. 

E x a m p le  1 2 . 2 2: 
assigned  to  variables  a,  b,  and  c,  respectively.  Thus,  surely  a  points  to  h,  b 
points  to  i,  and  c  points  to  j  by  the  end  of  line  (3). 

In  Fig.  12.20,  three  objects,  h,  i,  and  j,  are  created  and 

h: 
i: 

j  : 

1) 
2) 
3) 
4) 
5) 
6) 

a  =  new  O b j e c t ( ); 
b  =  new  O b j e c tO  ; 
c  =  new  O b j e c t ( ); 
a  =  b; 
b  =  c; 
c  =  a; 

Figure  12.20:  Java  code  for  Example  12.22 

If  you  follow  the  statements  (4)  through  (6),  you  discover  t h at  after  line  (4) 
a  points  only  to  i.  After  line  (5),  b  points  only  to  j,  and  after  line  (6),  c  points 
only  to  i. 

• 

The  above  analysis  is  flow  sensitive  because  we  follow  the  control  flow  and 
compute  what  each  variable  can  point  to  after  each  statement.  In  other  words, 
in  addition  to  considering  what  points-to  information  each  statement  "gener 
ates,"  we  also  account  for  what  points-to  information  each  statement  "kills." 
For  instance,  the  statement  b  =  c;  kills  the  previous  fact  "6  points  to  f  and 
generates  the  new  relationship  "6  points  to  what  c  points  to." 

A  flow-insensitive  analysis  ignores  the  control flow, which  essentially  assumes 

t h at  every  statement  in  the  program  can  be  executed  in  any  order.  It  computes 
only  one  global  points-to  m ap  indicating  what  each  variable  can  possibly  point 
to  at  any  point  of the  program  execution.  If a  variable  can  point  to  two  different 
objects  after two  different  statements  in  a program,  we  simply  record  t h at  it  can 
point  to  both  objects.  In  other  words,  in flow-insensitive analysis,  an  assignment 
does  not  "kill"  any  points-to  relations  but  can  only  "generate"  more  points-to 
relations.  To  compute  the flow-insensitive results,  we  repeatedly  add  t he  points-
to  effects  of each  statement  on  the  points-to  relationships  until  no  new  relations 
are  found.  Clearly,  lack  of  flow  sensitivity  weakens  the  analysis  results  greatly, 
but  it  tends  to  reduce  the  size  of the  representation  of the  results  and  make  the 
algorithm  converge  faster. 

12.4. 

A 

SIMPLE  POINTER-ANALYSIS  ALGORITHM 

937 

E x a m p le  1 2 . 2 3:  Returning  to  Example  12.22,  lines  (1)  through  (3)  again  tell 
us  a  can  point  to  h;  b  can  point  to  i,  and  c  can  point  to  j.  W i th  lines  (4) 
and  (5),  a  can  point  to  both  h  and  i,  and  b  can  point  to  b o th  i  and  j.  W i th 
line  (6),  c  can  point  to  h,i,  and  j.  This  information  affects  line  (5),  which  in 
t u rn  affects  line  (4),  In  the  end,  we  are  left  with  the  useless  conclusion  t h at 
anything  can  point  to  anything. 

• 

12.4.4  The  Formulation  in  Datalog 

Let  us  now  formalize  a  flow-insensitive  pointer-alias  analysis  based  on  the  dis 
cussion  above.  We  shall  ignore  procedure  calls  for  now  and  concentrate  on  the 
four  kinds  of  statements  t h at  can  affect  pointers: 

1.  Object  creation,  h: 

T  v  =  new  T ( );  This  statement  creates  a  new  heap 

object,  and  variable  v  can  point  to  it. 

2.  Copy  statement,  v  =  w;  Here,  v  and  w  are  variables.  The  statement 
makes  v  point  to  whatever  heap  object  w  currently  points  to;  i.e.,  w  is 
copied  into  v. 

3.  Field  store,  v .f  =  w;  T he  type  of  object  t h at  v  points  to  must  have  a 
field  /,  and  this  field  must  be  of  some  reference  type.  Let  v  point  to  heap 
object  h,  and  let  w  point  to  g.  This  statement  makes  t he  field  /,  in  h 
now  point  to  g.  Note  t h at  the  variable  v  is  unchanged. 

4.  Field  load,  v  =  w. f;  Here,  if  is  a  variable  pointing  to  some  heap  object 
t h at  has  a  field  /,  and  /  points  to  some  heap  object  h.  The  statement 
makes  variable  v  point  to  h. 

Note  t h at  compound  field  accesses  in  the  source  code  such  as  v  =  w. f. g 

will  be  broken  down  into  two  primitive  field-load  statements: 

vl  =  w. f; 
v  =  vl.g; 

Let  us  now  express  the  analysis  formally  in  Datalog  rules.  First,  there  are 

only  two  IDB  predicates  we  need  to  compute: 

1.  pts(V,H)  means  t h at  variable  V  can  point  to  heap  object  H. 

2.  hpts(H,  F,  G)  means  t h at  field  F  of  heap  object  H  can  point  to  heap 

object  G. 

The  E DB  relations  are  constructed  from  the  program  itself. 

Since  the 
location  of  statements  in  a  program  is  irrelevant  when  t he  analysis  is  flow-
insensitive,  we  only  have  to  assert  in  the  E DB  the  existence  of  statements  t h at 
have  certain  forms.  In  what  follows,  we  shall  make  a  convenient  simplification. 
Instead  of  defining  E DB  relations  to  hold  the  information  garnered  from  the 

938 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

program,  we  shall  use  a  quoted  statement  form  to  suggest  the  E DB  relation 
or  relations  t h at  represent  the  existence  of  such  a  statement.  For  example, 
"H  :  TV  =  new  T"  is  an  E DB  fact  asserting  t h at  at  statement  H  there  is 
an  assignment  t h at  makes  variable  V  point  to  a  new  object  of  type  T.  We  as 
sume  t h at  in  practice,  there  would  be  a  corresponding  E DB  relation  t h at  would 
be  populated  with  ground  atoms,  one  for  each  statement  of  this  form  in  t he 
program. 

W i th  this  convention,  all  we  need  to  write  the  Datalog  program  is  one  rule 
for  each  of  the  four  types  of  statements.  T he  program  is  shown  in  Fig,  12.21. 
Rule  (1)  says  t h at  variable  V  can  point  to  heap  object  H  if  statement  H  is  an 
assignment  of a  new  object  to  V.  Rule  (2)  says  t h at  if there  is  a  copy  statement 
V  =  W,  and  W  can  point  to  H,  then  V  can  point  to  H. 

1) 

2) 

pts{V,H) 

pts(V,H) 

:- 

:- 

3) 

hpts(H:F,G) 

:- 

4) 

pts(V,H) 

:- 

"H:  TV  =  new  T" 

«V  =  W"k 

pts(W,  H) 

"V.F  =  W"  & 
pts(W-,G)  & 
pts(V,H) 

"V  =  W.F"8c 
pts(W,G)  & 
hpts(G,F,H) 

Figure  12.21:  Datalog  program  for  flow-insensitive  pointer  analysis 

Rule  (3)  says  t h at  if  there  is  a  statement  of  the  form  V.F  =  W,W  can  point 
to  C7,  and  V  can  point  to  H,  then  the  F  field  of  H  can  point  to  G.  Finally, 
rule  (4)  says  t h at  if  there  is  a  statement  of the  form  V  =  W.F,  W  can  point  to 
G,  and  the  F  field  of  G  can  point  to  H,  then  V  can  point  to  H.  Notice  t h at  pts 
and  hpts  are  mutually  recursive,  but  this  Datalog  program  can  be  evaluated  by 
either  of  the  iterative  algorithms  discussed  in  Section  12.3.4. 

12.4.5  Using  Type  Information 

Because  Java  is  type  safe,  variables  can  only  point  to  types  t h at  are  compat 
ible  to  the  declared  types.  For  example,  assigning  an  object  belonging  to  a 
superclass  of  the  declared  type  of  a  variable  would  raise  a  run-time  exception. 
Consider  the  simple  example  in  Fig.  12.22,  where  5  is  a  subclass  of  T.  This 
program  will  generate  a  run-time  exception  if  p  is  true,  because  a  cannot  be 
assigned  an  object  of  class  T.  Thus,  statically  we  can  conclude  t h at  because  of 
the  type  restriction,  a  can  only  point  to  h  and  not  g. 

12.4.  A 

SIMPLE 

POINTER-ANALYSIS 

ALGORITHM 

939 

S  a; 
T  b; 
if 

(p)  { 
b  =  new  T ()  ; 

y  e l se 

b  =  new  S ( ); 

} 
a  =  b; 

g: 

h: 

Figure  12.22:  Java  program  with  a  type  error 

Thus,  we  introduce  to  our  analysis  three  E DB  predicates  t h at  reflect  impor 
t a nt  type  information  in  the  code  being  analyzed.  We  shall  use  the  following: 

1.  vType(V,T)  says  t h at  variable  V  is  declared  to  have  type  T. 

2.  hType(H,T)  says  t h at  heap  object  H  is  allocated  with  type  T.  T he  type 
of  a  created  object  may  not  be  known  precisely  if,  for  example,  t he  object 
is  returned  by  a  native  method.  Such  types  are  modeled  conservatively 
as  all  possible  types. 

3.  assignable(T,  S)  means  t h at  an  object  of  type  S  can  be  assigned  to  a 
variable  with  the  type  T.  This  information  is  generally  gathered  from  the 
declaration  of subtypes  in  the  program,  but  also  incorporates  information 
about  the  predefined  classes  of  the  language.  assignable(T:T)  is  always 
true. 

We  can  modify  the  rules  from  Fig.  12.21  to  allow  inferences  only  if  the 
variable  assigned  gets  a  heap  object  of  an  assignable  type.  The  rules  are  shown 
in  Fig.  12.23. 

T he  first  modification  is  to  rule  (2).  T he  last  three  subgoals  say  t h at  we  can 
only  conclude  t h at  V  can  point  to  H  if  there  are  types  T  and  S  t h at  variable  V 
and  heap  object  H  may  respectively  have,  such  t h at  objects  of  type  S  can  be 
assigned  to  variables  t h at  are  references  to  type  T.  A  similar  additional  restric 
tion  has  been  added  to  rule  (4).  Notice  t h at  there  is  no  additional  restriction 
in  rule  (3)  because  all  stores  must  go  through  variables.  Any  type  restriction 
would  only  catch  one  extra  case,  when  the  base  object  is  a  null  constant. 

12.4.6  Exercises  for  Section  12.4 

E x e r c i se  1 2. 4. 1:  In  Fig.  12.24,  h  and  g  are  labels  used  to  represent  newly 
created  objects,  and  are  not  part  of  the  code.  You  may  assume  t h at  objects  of 
type  T  have  a  field  /.  Use  the  Datalog  rules  of  this  section  to  infer  all  possible 
pts  and  hpts  facts. 

9 40 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

1) 

2) 

pts(V,H) 

pts(V,H) 

:- 

:- 

3) 

hpts(H,F,G) 

:- 

"H:  TV  = new  T 

"V  =  W"8c 
pts(W,H)  & 
vType(V,T)  & 
hType(H,  S)  & 
assignable(T, 

S) 

"V.F  =  PF"  & 
pis(VF,G)  & 
pts(V,H) 

4) 

pteCV,!*) 

:- 

= 

& 

pts(W,G)  & 
hpts(G,F,H) 
vType(V,  T)  & 
hType{H,  S)  & 
assignable(T, 

S) 

Figure  12.23:  Adding  type  restrictions  to  flow-insensitive  pointer  analysis 

h:  T  a  =  new  T O; 
T b  =  new  T O; 
T  c =  a; 
a. ,f = b; 
b. ,f =  c; 
T  d =  c.f; 

Figure  12.24:  Code  for  Exercise  12.4.1 

! Exercise  1 2 . 4 . 2:  Applying  t he  algorithm  of this  section  to  t he  code 

h:  T a = new T ( ); 
b  =  new  T O; 
g: 

T  c  =  a; 

would  infer  t h at  b o th  a  and  b  can  point  to  h  and  g.  Had  the  code  been  written 

h:  T a = new T ( ); 
b  =  new  T O; 
g: 

T  c  = b; 

we  would  infer  accurately  t h at  a  can  point  to  h,  and  b  and  c  can  point  to 
g.  Suggest  an  intraprocedural  data-flow  analysis  t h at  can  avoid  this  kind  of 
inaccuracy. 

12.5. 

CONTEXT-INSENSITIVE 

INTERPROCEDURAL 

ANALYSIS 

941 

t  p(t  x)  { 

h:  T  a =  new T; 
a.f  =  x; 
return  a; 

} 

void  main() 

g:  T b 
b 
b 

new  T; 

p(b); 
b.f; 

} 

Figure  12.25:  Example  code  for  pointer  analysis 

!  E x e r c i se  1 2 . 4 . 3:  We  can  extend  the  analysis  of  this  section  to  be  interproce 
dural  if we  simulate  call  and  return  as  if they  were  copy  operations,  as  in  rule  (2) 
of  Fig.  12.21.  T h at  is,  a  call  copies  the  actuals  to  their  corresponding  formals, 
and  t he  return  copies  the  variable  t h at  holds  the  return  value  to  t he  variable 
t h at  is  assigned  t he  result  of  the  call.  Consider  the  program  of  Fig.  12.25. 

a)  Perform  an  insensitive  analysis  on  this  code. 

b)  Some  of t he  inferences  made  in  (a)  are  actually  "bogus,"  in  the  sense  t h at 
they  do  not  represent  any  event  t h at  can  occur  at  run-time.  T he  problem 
can  be  traced  to  the  multiple  assignments  to  variable  b.  Rewrite  the  code 
of  Fig.  12.25  so  t h at  no  variable  is  assigned  more  t h an  once.  Rerun  the 
analysis  and  show  t h at  each  inferred  pts  and  hpts  fact  can  occur  at  run 
time. 

12.5  Context-Insensitive  Interprocedural 

Analysis 

We  now  consider  method  invocations.  We  first  explain  how  points-to  analysis 
can  be  used  to  compute  a  precise  call  graph,  which  is  useful  in  computing  precise 
points-to  results.  We  then  formalize  on-the-fly  call-graph  discovery  and  show 
how  Datalog  can  be  used  to  describe  the  analysis  succinctly. 

12.5.1  Effects  of  a  Method  Invocation 

T he  effects  of  a  method  call  such  as  x  =  y . n ( z)  in  Java  on  t he  points-to  rela 
tions  can  be  computed  as  follows: 

1.  Determine  t he  type  of t he  receiver  object,  which  is  the  object  t h at  y  points 
t o.  Suppose  its  type  is  t.  Let  m  be  t he  method  named  n  in  t he  narrowest 

942 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

superclass  of  t  t h at  has  a  method  named  n.  Note  t h a t,  in  general,  which 
method  is  invoked  can  only  be  determined  dynamically. 

2.  The  formal  parameters  of m  are  assigned  t he  objects  pointed  to  by  the  ac 
tual  parameters.  The  actual  parameters  include  not  just  t he  parameters 
passed  in  directly,  but  also  the  receiver  object  itself.  Every  method  invo 
cation  assigns  the  receiver  object  to  the  t h is  variable.3  We  refer  to  the 
t h is  variables  as  the  Oth  formal  parameters  of methods.  In  x  =  y . n ( z ), 
there  are  two  formal  parameters:  the  object  pointed  to  by  y  is  assigned 
to  variable  t h i s,  and  the  object  pointed  to  by  z  is  assigned  to  the  first 
declared  formal  parameter  of  m. 

3.  The  returned  object  of  m  is  assigned  to  the  left-hand-side  variable  of  the 

assignment  statement. 

In  context-insensitive  analysis,  parameters  and  returned  values  are  modeled 
by  copy  statements.  T he  interesting  question  t h at  remains  is  how  to  determine 
the  type  of  the  receiver  object.  We  can  conservatively  determine  the  type  ac 
cording  to  the  declaration  of  the  variable;  for  example,  if  the  declared  variable 
has  type 
then  only  methods  named  n  in  subtypes  of  t  can  be  invoked.  Unfor 
tunately,  if t he  declared  variable  has  type  O b j e c t,  then  all  methods  with  name 
n  are  all  potential  targets.  In  real-life  programs  t h at  use  object  hierarchies  ex 
tensively  and  include  many  large  libraries,  such  an  approach  can  result  in  many 
spurious  call  targets,  making  the  analysis  both  slow  and  imprecise. 

We  need  to  know  what  the  variables  can  point  to  in  order  to  compute  the 
call  targets;  but  unless  we  know  the  call  targets,  we  cannot  find  out  what  all  t he 
variables  can  point  to.  This  recursive  relationship  requires  t h at  we  discover  the 
call  targets  on  the  fly  as  we  compute  t he  points-to  set.  T he  analysis  continues 
until  no  new  call  targets  and  no  new  points-to  relations  are  found. 

E x a m p le  1 2 . 2 4:  In  the  code  in  Fig.  12.26,  r  is  a  subtype  of s,  which  itself is  a 
subtype  of  t.  Using  only  the  declared  type  information,  a . n ()  may  invoke  any 
of  the  three  declared  methods  with  name  n  since  s  and  r  are  b o th  subtypes  of 
a's  declared  type,  t.  Furthermore,  it  appears  t h at  a  may  point  to  objects  g,  h, 
and  i  after  line  (5). 

By  analyzing  the  points-to  relationships,  we  first  determine  t h at  a  can  point 
to  j,  an  object  of type  t.  Thus,  the  method  declared  in  line  (1)  is  a  call  target. 
Analyzing  line  (1),  we  determine  t h at  a  also  can  point  to  g,  an  object  of  type 
r.  Thus,  the  method  declared  in  line  (3)  may  also  be  a  call  target,  and  a  can 
now  also  point  to  i,  another  object  of  type  r.  Since  there  are  no  more  new 
call  targets,  the  analysis  terminates  without  analyzing  t he  method  declared  in 
line  (2)  and  without  concluding  t h at  a  can  point  to  h. 

• 

3 Remember  that  variables  are  distinguished  by  the  method  to  which  they  belong,  so  there 
is  not  just  one  variable  named  t h i s,  but  rather  one  such  variable  for  each  method  in  the 
program. 

CONTEXT-INSENSITIVE  INTERPROCEDURAL  ANALYSIS 

943 

c l a ss 

t  { 

1)  g: 

t  n ()  {  r e t u rn  new  r ( );  } 

} 
c l a ss  s  e x t e n ds  t  { 

2)  h: 

t  n ()  {  r e t u rn  new  s ( );  } 

} 
c l a ss  r  e x t e n ds  s  { 

3) 

i: 

t  n ()  {  r e t u rn  new  r ( );  } 

} 

main  ()  { 

j: 

4) 
5) 

t  a  =  new  t ( ); 
a  =  a . n ( ); 

} 

Figure  12.26:  A  virtual  method  invocation 

12.5.2  Call  Graph  Discovery  in  Datalog 

To  formulate  t he  Datalog  rules  for  context-insensitive  interprocedural  analysis, 
we  introduce  three  E DB  predicates,  each  of  which  is  obtainable  easily  from  the 
source  code: 

1.  actual(S,I,V)  says  V  is  the  J th  actual  parameter  used  in  call  site  S. 

2.  formal(M:  I,  V)  says  t h at  V  is  I th  formal  parameter  declared  in  method 

M. 

3.  cha(T,  N,  M)  says  t h at  M  is  the  method  called  when  N  is  invoked  on  a 

receiver  object  of  type  T.  (cha  stands  for  class  hierarchy  analysis). 

Each  edge  of  t he  call  graph  is  represented  by  an  IDB  predicate  invokes. 
As  we  discover  more  call-graph  edges,  more  points-to  relations  are  created  as 
t he  parameters  are  passed  in  and  returned  values  are  passed  out.  This  effect  is 
summarized  by  the  rules  shown  in  Figure  12.27. 

The  first  rule  computes  the  call  target  of the  call  site.  T h at  is,  "5  :  V.N (...)" 
says  t h at  there  is  a  call  site  labeled  S  t h at  invokes  method  named  N  on  the 
receiver  object  pointed  to  by  V.  The  subgoals  say  t h at  if  V  can  point  to  heap 
object  H,  which  is  allocated  as  type  T,  and  M  is  the  method  used  when  N  is 
invoked  on  objects  of  type  T,  then  call  site  S  may  invoke  method  M. 

The  second  rule  says  t h at  if  site  S  can  call  method  M,  then  each  formal 
parameter  of  M  can  point  to  whatever  the  corresponding  actual  parameter  of 
the  call  can  point  to.  The  rule  for  handling  returned  values  is  left  as  an  exercise. 
Combining  these  two  rules  with  those  explained  in  Section  12.4  create  a 
context-insensitive  points-to  analysis  t h at  uses  a  call  graph  t h at  is  computed 
on  t he  fly.  This  analysis  has  the  side  effect  of  creating  a  call  graph  using  a 

9 44 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

1) 

invokes(S,M) 

"S  :  V.N(...)"  & 
pts(V,  H)  & 
hType(H,  T)  & 
cha(T,  N,  M) 

pts(V,H) 

invokes(S,  M)  & 
formal(M,I,V) 
actual(S,I,W) 
pts(W,H) 

& 

& 

Figure  12.27:  Datalog  program  for  call-graph  discovery 

context-insensitive  and  flow-insensitive  points-to  analysis.  This  call  graph  is 
significantly  more  accurate  t h an  one  computed  based  only  on  type  declarations 
and  syntactic  analysis. 

12.5.3  Dynamic  Loading  and  Reflect  ion 

Languages  like  Java  allow  dynamic  loading  of  classes.  It  is  impossible  to  an 
alyze  all  t he  possible  code  executed  by  a  program,  and  hence  impossible  to 
provide  any  conservative  approximation  of  call  graphs  or  pointer  aliases  stat 
ically.  Static  analysis  can  only  provide  an  approximation  based  on  t he  code 
analyzed.  Remember  t h at  all  the  analyses  described  here  can  be  applied  at  t he 
Java  bytecode  level,  and  thus  it  is  not  necessary  to  examine  the  source  code. 
This  option  is  especially  significant  because  Java  programs  tend  to  use  many 
libraries. 

Even  if  we  assume  t h at  all  the  code  to  be  executed  is  analyzed,  there  is 
one  more  complication  t h at  makes  conservative  analysis  impossible:  reflection. 
Reflection  allows  a  program  to  determine  dynamically  t he  types  of  objects  to 
be  created,  the  names  of  methods  invoked,  as  well  as  the  names  of  t he  fields 
accessed.  T he  type,  method,  and  field  names  can  be  computed  or  derived 
from  user  input,  so  in  general  the  only  possible  approximation  is  to  assume  t he 
universe. 

E x a m p le  1 2 . 25  :  T he  code  below  shows  a  common  use  of  reflection: 

1) 
2) 
3) 
4) 

String  className  =  ...; 
Class  c = Class.forName(className); 
Object  o  =  c.newInstanceO ; 

T t  =  (T)  o; 

T he f orName method in t he Class library takes a string containing the class 
name  and  returns  the  class.  T he  method newlnstance  returns  an  instance  of 
t h at  class.  Instead  of leaving  the  object  o  with  type Object,  this  object  is  cast 
to  a  superclass  T  of  all  the  expected  classes. 

• 

12.6. 

CONTEXT-SENSITIVE  POINTER  ANALYSIS 

945 

While  many  large  Java  applications  use  reflection,  they  tend  to  use  common 
idioms,  such  as  the  one  shown  in  Example  12.25.  As  long  as  the  application 
does  not  redefine  the  class  loader,  we  can  tell  t he  class  of  the  object  if  we  know 
the  value  of  className.  If  the  value  of  className  is  defined  in  the  program, 
because  strings  are  immutable  in  Java,  knowing  what  className  points  to 
will  provide  t he  name  of  the  class.  This  technique  is  another  use  of  points-to 
analysis.  If  the  value  of  className  is  based  on  user  input,  then  the  points-to 
analysis  can  help  locate  where  the  value  is  entered,  and  t he  developer  may  be 
able  to  limit  the  scope  of  its  value. 

Similarly,  we  can  exploit  the  typecast  statement,  line  (4)  in  Example  12.25, 
to  approximate  the  type  of  dynamically  created  objects.  Assuming  t h at  the 
typecast  exception  handler  has  not  been  redefined,  t he  object  must  belong  to  a 
subclass  of  the  class  T. 

12.5.4  Exercises  for  Section  12.5 

E x e r c i se  1 2 . 5 . 1:  For  the  code  of  Fig.  12.26 

a)  Construct  the  E DB  relations  actual, 

formal,  and  cha. 

b)  Make  all  possible  inferences  of  pts  and  hpts  facts. 

E x e r c i se  1 2 . 5 . 2:  How  would  you  add  to  the  E DB  predicates  and  rules  of 
Section  12.5.2  additional  predicates  and  rules  to  take  into  account  the  fact  t h at 
if  a  method  call  returns  an  object,  then  the  variable  to  which  the  result  of  t he 
call  is  assigned  can  point  to  whatever  the  variable  holding  the  return  value  can 
point  to? 

12.6  Context-Sensitive  Pointer  Analysis 

As  discussed  in  Section  12.1.2,  context  sensitivity  can  improve  greatly  the  pre 
cision  of interprocedural  analysis.  We  talked  about  two  approaches  to  interpro 
cedural  analysis,  one  based  on  cloning  (Section  12.1.4)  and  one  on  summaries 
(Section  12.1.5).  Which  one  should  we  use? 

There  are  several  difficulties  in  computing  the  summaries  of points-to  infor 
mation.  First,  the  summaries  are  large.  Each  method's  summary  must  include 
the  effect  of  all  the  updates  t h at  the  function  and  all  its  callees  can  make,  in 
terms  of  the  incoming  parameters.  T h at  is,  a  method  can  change  the  points-to 
sets  of  all  d a ta  reachable  through  static  variables,  incoming  parameters  and  all 
objects  created  by  the  method  and  its  callees.  While  complicated  schemes  have 
been  proposed,  there  is  no  known  solution  t h at  can  scale  to  large  programs. 
Even  if  the  summaries  can  be  computed  in  a  bottom-up  pass,  computing  the 
points-to  sets  for  all  the  exponentially  many  contexts  in  a  typical  top-down 
pass  presents  an  even  greater  problem.  Such  information  is  necessary  for  global 
queries  like  finding  all  points  in  the  code  t h at  touch  a  certain  object. 

946 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

In  this  section,  we  discuss  a  cloning-based  context-sensitive  analysis.  A 

cloning-based  analysis  simply  clones  the  methods,  one  for  each  context  of  in 
terest.  We  then  apply  the  context-insensitive  analysis  to  t he  cloned  call  graph. 
While  this  approach  seems  simple,  the  devil  is  in  the  details  of  handling  the 
large  number  of  clones.  How  many  contexts  are  there?  Even  if  we  use  t he 
idea  of  collapsing  all  recursive  cycles,  as  discussed  in  Section  12.1.3,  it  is  not 
uncommon  to  find  1 014  contexts  in  a  Java  application.  Representing  the  results 
of  these  many  contexts  is  the  challenge. 

We  separate  the  discussion  of  context  sensitivity  into  two  parts: 

1.  How  to  handle  context  sensitivity  logically?  This  part  is  easy,  because  we 
simply  apply  t he  context-insensitive  algorithm  to  the  cloned  call  graph. 

2.  How  to  represent  the  exponentially  many  contexts?  One  way  is  to  rep 
resent  the  information  as  binary  decision  diagrams  (BDD's),  a  highly-
optimized  d a ta  structure  t h at  has  been  used  for  many  other  applications. 

This  approach  to  context  sensitivity  is  an  excellent  example  of  the  impor 
tance  of  abstraction.  As  we  are  going  to  show,  we  eliminate  algorithmic  com 
plexity  by  leveraging  the  years  of work  t h at  went  into  the  BDD  abstraction.  We 
can  specify  a  context-sensitive  points-to  analysis  in  just  a  few  lines  of  Datalog, 
which  in  t u rn  takes  advantage  of  many  thousands  of  lines  of  existing  code  for 
BDD  manipulation.  This  approach  has  several  important  advantages.  First, 
it  makes  possible  t he  easy  expression  of  further  analyses  t h at  use  the  results 
of  the  points-to  analysis.  After  all,  the  points-to  results  on  their  own  are  not 
interesting.  Second,  it  makes  it  much  easier  to  write  the  analysis  correctly,  as 
it  leverages  many  lines  of  well-debugged  code. 

12.6.1  Contexts  and  Call  Strings 

The  context-sensitive  points-to  analysis  described  below  assumes  t h at  a  call 
graph  has  been  already  computed.  This  step  helps  make  possible  a  compact 
representation  of  the  many  calling  contexts.  To  get  t he  call  graph,  we  first  run 
a  context-insensitive  points-to  analysis  t h at  computes  t he  call  graph  on  t he  fly, 
as  discussed  in  Section  12.5.  We  now  describe  how  to  create  a  cloned  call  graph. 
A  context  is  a  representation  of  the  call  string  t h at  forms  the  history  of  t he 
active  function  calls.  Another  way  to  look  at  t he  context  is  t h at  it  is  a  summary 
of  the  sequence  of  calls  whose  activation  records  are  currently  on  the  run-time 
stack.  If  there  are  no  recursive  functions  on  the  stack,  then  the  call  string  — 
the  sequence  of  locations  from  which  the  calls  on  the  stack  were  made  —  is  a 
complete  representation. 
It  is  also  an  acceptable  representation,  in  t he  sense 
t h at  there  is  only  a  finite  number  of  different  contexts,  although  t h at  number 
may  be  exponential  in  the  number  of  functions  in  the  program. 

However,  if  there  are  recursive  functions  in  t he  program,  then  the  number 
of possible  call  strings  is  infinite,  and  we  cannot  allow  all  possible  call  strings  to 
represent  distinct  contexts.  There  are  various  ways  we  can  limit  t he  number  of 

12.6. 

CONTEXT-SENSITIVE  POINTER  ANALYSIS 

947 

distinct  contexts.  For  example,  we  can  write  a  regular  expression  t h at  describes 
all  possible  call  strings  and  convert  t h at  regular  expression  to  a  deterministic 
finite  automaton,  using  the  methods  of  Section  3.7.  T he  contexts  can  then  be 
identified  with  the  states  of  this  automaton. 

Here,  we  shall  adopt  a  simpler  scheme  t h at  captures  the  history  of nonrecur 
sive  calls  but  considers  recursive  calls  to  be  "too  hard  to  unravel."  We  begin  by 
finding  all  the  mutually  recursive  sets  of functions  in  the  program.  T he  process 
is  simple  and  will  not  be  elaborated  in  detail  here.  Think  of  a  graph  whose 
nodes  are  the  functions,  with  an  edge  from  p  to  q  if  function  p  calls  function 
q.  T he  strongly  connected  components  (SCC's)  of  this  graph  are  the  sets  of 
mutually  recursive  functions.  As  a  common  special 
function  p  t h at  calls 
itself,  but  is  not  in  an  SCC  with  any  other  function  is  an  SCC  by  itself.  T he 
nonrecursive  functions  are  also  SCC's  by  themselves.  Call  an  SCC  nontrivial 
if  it  either  has  more  t h an  one  member  (the  mutually  recursive  case),  or  it  has 
a  single,  recursive  member.  The  SCC's  t h at  are  single,  nonrecursive  functions 
are  trivial  SCC's. 

Our  modification  of  the  rule  t h at  any  call  string  is  a  context  is  as  follows. 

Given  a  call  string,  delete  the  occurrence  of  a  call  site  s  if 

1.  s  is  in  a  function  p. 

2.  Function  q  is  called  at  site  s  (q  =  p  is  possible). 

3.  p  and  q  are  in  the  same  strong  component  (i.e.,  p  and  q  are  mutually 

recursive,  or  p  =  q  and  p  is  recursive). 

The  result  is  t h at  when  a  member  of  a  nontrivial  SCC  S  is  called,  the  call  site 
for  t h at  call  becomes  part  of  the  context,  but  calls  within  S  to  other  functions 
in  t he  same  SCC  are  not  part  of  the  context.  Finally,  when  a  call  outside  5  is 
made,  we  record  t h at  call  site  as  part  of  the  context. 

E x a m p le  1 2 . 2 6:  In  Fig.  12.28  is  a  sketch  of five methods  with  some  call  sites 
and  calls  among  them.  An  examination  of  the  calls  shows  t h at  q  and  r  are 
mutually  recursive.  However,  p,  s,  and  t  are  not  recursive  at  all.  Thus,  our 
contexts  will  be  lists  of  all  the  call  sites  except s3  and s5,  where  the  recursive 
calls  between  q  and  r  take  place. 

Let  us  consider  all  the  ways  we  could  get  from p  to  t,  t h at  is,  all  the  contexts 

in  which  calls  to  t  occur: 

1.  p  could  call  s  at  s2,  and  then  s  could  call  t  at  either  s7  or s8.  Thus,  two 

possible call strings are (s2, s7)  and (s2, s8). 

2.  p  could  call  q  at  s i.  Then,  q  and  r  could  call  each  other  recursively  some 

number  of  times.  We  could  break  the  cycle: 

(a)  At s4,  where  t  is  called  directly  by  q.  This  choice  leads  to  only  one 

context, ( s i, s4). 

948 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

void p()  { 

h:  T a = new T ( ); 

si:  T  b  =  a.q(); 
b.s(); 
s2: 

} 

T 

q() 

i 

s3:  T c = t h i s . rO ; 
i:  T d = new T ( ); 

s4: 

d . t Q; 

return d; 

} 

T 

r()  { 
s5:  T e  = t h i s . q O; 
s6: 

e.s(); 

return e; 

void s()  { 

s7:  T f  = t h i s . t O; 
s8: 

f  =  f.t(); 

} 

T 

} 

t()  { 
j:  T g = new T O; 

return  g; 

Figure  12.28:  Methods  and  call  sites  for  a  running  example 

(b)  At s6,  where  r  calls  s.  Here,  we  can  reach  t  either  by  t he  call  at s7 

or  t he  call  at s8.  T h at  gives  us  two  more  contexts,  ( s i, s6, s7)  and 
(sl,s6, s8). 

There  are  thus  five  different  contexts  in  which  t  can  be  called.  Notice  t h at  all 
these  contexts  omit  the  recursive call  sites, s3  and s5.  For example,  the  context 
( s i, s4)  actually represents the infinite set of call strings  ( s i, s3, (s5, s 3 )n, s4) 
for  all  n  >  0. 

• 

' 

We  now  describe  how  we  derive  t he  cloned  call  graph.  Each  cloned  method 
is  identified  by  the  method  in  t he  program  M  and  a  context  C.  Edges  can  be 
derived  by  adding  the  corresponding  contexts  to  each  of the  edges  in  the  original 
call  graph.  Recall  t h at  there  is  an  edge  in  the  original  call  graph  linking  call 
site  S  with  method  M  if  t he  predicate  invokes (S,  M)  is  true.  To  add  contexts 

12.6. 

CONTEXT-SENSITIVE  POINTER  ANALYSIS 

949 

to  identify  t he  methods  in  the  cloned  call  graph,  we  can  define  a  corresponding 
CSinvokes  predicate  such  t h at  CSinvokes(S,  C,  M,  D)  is  true  if  t he  call  site  S 
in  context  C  calls  t he  D  context  of  method  M. 

12.6.2  Adding  Context  to  Datalog  Rules 

To  find  context-sensitive  points-to  relations,  we  can  simply  apply  the  same 
context-insensitive  points-to  analysis  to  t he  cloned  call  graph.  Since  a  method 
in  t he  cloned  call  graph  is  represented  by  the  original  method  and  its  context, 
we  revise  all  the  Datalog  rules  accordingly.  For  simplicity,  the  rules  below  do 
not  include  the  type  restriction,  and  the  _'s  are  any  new  variables. 

1) 

pts(V,C,H) 

:- 

"H  :  TV  =  new  T ( )"  & 
CSinvokes(H,  C,  _,  _) 

2) 

pts(V,C,H) 

:- 

uV  =  W"k 

3) 

hpts(H,F,G) 

:- 

4) 

pts{V,C,H) 

:- 

pts(W,C,H) 

"V.F  =  W"  k 
pts(W,C,G) 
k 
pts(V,C,  H) 

"V  =  W.F"k 
pts(W,C,G) 
k 
hpts(G,  F,  H) 

5) 

pts(V,D,H) 

:- 

CSinvokes(S,C,M,D) 

k 

formal(M,I,V) 
actual (S,  I,  W)  & 
pts{W,C,  H) 

k 

Figure  12.29:  Datalog  program  for  context-sensitive  points-to  analysis 

An  additional  argument,  representing  the  context,  must  be  given  to  t he  IDB 
predicate  pts.  pts(V,  C,  H)  says  t h at  variable  V  in  context  C  can  point  to  heap 
object  H.  All  the  rules  are  self-explanatory,  perhaps  with  the  exception  of  Rule 
5.  Rule  5  says  t h at  if the  call  site  5  in  context  C  calls  method  M  of  context  D, 
then  t he  formal  parameters  in  method  M  of  context  D  can  point  to  t he  objects 
pointed  to  by  t he  corresponding  actual  parameters  in  context  C. 

12.6.3  Additional  Observations  About  Sensitivity 

W h at  we  have  described  is  one  formulation  of  context  sensitivity  t h at  has  been 
shown  to  be  practical  enough  to  handle  many  large  real-life  Java  programs, 

950 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

using the  tricks  described  briefly in  the  next  section.  Nonetheless,  this  algorithm 
cannot  yet  handle  the  largest  of  Java  applications. 

The  heap  objects  in  this  formulation  are  named  by  their  call  site,  but  with 

out  context  sensitivity.  T h at  simplification  can  cause  problems.  Consider  t he 
object-factory  idiom  where,  all  objects  of  the  same  type  are  allocated  by  the 
same  routine.  The  current  scheme  would  make  all  objects  of t h at  class  share  the 
same  name.  It  is  relatively  simple  to  handle  such  cases  by  essentially  inlining 
the  allocation  code.  In  general,  it  is  desirable  to  increase  t he  context  sensitivity 
in  the  naming  of  objects.  While  it  is  easy  to  add  context  sensitivity  of  objects 
to  t he  Datalog  formulation,  getting  t he  analysis  to  scale  to  large  programs  is 
another  m a t t e r. 

Another  important  form  of  sensitivity  is  object  sensitivity.  An  object-
sensitive  technique  can  distinguish  between  methods  invoked  on  different  re 
ceiver  objects.  Consider  the  scenario  of  a  call  site  in  a  calling  context  where 
a  variable  is  found  to  point  to  two  different  receiver  objects  of  the  same  class. 
Their fields may  point  to  different  objects.  Without  distinguishing  between  the 
objects,  a  copy  among  fields  of  the  t h is  object  reference  will  create  spurious 
relationships  unless  we  separate  the  analysis  according  to  t he  receiver  objects. 
Object  sensitivity  is  more  useful  t h an  context  sensitivity  for  some  analyses. 

12.6.4  Exercises  for  Section  12.6 

void  pO  { 

h:  T  a  =  new  TO ; 
i:  T b = new T ( ); 

cl:  T  c  =  a.q(b); 

q(T  y)  < 

j : T  d  = new T ( ); 
c2: 

d  = this.q(d); 
d  = d.q(y); 
d  = d.r(); 

c3: 
c4: 

return  d; 

T 

r()  { 

return  this; 

} 

Figure  12.30:  Code  for  Exercises  12.6.1  and  12.6.2 

E x e r c i se  1 2 . 6 . 1:  W h at  are  all  the  contexts  t h at  would  be  distinguished  if  we 
apply  the  methods  of  this  section  to  the  code  in  Fig.  12.30? 

12.7. 

DATALOG 

IMPLEMENTATION  BY  BDD'S 

951 

!  E x e r c i se  1 2 . 6 . 2:  Perform  a  context  sensitive  analysis  of the  code  in  Fig.  12.30. 

!  E x e r c i se  1 2 . 6 . 3:  Extend  the  Datalog  rules  of  this  section  to  incorporate  the 

type  and  subtype  information,  following  the  approach  of  Section  12.5. 

12.7  Datalog  Implementation  by  BDD's 

Binary  Decision  Diagrams  (BDD's)  are  a  method  for  representing  boolean  func 
tions  by  graphs.  Since  there  are  22"  boolean  functions  of  n  variables,  no  repre 
sentation  method  is  going  to  be  very  succinct  on  all  boolean  functions.  However, 
the  boolean  functions  t h at  appear  in  practice  tend  to  have  a  lot  of regularity.  It 
is  thus  common  t h at  one  can  find  a  succinct  BDD  for  functions  t h at  one  really 
wants  to  represent. 

It  t u r ns  out  t h at  the  boolean  functions  t h at  are  described  by  t he  Datalog 
programs  t h at  we  have  developed  to  analyze  programs  are  no  exception.  While 
succinct  BDD's  representing  information  about  a  program  often  must  be  found 
using  heuristics  a n d / or  techniques  used  in  commercial  BDD-manipulating  pack 
ages,  the  BDD  approach  has  been  quite  successful  in  practice. 
In  particular, 
it  outperforms  methods  based  on  conventional  database-management  systems, 
because  the  latter  are  designed  for  the  more  irregular  d a ta  patterns  t h at  appear 
in  typical  commercial  data. 

It  is  beyond  t he  scope  of  this  book  to  cover  all  of the  BDD  technology  t h at 
has  been  developed  over  the  years.  We  shall  here  introduce  you  to  t he  BDD 
notation.  We  then  suggest  how  one  represents  relational  d a ta  as  BDD's  and 
how  one  could  manipulate  BDD's  to  reflect  the  operations  t h at  are  performed 
to  execute  Datalog  programs  by  algorithms  such  as  Algorithm  12.18.  Finally, 
we  describe  how  to  represent  the  exponentially  many  contexts  in  BDD's,  the 
key  to  the  success  of  the  use  of  BDD's  in  context-sensitive  analysis. 

12.7.1  Binary  Decision  Diagrams 

A  BDD  represents  a  boolean  function  by  a  rooted  DAG.  The  interior  nodes  of 
the  DAG  are  each  labeled  by  one  of  the  variables  of  the  represented  function. 
At  the  b o t t om  are  two  leaves,  one  labeled  0  the  other  labeled  1.  Each  interior 
node  has  two  edges  to  children;  these  edges  are  called  "low"  and  "high."  T he 
low  edge  is  associated  with  the  case  t h at  the  variable  at  the  node  has  value  0, 
and  the  high  edge  is  associated  with  the  case  where  the  variable  has  value  1. 

Given  a  t r u th  assignment  for  the  variables,  we  can  start  at  the  root,  and 
at  each  node,  say  a  node  labeled  x,  follow  the  low  or  high  edge,  depending 
on  whether  t he  t r u th  value  for  x  is  0  or  1,  respectively. 
If  we  arrive  at  t he 
leaf  labeled  1,  then  the  represented  function  is  true  for  this  t r u th  assignment; 
otherwise  it  is  false. 

E x a m p le  1 2 . 2 7:  In  Fig.  12.31  we  see  a  BDD.  We  shall  see  the  function  it 
represents  shortly.  Notice  t h at  we  have  labeled  all  the  "low"  edges  with  0  and 

952 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

Figure  12.31:  A  binary  decision  diagram 

all  the  "high"  edges  by  1.  Consider  the  t r u th  assignment  for  variables  wxyz 
t h at  sets  w  =  x  =  y  =  0  and  z  =  1.  Starting  at  the  root,  since  w  —  0  we  take 
the  low  edge,  which  gets  us  to  t he  leftmost  of t he  nodes  labeled  x.  Since  x  =  0, 
we  again  follow  the  low  edge  from  this  node,  which  takes  us  to  the  leftmost  of 
the  nodes  labeled  y.  Since  y  =  0  we  next  move  to  the  leftmost  of  the  nodes 
labeled  z.  Now,  since  z  =  1,  we  take  the  high  edge  and  wind  up  at  t he  leaf 
labeled  1.  Our  conclusion  is  t h at  t he  function  is  t r ue  for  this  t r u th  assignment. 
Now,  consider  the  t r u th  assignment  wxyz  =  0101,  t h at  is,  w  =  y  =  0  and 
x  =  z  =  1.  We  again  start  at  the  root.  Since  w  =  0  we  again  move  to  the 
leftmost  of the  nodes  labeled  x.  But  now,  since  x  =  1,  we  follow  t he  high  edge, 
which  j u m ps  to  the  0  leaf.  T h at  is,  we  know  not  only  t h at  t r u th  assignment 
0101  makes  the  function  false,  but  since  we  never  even  looked  at  y  or  z,  any 
t r u th  assignment  of  the  form  Qlyz  will  also  make  the  function  have  value  0. 
This  "short-circuiting"  ability  is  one  of  the  reasons  BDD's  tend  to  be  succinct 
representations  of  boolean  functions. 

• 

In  Fig.  12.31  the  interior  nodes  are  in  ranks  —  each  rank  having  nodes  with 
a  particular  variable  as  label.  Although  it  is  not  an  absolute  requirement,  it  is 
convenient  to  restrict  ourselves  to  ordered  BDD's.  In  an  ordered  BDD,  there  is 
an  order  x\,xi,... 
,xn  to  t he  variables,  and  whenever  there  is  an  edge  from  a 
parent  node  labeled  Xi  to  a  child  labeled  Xj,  then  i  <  j.  We  shall  see  t h at  it 
is  easier  to  operate  on  ordered  BDD's,  and  from  here  we  assume  all  BDD's  are 

12.7. 

DATALOG 

IMPLEMENTATION  BY  BDD'S 

953 

ordered. 

Notice  also  t h at  BDD's  are  DAG's,  not  trees.  Not  only  will  the  leaves  0 
and  1  typically  have  many  parents,  but  interior  nodes  also  may  have  several 
parents.  For  example,  the  rightmost  of  the  nodes  labeled  z  in  Fig.  12.31  has 
two  parents.  This  combination  of  nodes  t h at  would  result  in  t he  same  decision 
is  another  reason  t h at  BDD's  tend  to  be  succinct. 

12.7.2  Transformations  on  BDD's 

We  alluded,  in  t he  discussion  above,  to  two  simplifications  on  BDD's  t h at  help 
make  t h em  more  succinct: 

1.  Short-Circuiting:  If  a  node  N  has  both  its  high  and  low  edges  go  to  the 
same  node  M,  then  we  may  eliminate  N.  Edges  entering  N  go  to  M 
instead. 

2.  Node-Merging:  If  two  nodes  N  and  M  have  low  edges  t h at  go  to  the  same 
node  and  also  have  high  edges  t h at  go  to  the  same  node,  then  we  may 
merge  N  with  M.  Edges  entering  either  N  or  M  go  to  the  merged  node. 

It  is  also  possible  to  run  these  transformations  in  the  opposite  direction. 
In 
particular,  we  can  introduce  a  node  along  an  edge  from  N  to  M.  Both  edges 
from  the  introduced  node  go  to  M,  and  t he  edge  from  TV"  now  goes  to  the 
introduced  node.  Note,  however,  t h at  the  variable  assigned  to  the  new  node 
must  be  one  of  those  t h at  lies  between  the  variables  of  N  and  M  in  the  order. 
Figure  12.32  shows  the  two  transformations  schematically. 

(a) Short-circuiting 

(b) Node-merging 

Figure  12.32:  Transformations  on  BDD's 

954 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

12.7.3  Representing  Relations  by  BDD's 

The  relations  with  which  we  have  been  dealing  have  components  t h at  are  taken 
frorn  "domains."  A  domain  for  a  component  of  a  relation  is  t he  set  of  possible 
values  t h at  tuples  can  have  in  t h at  component.  For  example,  t he  relation 
pts(V,  H)  has  t he  domain  of  all  program  variables  for  its  first  component  and 
the  domain  of  all  object-creating  statements  for  the  second  component. 
If  a 
domain  has  more  t h an  2n _1  possible  values  but  no  more  t h an  2n  values,  then 
it  requires  n  bits  or  boolean  variables  to  represent  values  in  t h at  domain. 

A  tuple  in  a  relation  may  thus  be  viewed  as  a  t r u th  assignment  to  the 
variables  t h at  represent  values  in  the  domains  for  each  of the  components  of the 
tuple.  We  may  see  a  relation  as  a  boolean  function  t h at  returns  t he  value  t r ue 
for  all  and  only  those  t r u th  assignments  t h at  represent  tuples  in  t he  relation. 
An  example  should  make  these  ideas  clear. 

E x a m p le  1 2 . 2 8:  Consider  a  relation  r(A,  B)  such  t h at  the  domains  of  b o th 
A  and  B  are  {a, b, c, d}.  We  shall  encode  a  by  bits  00,  b  by  01,  c  by  10,  and  d 
by  11.  Let  the  tuples  of relation  r  be: 

A 
a 
a 
d 

B 
b 
c 
c 

Let  us  use  boolean  variables  wx  to  encode  the  first  (A)  component  and  variables 
yz  to  encode  the  second  (B)  component.  Then  the  relation  r  becomes: 

w  X 
0 
0 
0 
0 
1 
1 

y 
0 
l 
l 

z 
1 
0 
0 

T h at  is,  t he  relation  r  has  been  converted  into  t he  boolean  function  t h at  is 
true  for  the  three  truth-assignments  wxyz  =  0001,  0010,  and  1110.  Notice  t h at 
these  three  sequences  of  bits  are  exactly  those  t h at  label  t he  paths  from  t he 
root  to  t he  leaf  1  in  Fig.  12.31.  T h at  is,  the  BDD  in  t h at  figure  represents  this 
relation  r,  if  the  encoding  described  above  is  used. 

• 

12.7.4  Relational  Operations  as  B DD  Operations 

Now  we  see how to represent  relations  as  BDD's.  But  to  implement  an  algorithm 
like  Algorithm  12.18  (incremental  evaluation  of  Datalog  programs),  we  need 
to  manipulate  BDD's  in  a  way  t h at  reflects  how  the  relations  themselves  are 
manipulated.  Here  are  the  principal  operations  on  relations  t h at  we  need  to 
perform: 

12.7.  DATALOG 

IMPLEMENTATION 

BY 

BDD'S 

955 

1.  Initialization:  We  need  to  create  a  BDD  t h at  represents  a  single  tuple  of 
a  relation.  We'll  assemble  these  into  BDD's  t h at  represent  large  relations 
by  taking  the  union. 

2.  Union:  To  take  the  union  of  relations,  we  take  the  logical  OR  of  t he 
boolean  functions  t h at  represent  the  relations.  This  operation  is  needed 
not  only  to  construct  initial  relations,  but  also  to  combine  the  results  of 
several  rules  for  the  same  head  predicate,  and  to  accumulate  new  facts 
into  t he  set  of  old  facts,  as  in  the  incremental  Algorithm  12.18. 

3.  Projection:  W h en  we  evaluate  a  rule  body,  we  need  to  construct  the  head 
In  terms  of  the 
relation  t h at  is  implied  by  the  true  tuples  of  the  body. 
BDD  t h at  represents  the  relation,  we  need  to  eliminate  the  nodes  t h at 
are  labeled  by  those  boolean  variables  t h at  do  not  represent  components 
of  the  head.  We  may  also  need  to  rename  the  variables  in  the  BDD 
to  correspond  to  the  boolean  variables  for  the  components  of  the  head 
relation. 

4.  Join:  To  find  the  assignments  of  values  to  variables  t h at  make  a  rule 
body  true,  we  need  to  "join"  the  relations  corresponding  to  each  of  the 
subgoals.  For  example,  suppose  we  have  two  subgoals  r(A,B)  k  s(B,  C). 
T he  join  of  t he  relations  for  these  subgoals  is  the  set  of  (a, 6, c)  triples 
such  t h at  (a, 6)  is  a  tuple  in  the  relation  for  r,  and  (6, c)  is  a  tuple  in 
the  relation  for  s.  We  shall  see  t h a t,  after  renaming  boolean  variables  in 
BDD's  so  the  components  for  the  two  B's  agree  in  variable  names,  the 
operation  on  BDD's  is  similar  to  the  logical  AND,  which  in  t u rn  is  similar 
to  the  OR  operation  on  BDD's  t h at  implements  the  union. 

B D D 's  for  S i n g le  T u p l es 

To  initialize  a  relation,  we  need  to  have  a  way  to  construct  a  BDD  for  the 
function  t h at  is  true  for  a  single  t r u th  assignment.  Suppose  the  boolean  vari 
ables  are  Xi,x2,  •  •  •  ,xn,  and  the  t r u th  assignment  is  a\a2  •  •  •  an,  where  each  ai 
is  either  0  or  1.  The  BDD  will  have  one  node  Ni  for  each  Xi.  If 
=  0,  then 
t he  high  edge  from  Ni  leads  to  t he  leaf  0,  and  t he  low  edge  leads  to  Ni+\,  or  to 
the  leaf  1  if  i  =  n.  If  a»  =  1,  then  we  do  the  same,  but  the  high  and  low  edges 
are  reversed. 

This  strategy  gives  us  a  BDD  t h at  checks  whether  each  Xi  has  the  correct 
value,  for  i  =  1 , 2 , . ..  , n.  As  soon  as  we  find  an  incorrect  value,  we  j u mp 
directly  to  the  0  leaf.  We  only  wind  up  at  the  1  leaf  if  all  variables  have  their 
correct  value. 

As  an  example,  look  ahead  to  Fig.  12.33(b).  This  B DD  represents  the 

function  t h at  is  true  if  and  only  if  x  =  y  =  0,  i.e.,  the  t r u th  assignment  00. 

956 

U n i on 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

We  shall  give  in  detail  an  algorithm  for  taking  the  logical  OR  of  BDD's,  t h at 
is,  the  union  of  the  relations  represented  by  the  BDD's. 

A l g o r i t hm  1 2 . 2 9:  Union  of  BDD's. 

I N P U T:  Two  ordered  BDD's  with  the  same  set  of variables,  in  the  same  order. 

O U T P U T:  A  BDD  representing  the  function  t h at  is  the  logical  OR  of  t he  two 
boolean  functions  represented  by  t he  input  BDD's. 

M E T H O D:  We  shall  describe  a  recursive  procedure  for  combining  two  BDD's. 
The  induction  is  on  the  size  of  the  set  of  variables  appearing  in  t he  BDD's. 

B A S I S:  Zero  variables.  The  BDD's  must  b o th  be  leaves,  labeled  either  0  or  1. 
The  output  is  the  leaf labeled  1  if either  input  is  1,  or  t he  leaf labeled  0  if  both 
are  0. 

I N D U C T I O N:  Suppose  there  are  k  variables,  yi,y2,...  ,yu  found  among  t he 
two  BDD's.  Do  the  following: 

1.  If  necessary,  use  inverse  short-circuiting  to  add  a  new  root  so  t h at  b o th 

BDD's  have  a  root  labeled  y\. 

2.  Let  the  two  roots  be  N  and  M;  let  their  low  children  be  Ao  and  Mo,  and 
let  their  high  children  be  N\  and  M\.  Recursively  apply  this  algorithm  to 
the  BDD's  rooted  at  Ao  and  M0.  Also,  recursively  apply  this  algorithm 
to  the  BDD's  rooted  at  N\  and  Mx.  The  first  of  these  BDD's  represents 
the  function  t h at  is  true  for  all  t r u th  assignments  t h at  have  y\  —  0  and 
t h at  make  one  or  b o th  of  the  given  BDD's  true.  T he  second  represents 
t he  same  for  the  t r u th  assignments  with  y\  =  1. 

3.  Create  a  new  root  node  labeled  y\. 

Its  low  child  is  the  root  of  the  first 
recursively  constructed  BDD,  and  its  high  child  is  the  root  of  the  second 
BDD. 

4.  Merge  the  two  leaves  labeled  0  and  t he  two  leaves  labeled  1  in  t he  com 

bined  BDD  just  constructed. 

5.  Apply  merging  and  short-circuiting  where  possible  to  simplify  t he  BDD. 

• 

E x a m p le  1 2 . 3 0:  In  Fig.  12.33(a)  and  (b)  are  two  simple  BDD's.  T he  first 
represents  the  function  x  OR  y,  and  t he  second  represents  t he  function 

NOT  x A ND  NOT  y 

12.7. 

DATALOG 

IMPLEMENTATION  BY  BDD'S 

957 

0 

0 

0 

0 

1 

0 

1 

0 

1 

(a) 

(b) 

(c) 

Figure  12.33:  Constructing  the  BDD  for  a  logical  OR 

Notice  t h at  their  logical  OR  is  the  function  1  t h at  is  always  true.  To  apply 
Algorithm  12.29  to  these  two  BDD's,  we  consider  the  low  children  of  t he  two 
roots  and  t he  high  children  of  t he  two  roots;  let  us  take  up  t he  latter  first. 

T he  high  child  of  the  root  in  Fig.  12.33(a)  is  1,  and  in  Fig.  12.33(b)  it  is  0. 
Since  these  children  are  b o th  at  the  leaf  level,  we  do  not  have  to  insert  nodes 
labeled  y  along  each  edge,  although  t he  result  would  be  t he  same  h ad  we  chosen 
to  do  so.  The  basis  case  for  the  union  of  0  and  1  is  to  produce  a  leaf  labeled  1 
t h at  will  become  t he  high  child  of  the  new  root. 

T he  low  children  of  t he  roots  in  Fig.  12.33(a)  and  (b)  are  b o th  labeled  y, 
so  we  can  compute  their  union  BDD  recursively.  These  two  nodes  have  low 
children  labeled  0  and  1,  so  the  combination  of  their  low  children  is  the  leaf 
labeled  1.  Likewise,  their  high  children  are  1  and  0,  so  the  combination  is 
again  t he  leaf  1.  When  we  add  a  new  root  labeled  x,  we  have  the  BDD  seen  in 
Fig.  12.33(c). 

We  are  not  done,  since  Fig.  12.33(c)  can  be  simplified.  T he  node  labeled  y 
has  b o th  children  the  node  1,  so  we  can  delete  the  node  y  and  have  the  leaf  1 
be  t he  low  child  of  the  root.  Now,  both  children  of  the  root  are  the  leaf  1,  so 
we  can  eliminate  t he  root.  T h at  is,  the  simplest  BDD  for  the  union  is  t he  leaf 
1,  all  by  itself. 

• 

12.7.5  Using  BDD's  for  Points-to  Analysis 

Getting  context-insensitive  points-to  analysis  to  work  is  already  nontrivial.  The 
ordering  of t he  BDD  variables  can  greatly  change  the  size  of the  representation. 
Many  considerations,  as  well  as  trial  and  error,  are  needed  to  come  up  with  an 
ordering  t h at  allows  the  analysis  to  complete  quickly. 

It  is  even  harder  to  get  context-sensitive  points-to  analysis  to  execute  be 
cause  of  the  exponentially  many  contexts  in  the  program.  In  particular,  if  we 

958 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

arbitrarily  assign  numbers  to  represent  contexts  in  a  call  graph,  we  cannot  han 
dle  even  small  Java  programs.  It  is  important  t h at  the  contexts  be  numbered 
so  t h at  the  binary  encoding  of  the  points-to  analysis  can  be  made  very  com 
pact.  Two  contexts  of  the  same  method  with  similar  call  paths  share  a  lot  of 
commonalities,  so  it  is  desirable  to  number  the  n  contexts  of a  method  consecu 
tively.  Similarly,  because  pairs  of caller-callees  for  the  same  call  site  share  many 
similarities,  we  wish  to  number  the  contexts  such  t h at  the  numeric  difference 
between  each  caller-callee  pair  of  a  call  site  is  always  a  constant. 

Even  with  a  clever  numbering  scheme  for  the  calling  contexts,  it  is  still  hard 
to  analyze  large  Java  programs  efficiently.  Active  machine  learning  has  been 
found  useful  in  deriving  a  variable  ordering  efficient  enough  to  handle  large 
applications. 

12.7.6  Exercises  for  Section  12.7 

E x e r c i se  1 2 . 7 . 1:  Using  the  encoding  of  symbols  in  Example  12.28,  develop 
a  BDD  t h at  represents  the  relation  consisting  of  the  tuples  (6, b),  (c, a),  and 
(6,  a).  You  may  order  the  boolean  variables  in  whatever  way  gives  you  the  most 
succinct  BDD. 

!  E x e r c i se  1 2 . 7 . 2:  As  a  function  of  n,  how  many  nodes  are  there  in  the  most 
succinct  BDD  t h at  represents  the  exclusive-or  function  on  n  variables.  T h at  is, 
the  function  is  true  if  an  odd  number  of the  n  variables  are  true  and  false  if  an 
even  number  are  true. 

E x e r c i se  1 2 . 7 . 3:  Modify  Algorithm  12.29  so  it  produces  the  intersection  (log 
ical  AND)  of  two  BDD's. 

!!  E x e r c i se  1 2 . 7 . 4:  Find  algorithms  to  perform  the  following  relational  opera 

tions  on  the  ordered  BDD's  t h at  represent  them: 

a)  Project  out  some  of  the  boolean  variables.  T h at  is,  the  function  repre 

sented  should  be  true  for  a  given  t r u th  assignment  a  if  there  was  any 
t r u th  assignment  for  the  missing  variables  t h a t,  together  with  a  made 
the  original  function  true. 

b)  Join  two  relations  r  and  s,  by  combining  a  tuple  from  r  with  one  from 
s  whenever  these  tuples  agree  on  the  attributes  t h at  r  and  s  have  in 
It  is  really  sufficient  to  consider  the  case  where  the  relations 
common. 
have  only  two  components,  and  one  from  each  relation  matches;  t h at  is, 
the  relations  are  r(A,B)  and  s(B,  C). 

12.8  Summary  of  Chapter  12 

• 

Interprocedural  Analysis:  A  data-flow  analysis 
information 
across  procedure  boundaries  is  said  to  be  interprocedural.  Many  analyses, 

tracks 

t h at 

12.8.  SUMMARY  OF  CHAPTER  12 

959 

such  as  points-to  analysis,  can  only  be  done  in  a  meaningful  way  if  they 
are  interprocedural. 

•  Call  Sites:  Programs  call  procedures  at  certain  points  referred  to  as  call 
sites.  T he  procedure  called  at  a  site  may  be  obvious,  or  it  may  be  am 
biguous,  should  the  call  be  indirect  through  a  pointer  or  a  call  of a  virtual 
method  t h at  has  several  implementations. 

•  Call  Graphs:  A  call  graph  for  a  program  is  a  bipartite  graph  with  nodes 
for  call  sites  and  nodes  for  procedures.  An  edge  goes  from  a  call-site  node 
to  a  procedure  node  if  t h at  procedure  may  be  called  at  t he  site. 

• 

Inlining:  As  long  as  there  is  no  recursion  in  a  program,  we  can  in  principle 
replace  all  procedure  calls  by  copies  of their  code,  and  use  intraprocedural 
analysis  on  the  resulting  program.  This  analysis  is  in  effect,  interproce 
dural. 

•  Flow  Sensitivity  and  Context-Sensitivity:  A  data-flow  analysis  t h at  pro 
duces  facts  t h at  depend  on  location  in  the  program  is  said  to  be  flow-
sensitive. 
If  the  analysis  produces  facts  t h at  depend  on  t he  history  of 
procedure  calls  is  said  to  be  context-sensitive.  A  data-flow  analysis  can 
be  either  flow-  or  context-sensitive,  both,  or  neither. 

+  Cloning-Based  Context-Sensitive  Analysis: 

In  principle,  once  we  establish 

the  different  contexts  in  which  a  procedure  can  be  called,  we  can  imagine 
t h at  there  is  a  clone  of  each  procedure  for  each  context.  In  t h at  way,  a 
context-insensitive  analysis  serves  as  a  context-sensitive  analysis. 

4- 

Summary-Based  Context-Sensitive  Analysis:  Another  approach 

inter 
procedural  analysis  extends  the  region-based  analysis  technique  t h at  was 
described  for  intraprocedural  analysis.  Each  procedure  has  a  transfer 
function  and  is  treated  as  a  region  at  each  place  where  t h at  procedure  is 
called. 

to 

+  Applications  of  Interprocedural  Analysis:  An 

important  application  re 
quiring  interprocedural  analysis  is  the  detection  of  software  vulnerabili 
ties.  These  are  often  characterized  by  having  d a ta  read  from  an  untrusted 
input  source  by  one  procedure  and  used  in  an  exploitable  way  by  another 
procedure. 

•  Datalog:  The  language  Datalog  is  a  simple  notation  for  if-then  rules  t h at 
can  be  used  to  describe  data-flow  analyses  at  a  high  level.  Collections  of 
Datalog  rules,  or  Datalog  programs,  can  be  evaluated  using  one  of  several 
standard  algorithms. 

•  Datalog  Rules:  A  Datalog  rule  consists  of  a  body  (antecedent)  and  head 
(consequent).  The  body  is  one  or  more  atoms,  and  the  head  is  an  atom. 
Atoms  are  predicates  applied  to  arguments  t h at  are  variables  or  constants. 

960 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

T he  atoms  of the  body  are  connected  by  logical  AND,  and  an  atom  in  the 
body  may  be  negated. 

+  IDB  and  EDB  Predicates:  E DB  predicates  in  a  Datalog  program  have 
In  a  data-flow  analysis,  these  predicates 
their  true  facts  given  a-priori. 
correspond  to  the  facts  t h at  can  be  obtained  from  the  code  being  analyzed. 
IDB  predicates  are  defined  by  the  rules  themselves  and  correspond  in  a 
data-flow  analysis  to  t he  information  we  are  trying  to  extract  from  the 
code  being  analyzed. 

+  Evaluation  of Datalog  programs:  We  apply  rules  by  substituting  constants 
for  variables  t h at  make  the  body  true.  Whenever  we  do  so,  we  infer  t h at 
the  head,  with  the  same  substitution  for  variables,  is  also  true.  This 
operation  is  repeated,  until  no  more  facts  can  be  inferred. 

+ 

Incremental  Evaluation  of  Datalog  Programs:  An  efficiency  improvement 
is  obtained  by  doing  incremental  evaluation.  We  perform  a  series  of 
In  one  round,  we  consider  only  substitutions  of  constants  for 
rounds. 
variables  t h at  make  at  least  one  atom  of  the  body  be  a  fact  t h at  was  just 
discovered  on  the  previous  round. 

+  Java  Pointer  Analysis:  We  can  model  pointer  analysis  in  Java  by  a  frame 
work  in  which  there  are  reference  variables  t h at  point  to  heap  objects, 
which  may  have  fields  t h at  point  to  other  heap  objects.  An  insensitive 
pointer  analysis  can  be  written  as  a  Datalog  program  t h at  infers  two  kinds 
of facts:  a  variable  can  point  to  a  heap  object,  or  a  field  of  a  heap  object 
can  point  to  another  heap  object. 

+  Type  Information  to  Improve  Pointer  Analysis:  We  can  get  more  precise 
pointer  analysis  if  we  take  advantage  of  t he  fact  t h at  reference  variables 
can  only  point  to  heap  objects  t h at  are  of  the  same  type  as  the  variable 
or  a  subtype. 

• 

Interprocedural  Pointer  Analysis:  To  make  the  analysis  interprocedural, 
we  must  add  rules  t h at  reflect  how  parameters  are  passed  and  return 
values  assigned  to  variables.  These  rules  are  essentially  t he  same  as  t he 
rules  for  copying  one  reference  variable  to  another. 

•  Call-Graph  Discovery:  Since  Java  has  virtual  methods, 

interprocedural 
analysis  requires  t h at  we  first  limit  what  procedures  can  be  called  at  a 
given  call  site.  The  principal  way  to  discover  limits  on  what  can  be  called 
where  is  to  analyze  the  types  of  objects  and  take  advantage  of  the  fact 
t h at  the  actual  method  referred  to  by  a  virtual  method  call  must  belong 
to  an  appropriate  class. 

•  Context-Sensitive  Analysis:  When  procedures  are  recursive,  we  must  con 
dense  the  information  contained  in  call  strings  into  a  finite  number  of 
contexts.  An  effective  way  to  do  so  is  to  drop  from  the  call  string  any 

12.9.  REFERENCES  FOR  CHAPTER  12 

961 

call  site  where  a  procedure  calls  another  procedure  (perhaps  itself)  with 
which  it  is  mutually  recursive.  Using  this  representation,  we  can  mod 
ify  the  rules  for  intraprocedural  pointer  analysis  so  the  context  is  carried 
along  in  predicates;  this  approach  simulates  cloning-based  analysis. 

4  Binary  Decision  Diagrams:  BDD's  are  a  succinct  representation  of  bool 
ean  functions  by  rooted  DAG's.  The  interior  nodes  correspond  to  boolean 
variables  and  have  two  children,  low  (representing  t r u th  value  0)  and  high 
(representing  1).  There  are two leaves labeled  0  and  1.  A t r u th  assignment 
makes  the  represented  function  true  if  and  only  if  the  p a th  from  the  root 
in  which  we  go  to  the  low  child  if  t he  variable  at  a  node  is  0  and  to  the 
high  child  otherwise,  leads  to  the  1  leaf. 

4  BDD's  and  Relations:  A  BDD  can  serve  as  a  succinct  representation  of 
one  of  t he  predicates  in  a  Datalog  program.  Constants  are  encoded  as 
t r u th  assignments  to  a  collection  of  boolean  variables,  and  the  function 
represented by  the  BDD  is  true  if an  only  if t he  boolean  variables  represent 
a  true  fact  for  t h at  predicate. 

4 

Implementing  Data-Flow  Analysis  by  BDD's:  Any  data-flow  analysis  t h at 
can  be  expressed  as  Datalog  rules  can  be  implemented  by  manipulations 
on  t he  BDD's  t h at  represent  the  predicates  involved  in  those  rules.  Often, 
this  representation  leads  to  a  more  efficient  implementation  of  the  data 
flow  analysis  t h an  any  other  known  approach. 

12.9  References  for  Chapter  12 

Some  of the  basic  concepts  in  interprocedural  analysis  can  be  found  in  [1,  6,  7, 
and  21].  Callahan  et  al.  [11]  describe  an  interprocedural  constant-propagation 
algorithm. 

Steensgaard  [22]  published  the  first  scalable  pointer-alias  analysis. 

It  is 
context-insensitive,  flow-insensitive,  and  equivalence-based.  A  context-insens 
itive  version  of  t he  inclusion-based  points-to  analysis  was  derived  by  Ander 
sen  [2].  Later,  Heintze  and  Tardieu  [15]  described  an  efficient  algorithm  for  this 
analysis.  Fahndrich,  Rehof,  and  Das  [14]  presented  a  context-sensitive,  flow-
insensitive,  equivalence-based  analysis  t h at  scales  to  large  programs  like  g c c. 
Notable  among  previous  a t t e m p ts  to  create  a  context-sensitive,  inclusion-based 
points-to  analysis  is  Emami,  Ghiya,  and  Hendren  [13],  which  is  a  cloning-based 
context-sensitive,  flow-sensitive,  inclusion-based,  points-to  algorithm. 

Binary  decision  diagrams  (BDD's)  first  appeared  in  Bryant  [9].  Their  first 
use  for  data-flow  analysis  was  by  Berndl  et  al.  [4].  The  application  of  BDD's  to 
insensitive  pointer  analysis  is  reported  by  Zhu  [25]  and  Berndl  et  al.  [8].  Whaley 
and  Lam  [24]  describe  the  first  context-sensitive,  flow-insensitive,  inclusion-
based  algorithm  t h at  has  been  shown  to  apply  to  real-life  applications.  T he 
paper  describes  a  tool  called  bddbddb  t h at  automatically  translates  analysis 

962 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

described  in  Datalog  into  BDD  code.  Object-sensitivity  was  introduced  by 
Milanova,  Rountev,  and  Ryder  [18]. 

For  a  discussion  of  Datalog,  see  Ullman  and  Widom  [23].  Also  see  Lam  et 

al.  [16]  for  a  discussion  of  t he  connection  of  data-flow  analysis  to  Datalog. 

The  Metal  code  checker  is  described  by  Engler  et  al.  [12]  and  t he  PREfix 
checker  was  created  by  Bush,  Pincus,  and  Sielaff  [10].  Ball  and  Rajamani  [4] 
developed  a  program  analysis  engine  called  SLAM  using  model  checking  and 
symbolic  execution  to  simulate  all  possible  behaviors  of a  system.  Ball  et  al.  [5] 
have  created  a  static  analysis  tool  called  SDV  based  on  SLAM  to  find  A PI  usage 
errors  in  C  device-driver  programs  by  applying  BDD's  to  model  checking. 

Livshits  and  Lam  [17]  describe  how  context-sensitive  points-to  analysis  can 
be  used  to  find  SQL  vulnerabilities  in  Java  web  applications.  Ruwase  and 
Lam  [20]  describe  how  to  keep  track  of array  extents  and  insert  dynamic  bounds 
checks  automatically.  Rinard  et  al.  [19]  describe  how  to  extend  arrays  dynam 
ically  to  accommodate  for  the  overflowed  contents.  Avots  et  al.  [3]  extend  the 
context-sensitive  Java  points-to  analysis  to  C  and  show  how  it  can  be  used  to 
reduce  the  cost  of  dynamic  detection  of  buffer  overflows. 

1.  Allen,  F.  E.,  "Interprocedural  d a ta  flow  analysis,"  Proc.  IFIP  Congress 

1974,  PP-  398-402,  North  Holland,  Amsterdam,  1974. 

2.  Andersen,  L.,  Program  Analysis  and  Specialization  for  the  C  Programming 
Language,  P h . D.  thesis,  DIKU,  Univ.  of  Copenhagen,  Denmark,  1994. 

3.  Avots,  D.,  M.  Dalton,  V.  B.  Livshits,  and  M.  S.  Lam,  "Improving  software 

security  with  a  C  pointer  analysis,"  ICSE  2005:  Proc.  27th  International 
Conference  on  Software  Engineering,  pp.  332-341. 

4.  Ball,  T.  and  S.  K.  Rajamani,  "A  symbolic  model  checker  for  boolean 

programs,"  Proc.  SPIN  2000  Workshop  on  Model  Checking  of  Software, 
pp.  113-130. 

5.  Ball,  T.,  E.  Bounimova,  B.  Cook,  V.  Levin,  J.  Lichtenber,  C.  McGarvey, 
B.  Ondrusek,  S.  Rajamani,  and  A.  Ustuner,  "Thorough  static  analysis  of 
device  drivers,"  EuroSys  (2006),  pp.  73-85. 

6.  Banning,  J.  P.,  "An  efficient  way  to  find  t he  side  effects  of procedural  calls 

and  the  aliases  of  variables,"  Proc.  Sixth  Annual  Symposium  on  Principles 
of  Programming  Languages  (1979),  pp.  2 9 - 4 1. 

7.  Barth,  J.  M.,  "A  practical  interprocedural  d a ta  flow  analysis  algorithm," 

Comm.  ACM  21:9  (1978),  pp.  724-736. 

8.  Berndl,  M.,  O.  Lohtak,  F.  Qian,  L.  Hendren,  and  N.  Umanee,  "Points-

to  analysis  using  BDD's,"  Proc.  ACM  SIGPLAN  2003  Conference  on 
Programming  Language  Design  and  Implementation,  p p.  103-114. 

9.  Bryant,  R.  E.,  "Graph-based  algorithms  for  Boolean  function  manipula 

tion,"  IEEE  Trans,  on  Computers  C-35:8  (1986),  pp.  677-691. 

12.9. 

REFERENCES  FOR  CHAPTER  12 

963 

10.  Bush,  W.  R.,  J.  D.  Pincus,  and  D.  J.  Sielaff,  "A  static  analyzer  for  finding 

dynamic  programming  errors,"  Software-Practice  and  Experience,  30:7 
(2000),  pp.  775-802. 

11.  Callahan,  D.,  K.  D.  Cooper,  K.  Kennedy,  and  L.  Torczon,  "Interprocedu 

ral  constant  propagation,"  Proc.  SIGPLAN  1986  Symposium  on  Compiler 
Construction,  SIGPLAN  Notices,  21:7  (1986),  pp.  152-161. 

12.  Engler,  D.,  B.  Chelf,  A.  Chou,  and  S.  Hallem,  "Checking  system  rules  us 

ing  system-specific,  programmer-written  compiler  extensions,"  Proc.  Sixth 
USENIX  Conference 
Implementation 
(2000).  pp.  1-16. 

on  Operating  Systems  Design  and 

13.  Emami,  M.,  R.  Ghiya,  and  L.  J.  Hendren,  "Context-sensitive  interproce 
dural  points-to  analysis  in  the  presence  of  function  pointers,"  Proc.  SIG 
PLAN  Conference  on  Programming  Language  Design  and  Implementation 
(1994),  p p.  224-256. 

14.  Fahndrich,  M.,  J.  Rehof,  and  M.  Das,  "Scalable  context-sensitive  flow 
analysis  using  instantiation  constraints,"  Proc.  SIGPLAN  Conference  on 
(2000),  pp.  253-263. 
Programming  Language  Design  and  Implementation 

15.  Heintze,  N.  and  O.  Tardieu,  ""Ultra-fast  aliasing  analysis  using  CLA:  a 
million  lines  of  C  code  in  a  second,"  Proc.  of  the  SIGPLAN  Conference  on 
Programming  Language  Design  and  Implementation  (2001),  pp.  254-263. 

16.  Lam,  M.  S.,  J.  Whaley,  V.  B.  Livshits,  M.  C.  Martin,  D.  Avots,  M.  Carbin, 
and  C.  Unkel,  "Context-sensitive  program  analysis  as  database  queries," 
Proc.  2005  ACM  Symposium  on  Principles  of  Database  Systems,  pp.  1-12. 

17.  Livshits,  V.  B.  and  M.  S.  Lam,  "Finding  security  vulnerabilities  in  Java 
lJ^th  USENIX  Security  Sympo 

applications  using  static  analysis"  Proc. 
sium  (2005),  pp.  271-286. 

18.  Milanova,  A.,  A.  Rountev,  and  B.  G.  Ryder,  "Parameterized  object  sen 
sitivity  for  points-to  and  side-effect  analyses  for  Java"  Proc.  2002  ACM 
SIGSOFT 
and  Analysis, 
on 
pp.  1-11. 

International  Symposium 

Software 

Testing 

19.  Rinard,  M.,  C.  Cadar,  D.  Dumitran,  D.  Roy,  and  T.  Leu,  "A  dynamic 
technique  for  eliminating  buffer  overflow  vulnerabilities  (and  other  mem 
ory  errors),"  Proc.  2004  Annual  Computer  Security  Applications  Confer 
ence,  pp.  82-90. 

20.  Ruwase,  O.  and  M.  S.  Lam,  "A  practical  dynamic  buffer  overflow  detec 

tor,"  Proc. 
posium  (2004),  pp.  159-169. 

11th  Annual  Network  and  Distributed  System  Security  Sym 

964 

CHAPTER 

12. 

INTERPROCEDURAL  ANALYSIS 

21.  Sharir,  M.  and  A.  Pnueli,  "Two  approaches  to  interprocedural  d a ta  flow 

analysis," 
in  S.  Muchnick  and  N.  Jones  (eds.)  Program  Flow  Analysis: 
Theory  and  Applications,  Chapter  7,  p p.  189-234.  Prentice-Hall,  Upper 
Saddle  River  NJ,  1981. 

22.  Steensgaard,  B.,  "Points-to  analysis  in  linear  time,"  Twenty-Third  ACM 

Symposium  on  Principles  of  Programming  Languages 

(1996). 

23.  Ullman,  J.  D.  and  J.  Widom,  A  First  Course  in  Database  Systems,  Pren 

tice-Hall,  Upper  Saddle  River  NJ,  2002. 

24.  Whaley,  J.  and  M.  S.  Lam,  "Cloning-based  context-sensitive  pointer  alias 
analysis  using  binary  decision  diagrams,"  Proc.  ACM  SIGPLAN  2004 
Implementation,  p p. 
Conference  on  Programming  Language  Design  and 
131-144. 

25.  Zhu,  J.,  "Symbolic  Pointer  Analysis,"  "Proc.  International  Conference  in 

Computer-Aided  Design  (2002),  pp.  150-157. 

Appendix  A 

A  Complete  Front  End 

T he  complete  compiler  front  end  in  this  appendix  is  based  on  the  informally 
described  simple  compiler  of  Sections  2.5-2.8.  T he  main  difference  from  Chap 
ter  2  is  t h at  t he  front  end  generates  jumping  code  for  boolean  expressions,  as 
in  Section  6.6.  We  begin  with  the  syntax  of  the  source  language,  described  by 
a  grammar  t h at  needs  to  be  adapted  for  top-down  parsing. 

T he  Java  code  for  t he  translator  consists  of  five  packages:  main, lexer, 
symbol, parser,  and inter.  Package inter  contains  classes  for  the  language 
constructs  in  t he  abstract  syntax.  Since  the  code  for  the  parser  interacts  with 
t he  rest  of  t he  packages,  it  will  be  discussed  last.  Each  package  is  stored  as  a 
separate  directory  with  a  file  per  class. 

Going  into  t he  parser,  the  source  program  consists  of  a  stream  of  tokens,  so 
object-orientation  has  little  to  do  with  the  code  for  the  parser.  Coming  out  of 
t he  parser,  t he  source program  consists  of a syntax tree,  with  constructs  or  nodes 
implemented  as  objects.  These  objects  deal  with  all  of t he  following:  construct 
a  syntax-tree  node,  check  types,  and  generate  three-address  intermediate  code 
(see  package inter). 

A.l  The  Source  Language 

A  program  in  the  language  consists  of  a  block  with  optional  declarations  and 
statements.  Token  b a s ic  represents  basic  types. 

-> 
-> 

program 
block 
decls 
decl 
type 
stmts 

block 
{  decls  stmts  } 
decls  decl 
|  e 
type  id  ; 
type  [  n um  ] 
stmts  stmt  1  e 

|  b a s ic 

Treating  assignments  as  statements,  rather  t h an  as  operators  within  expres 

sions,  simplifies  translation. 

965 

966 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

Object-Oriented  Versus  Phase-Oriented 

W i th  an  object-oriented  approach,  all  the  code  for  a  construct  is  collected 
in  the  class  for  the  construct.  Alternatively,  with  a  phase-oriented  ap 
proach,  the  code  is  grouped  by  phase,  so  a  type  checking  procedure  would 
have  a  case  for  each  construct,  and  a  code  generation  procedure  would 
have  a  case  for  each  construct,  and  so  on. 

The  tradeoff  is  t h at  an  object-oriented  approach  makes  it  easier  to 
change  or  add  a  construct,  such  as  "for"  statements,  and  a  phase-oriented 
approach  makes  it  easier  to  change  or  add  a  phase,  such  as  type  checking. 
W i th  objects,  a  new  construct  can  be  added  by  writing  a  self-contained 
class,  but  a  change  to  a phase,  such  as  inserting  code  for  coercions,  requires 
changes  across  all  t he  affected  classes.  W i th  phases,  a  new  construct  can 
result  in  changes  across  the  procedures  for  the  phases. 

stmt 

loc 

-» 
| 
| 
| 
| 
| 
| 
->• 

loc  =  bool  ; 

if  (  bool)  stmt 
if  (  bool)  stmt  e l se  stmt 
w h i le  (  bool)  stmt 
do  stmt  w h i le  (  bool)  ; 
b r e ak  ; 
block 
loc  [  bool ] 

id 

| 

The  productions  for  expressions  handle  associativity  and  precedence  of  op 
erators.  They  use  a  nonterminal  for  each  level  of precedence  and  a  nonterminal, 
factor,  for  parenthesized  expressions,  identifiers,  array  references,  and  constants. 

bool  1  1  join  |  join 
join  kk  equality 
equality  ==  rel  \  equality  ! =  rel  \  rel 
expr  <  expr  \  expr  <=  expr  \  expr >=  expr  \ 

equality 

| 

expr  >  expr  J  expr 
\ 

expr  +  term 
term  *  unary 
!  unary 
(  bool  ) 

\ 
| 

expr  -  term 

\ 
term  1  unary 
factor 
|  real 

\ 
|  n um 

-  unary 
loc 

\ 

term 
\  unary 

|  t r ue 

|  false 

bool 
join 
equality 
rel 

expr 
term 
unary 
factor 

-+ 
-+ 
-t 

-> 

-> 

A.  2  Main 

Execution  begins  in  method  main  in  class  Main.  Method  main  creates  a  lexical 
analyzer  and  a  parser  and  then  calls  method  program  in  t he  parser: 

1) package main; 
2)  import  java.io.*;  import  lexer.*;  import parser.*; 

//  File  Main.Java 

A.3. 

LEXICAL  ANALYZER 

967 

public  static  void main(String[]  args)  throws  IOException { 

3) public  class  Main { 
4) 
5) 
6) 
7) 

Lexer  lex = new LexerQ; 
Parser parse = new Parser(lex); 
parse .programO ; 

System.out.write('\n')j 

8) 
9) 
10) } 

> 

A.3  Lexical  Analyzer 

Package  l e x er  is  an  extension  of  the  code  for  the  lexical  analyzer  in  Sec 
tion  2.6.5.  Class  Tag  defines  constants  for  tokens: 

//  File  Tag.java 

public final  static  int 

1) package lexer; 
2) public  class  Tag { 
3) 
4) 
5) 
6) 
7) 

= 261,  FALSE = 262,  GE 

AND  = 256,  BASIC = 257,  BREAK  = 258,  DO  = 259,  ELSE  = 260, 
= 265, 
EQ 
= 270, 
INDEX = 266,  LE 
OR  »= 271,  REAL  = 272,  TEMP  = 273,  TRUE = 274,  WHILE = 275; 

= 263;  ID  = 264,  IF 
= 267,  MINUS = 268,  NE  = 269,  NUM 

Three  of  the  constants,  INDEX,  MINUS,  and  TEMP,  are  not  lexical  tokens;  they 
will  be  used  in  syntax  trees. 

Classes  Token  and  Num  are  as  in  Section  2.6.5,  with  m e t h od  t o S t r i ng  added: 

1) package lexer; 
2) public  class  Token { 
3) 
4) 

public  final  int  tag; 
public Token(int t)  { tag = t;  > 

//  File  Token.Java 

public  String toStringO  {return  ""  +  (char)tag;} 

5) 
6 )> 

//  File  Num.Java 

1) package lexer; 
2) public  class  Num extends  Token { 
public final  int value; 
3) 
public Num(int v)  { super(Tag.NUM);  value = v;  } 
4) 
5) 
public  String toStringO  { return  11"  + value;  } 
6)1 

Class  Word  manages  lexemes  for  reserved  words,  identifiers,  and  composite 
tokens  like  kk.  It  is  also  useful  for  managing  the  written  form  of  operators  in 
t he  intermediate  code  like  unary  minus;  for  example,  the  source  text  -2  has  t he 
intermediate  form  minus  2. 

//  File  Word.java 

1) package lexer; 
2) public  class  Word extends  Token  { 
public  String lexeme  =  ""; 
3) 
public  WordCString s,  int tag)  { super(tag);  lexeme = s;  } 
4) 
public String toStringO  { return lexeme;  } 
5) 
public  static  final Word 
6) 

7) 

and =  new  Word(  "kk",  Tag.AND  ),  or  = new  Word(  "II",  Tag.OR  ), 

968 

8) 
9) 
10) 
11) 
12) 
13) 
14) } 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

eq  = new Word(  "==",  Tag.EQ  ),  ne = new Word(  "!=", Tag.NE ), 
le  = new Word(  "<=",  Tag.LE  ),  ge = new Word(  ">=", Tag.GE ), 
minus  = new Word(  "minus",  Tag.MINUS  ), 
True  = new Word(  "true",  Tag.TRUE  ), 
False  = new Word(  "false",  Tag.FALSE ), 
Tag.TEMP  ); 
temp 

= new Word(  "t", 

Class Real  is  for  floating  point  numbers: 

1) package lexer; 

//  File  Real.java 

2) public class Real extends Token •[ 
public final float  value; 
3) 
public Real(float v)  { super(Tag.REAL);  value = v;  } 
4) 
5) 
public String toStringO  { return  ""  + value;  } 
6 )> 

The  main  method  in  class  Lexer,  function scan,  recognizes  numbers,  iden 

tifiers,  and  reserved  words,  as  discussed  in  Section 2.6.5. 

Lines 9-13  in  class Lexer  reserve  selected  keywords.  Lines 14-16  reserve 
lexemes  for  objects  defined  elsewhere.  Objects Word.True  and Word.False 
are  defined  in  class Word.  Objects  for  the  basic  types int, char, bool,  and 
float  are  defined  in  class Type,  a  subclass  of Word.  Class Type  is  from  package 
symbols. 

//  File  Lexer.Java 

public  static  int  line = 1; 
char peek = '  '; 
Hashtable words = new Hashtable(); 
void reserve(Word w)  { words.put(w.lexeme,  w );  } 
public Lexer()  { 

1) package lexer; 
2)  import  java.io.*;  import  java.util.*;  import  symbols.*; 
3) public  class  Lexer  { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) 
14) 
15) 
16) 
17) 

reserve(  new Word("if", 
); 
reserve( new Word("else",  Tag.ELSE)  ); 
reserve( new Word("while",  Tag.WHILE)  ); 
reserve( new Word("do", 
); 
reserve( new Word("break",  Tag.BREAK)  ); 
reserve( Word.True  );  reserve( Word.False ); 
reserve(  Type.Int  );  reserve(  Type.Char  ); 
reserve(  Type.Bool  );  reserve( Type.Float  ); 

Tag.DO) 

Tag.IF) 

} 

Function r e a d c hO  (line 18)  is  used  to  read  t he  next  input  character  into 
variable peek.  The  name readch  is  reused  or  overloaded  (lines  19-24)  to 
help  recognize  composite  tokens.  For  example,  once  input  <  is  seen,  t he  call 
r e a d c hO = >)  reads  the  next  character  into peek  and  checks  whether  it  is  =. 

18) 
19) 
20) 
21) 
22) 
23) 
24) 

void readchO  throws  IOException { peek =  (char)System.in.read();  } 
boolean readch(char  c)  throws  IOException { 

readchO; 
if( peek  != c ) return false; 
peek = '  '; 
return true; 

> 

A.3. 

LEXICAL  ANALYZER 

969 

Function  s c an  begins  by  skipping  white  space  (lines  26-30).  It  recognizes 

composite  tokens  like  <=  (lines  31-44)  a nd  numbers  like  365  a nd  3 . 14  (lines 

45-58),  before  collecting  words  (lines  59-70). 

25) 
26) 
27) 
28) 
29) 
30) 
31) 
32) 
33) 
34) 
35) 
36) 
37) 
38) 
39) 
40) 
41) 
42) 
43) 
44) 
45) 
46) 
47) 
48) 
49) 
50) 
51) 
52) 
53) 
54) 
55) 
56) 
57) 
58) 
59) 
60) 
61) 
62) 
63) 
64) 
65) 
66) 
67) 
68) 
69) 
70) 

public  Token  scan() 

throws  IOException  { 

f o r( 

; 

;  readchO  )  { 

' 

' 
i f(  peek  == 
e l se  i f(  peek  == 
e l se  break; 

II  peek  == 
' \ n'  )  l i ne  =  l i ne  +  1; 

' \ t'  )  continue; 

switchC  peek  )  { 
: 
case 

i f( 

readchO &') 

)  r e t u rn  Word.and; 

e l se  r e t u rn  new  Token('&' 

case 

' I ': 

if (  readchC  |  ') 

)  r e t u rn  Word.or; 

e l se  r e t u rn  new  T o k e n ( ' |' 

case 

' = ': 

i f( 

r e a d c h ( ' = ') 

case 

' ! ': 

i f( 

r e a d c h ( ' = ') 

case 

' < ': 

i f( 

r e a d c h ( ' = ') 

case 

' > ': 

i f( 

r e a d c h ( ' = ') 

)  r e t u rn  Word.eq; 

)  r e t u rn  Word.ne; 

)  r e t u rn  Word.le; 

)  r e t u rn  Word.ge; 

} 
i f(  C h a r a c t e r . i s D i g i t ( p e e k) 

)  { 

e l se  r e t u rn  new  Token('=' 

e l se  r e t u rn  new  T o k e n ( ' !' 

e l se  r e t u rn  new  Token('<' 

e l se  r e t u rn  new  Token('>' 

i nt  v  =  0; 
do  { 

v  =  10*v  +  C h a r a c t e r . d i g i t ( p e e k,  10);  r e a d c h O; 

); 
' .'  )  r e t u rn  new  Num(v); 

}  while(  C h a r a c t e r . i s D i g i t ( p e e k) 
i f(  peek  != 
f l o at  x  =  v;  f l o at  d  =  10; 
f o r ( ; ;)  { 

readchO  ; 
i f(  !  C h a r a c t e r . i s D i g i t ( p e e k) 
x  =  x  +  C h a r a c t e r . d i g i t ( p e e k,  10)  /  d;  d  =  d*10; 

)  break; 

> 
r e t u rn  new  R e a l ( x ); 

> 
i f(  C h a r a c t e r . i s L e t t e r ( p e e k) 

)  { 

StringBuffer  b  =  new  S t r i n g B u f f e r ( ); 
do  { 

b. append (peek) ;  r e a d c h O; 

>  while(  C h a r a c t e r . i s L e t t e r O r D i g i t ( p e e k) 
S t r i ng  s  =  b . t o S t r i n gO  ; 
Word  w  =  (Word)words.get(s); 
i f(  w  !=  n u ll  )  r e t u rn  w; 
w  =  new  Word(s,  Tag.ID); 
w o r d s . p u t ( s,  w); 
r e t u rn  w; 

); 

Finally,  any  remaining  characters  are  r e t u r n ed  as  tokens  (lines  71-72). 

Token  tok  =  new  Token(peek);  peek  = 
r e t u rn 

tok; 

' 

'; 

71) 
72) 
73) 
74)  > 

> 

970 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

A.4 

Symbol  Tables  and  Types 

Package symbols  implements  symbol  tables  and  types. 

Class Env is  essentially unchanged  from  Fig.  2.37.  Whereas  class Lexer  maps 
strings  to  words,  class Env  maps  word  tokens  to  objects  of  class Id,  which  is 
defined  in  package inter  along  with  the  classes  for  expressions  and  statements. 

//  File  Env.Java 

private Hashtable table; 
protected  Env prev; 
public Env(Env n)  { table = new HashtableO;  prev = n;  } 
public void put(Token w,  Id i) { table.put(w,  i);  } 
public  Id get(Token w)  { 

1) package symbols; 
2)  import java.util.*;  import lexer.*;  import  inter.*; 
3) public  class  Env { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) 
14) 
15)  > 

Id found = (Id)(e.table.get(w)); 
if( found  != null ) return found; 

for( Env e = this;  e  != null;  e = e.prev ) { 

> 
return null; 

> 

We  define  class Type  to  be  a  subclass  of Word  since  basic  type  names  like int 
are  simply  reserved  words,  to  be  mapped  from  lexemes  to  appropriate  objects  by 
the lexical analyzer.  T he objects for the basic types are Type. Int, Type. Float, 
Type.Char,  and Type.Bool  (lines  7-10).  All  of  them  have  inherited  field tag 
set  to Tag.BASIC,  so  the  parser  treats  them  all  alike. 

public  int  width  = 0; 
public Type(String s,  int tag,  int w) { super(s, tag);  width = w;  } 
public  static final Type 

// width is used for storage allocation 

//  File  Type.java 

1) package symbols; 
2)  import  lexer.*; 
3) public  class  Type  extends Word { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 

= new Type(  "int", 

Int 
Tag.BASIC,  4  ), 
Float = new Type(  "float",  Tag.BASIC,  8 ), 
Char  = new Type(  "char",  Tag.BASIC,  1 ), 
Bool  = new Type(  "bool",  Tag.BASIC,  1  ); 

Functions numeric  (lines  11-14)  and max  (lines  15-20)  are  useful  for  type 

conversions. 

public  static boolean numeric(Type p)  { 

if (p == Type.Char I I p == Type.Int  I I p == Type.Float) return true; 
else return false; 

> 
public  static  Type max(Type pi,  Type  p2  )  { 

if (  ! numeric(pl)  ||  ! numeric(p2) ) return null; 
else if  ( pi == Type.Float  ||  p2 == Type.Float  ) return Type.Float; 
else  if  ( pi == Type.Int 
else return Type.Char; 

)  return Type.Int; 

||  p2 == Type.Int 

11) 
12) 
13) 
14) 
15) 
16) 
17) 
18) 
19) 
20)  > 
21)  > 

A.5. 

INTERMEDIATE  CODE  FOR  EXPRESSIONS 

971 

Conversions  are  allowed  between  the  "numeric"  types Type.Char, Type. Int, 
and Type. Float.  W h en an arithmetic operator is applied to two numeric types, 
t he  result  is  t he  "max"  of  t he  two  types. 

Arrays  are  t he  only  constructed  type  in  t he  source  language.  T he  call  to 
super  on  line 7  sets  field width,  which  is  essential  for  address  calculations.  It 
also  sets lexeme  and tok  to  default  values  t h at  are  not  used. 

public  Type  of; 
public  int  size  = 1; 
public Array(int  sz,  Type p)  { 

1) package symbols; 
2) import  lexer.*; 
3) public  class  Array  extends  Type  { 
4) 
5) 
6) 
7) 
8) 
9) 
10)  } 

//  File  Array.Java 

// array *of* type 
// number of elements 

super("[]", Tag.INDEX,  sz*p.width);  size = sz;  of = p; 

> 
public String toStringO  { return " [" + size + "]  " + of .toStringO;  } 

A.5 

Intermediate  Code  for  Expressions 

Package inter  contains  the Node  class  hierarchy. Node  has  two  subclasses: Expr 
for  expression  nodes  and Stmt  for  statement  nodes.  This  section  introduces 
Expr  and  its  subclasses.  Some  of  the  methods  in Expr  deal  with  booleans  and 
jumping  code;  they  will  be  discussed  in  Section  A.6,  along  with  the  remaining 
subclasses  of Expr. 

Nodes  in  t he  syntax tree  are  implemented  as  objects  of class Node.  For  error 
reporting,  field lexline  (line 4,  file  Node.Java)  saves  the  source-line  number  of 
the  construct  at  this  node.  Lines 7-10  are  used  to  emit  three-address  code. 

//  File  Node.java 

1) package inter; 
2) import  lexer.*; 
3) public  class  Node  { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11)  } 

int  lexline  =  0; 
Node()  { lexline = Lexer.line;  } 
void error(String s)  { throw new Error("near line  "+lexline+":  "+s);  } 
static  int  labels  =  0; 
public int newlabelO  -[ return ++labels;  } 
public void emitlabel(int i) { System.out.print("L" + i + " : " ); } 
public void emit(String s)  { System.out.println("\t"  + s);  } 

Expression  constructs  are  implemented  by  subclasses  of Expr.  Class Expr 
has  fields op  and type  (lines 4-5,  file  Expr.java),  representing  the  operator  and 
type,  respectively,  at  a  node. 

//  File  Expr.java 

1) package inter; 
2) import  lexer.*;  import  symbols.*; 
3) public  class  Expr  extends  Node  { 
4) 
5) 
6) 

public  Token  op; 
public  Type  type; 
Expr(Token tok,  Type p)  { op = tok;  type = p;  } 

972 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

Method gen  (line  7)  returns  a  "term"  t h at  can  fit  the  right  side  of  a  three-

address  instruction.  Given  expression  E  =  E1+E2,  method gen  returns  a  term 
xi+x2,  where  X\  and  x2  are  addresses  for  t he  values  of  Ei  and  E2,  respectively. 
The  return  value this  is  appropriate  if  this  object  is  an  address;  subclasses  of 
Expr  typically  reimplement gen. 

Method reduce  (line  8)  computes  or  "reduces"  an  expression  down  to  a 
single  address;  t h at  is,  it  returns  a  constant,  an  identifier,  or  a  temporary  name. 
Given  expression  E,  method reduce  returns  a  temporary  t  holding  t he  value  of 
E.  Again, this  is  an  appropriate  return  value  if  this  object  is  an  address. 

We  defer  discussion  of  methods jumping  and emit jumps  (lines  9-18)  until 

Section  A.6;  they  generate  jumping  code  for  boolean  expressions. 

public Expr gen()  { return this;  > 
public Expr reduce()  { return this;  } 
public void jumping(int  t,  int f)  { emitjumps(toStringO,  t,  f );  } 
public void emitjumps(String test,  int t,  int f)  { 

if( t  != 0 && f  != 0 )  { 

emit("if  " + test + " goto L" + t ); 
emit("goto L" + f ); 

} 
else if( t  != 0 ) emit("if " + test + " goto L" + t ); 
else if( f  != 0 ) emit("iffalse  " + test + " goto L" + f ); 
else  ;  // nothing since both t and f fall through 

} 
public  String toStringO  { return op.toStringO ;  > 

7) 
8) 
9) 
10) 
11) 
12) 
13) 
14) 
15) 
16) 
17) 
18) 
19) 
20) } 

Class Id  inherits  the  default  implementations  of gen  and reduce  in  class 

Expr,  since  an  identifier  is  an  address. 

1) package inter; 
2) import  lexer.*;  import  symbols.*; 
3) public  class  Id extends  Expr { 
4) 
5) 

//  File  Id.Java 

public  int  offset; 
public Id(Word id,  Type p,  int b)  { super(id,  p );  offset = b;  } 

// relative address 

6)> 

T he  node  for  an  identifier  of  class Id  is  a  leaf.  T he  call super(id,p)  (line  5, 
file  Id.java)  saves id  and p  in  inherited  fields op  and type,  respectively.  Field 
offset  (line  4)  holds  the  relative  address  of this  identifier. 

Class Op  provides  an  implementation  of reduce  (lines  5-10,  file  Op.java) 
t h at  is  inherited  by  subclasses Arith  for  arithmetic  operators, Unary  for  unary 
operators,  and Access  for  array  accesses.  In  each  case, reduce  calls gen  to 
generate  a  term,  emits  an  instruction  to  assign  the  t e rm  to  a  new  t e m p o r a ry 
name,  and  returns  t he  temporary. 

//  File  Op.java 

1) package inter; 
2) import  lexer.*;  import  symbols.*; 
3) public  class  Op extends  Expr { 
4) 
5) 
6) 

public 0p(Token tok,  Type p)  { super(tok,  p );  } 
public  Expr reduce()  { 
Expr x = gen(); 

A.5. 

INTERMEDIATE  CODE  FOR  EXPRESSIONS 

973 

Temp  t  =  new  Temp(type); 
emit(  t . t o S t r i n gO  +  "  =  "  +  x . t o S t r i n gO  ); 
r e t u rn 

t; 

7) 
8) 
9) 
10) 
11)  } 

} 

Class Arith  implements  binary  operators  like  +  and  *.  Constructor Arith 
begins by calling super (tok, null)  (line  6),  where tok is  a token representing 
the  operator  and null  is  a  placeholder  for  the  type.  The  type  is  determined 
on  line  7  by  using Type.max,  which  checks  whether  the  two  operands  can  be 
coerced  to  a  common  numeric  type;  the  code  for Type.max  is  in  Section  A.4. 
If  they  can  be  coerced, type  is  set  to  t he  result  type;  otherwise,  a  type  error 
is  reported  (line  8).  This  simple  compiler  checks  types,  but  it  does  not  insert 
type  conversions. 

//  File  Arith.java 

public  Expr  e x p r l,  expr2; 
p u b l ic  Arith(Token  tok,  Expr  x l,  Expr x2)  { 
s u p e r ( t o k,  n u l l );  exprl  =  x l; expr2 = x2; 
type  =  Type.max(exprl.type, expr2.type); 
if  (type  ==  n u ll  )  e r r o r ( " t y pe  e r r o r " ); 

import  symbols.*; 

1)  package  i n t e r; 
2)  import  l e x e r . *; 
3)  p u b l ic  c l a ss  Arith  extends  Op  { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) 
14) 
15) 
16)  } 

} 
p u b l ic  S t r i ng  t o S t r i n gO  { 

> 
p u b l ic  Expr  gen()  •[ 

} 

r e t u rn  new  Arith(op,  e x p r l . r e d u c e ( ),  expr2.reduce()); 

r e t u rn  e x p r l . t o S t r i n g ( ) +"  " + o p . t o S t r i n g ( ) +"  "+expr2.toStringO; 

Method gen  constructs  the  right  side  of a three-address  instruction  by  reduc 
ing  the  subexpressions  to  addresses  and  applying  the  operator  to  the  addresses 
(line  11,  file  Arith.java).  For  example,  suppose gen  is  called  at  the  root  for 
a+b*c.  T he  calls  to reduce  return a  as  the  address  for  subexpression a  and  a 
t e m p o r a ry t  as  the  address  for  b*c.  Meanwhile, reduce  emits  the  instruction 
t=b*c.  Method gen  returns  a  new Arith node,  with  operator  *  and  addresses 
a  and t  as  o p e r a n d s .1 

It  is  worth  noting  t h at  temporary  names  are  typed,  along  with  all  other 
expressions.  The  constructor Temp  is  therefore  called  with  a type  as  a  parameter 
(line  6,  file  Temp.Java).2 

1) package  i n t e r; 
2)  import  l e x e r . *; 
import  symbols.*; 
3)  p u b l ic  c l a ss  Temp  extends  Expr  { 

//  File  Temp.java 

1F or  error  reporting,  field  l e x l i ne  in  class  Node  records  the  current  lexical  line  number 
when  a  node  is  constructed.  We  leave  it  to  the  reader  to  track  line  numbers  when  new  nodes 
are  constructed  during  intermediate  code  generation. 

2An  alternative  approach  might  be  for  the  constructor  to  take  an  expression  node  as  a 

parameter,  so  it  can  copy  the  type  and  lexical  position  of  the  expression  node. 

974 

4) 
5) 
6) 
7) 
8 )> 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

static  int  count  =  0; 
int  number  =  0; 
public Temp(Type p)  { super(Word.temp,  p );  number = ++count;  > 
public  String toStringO  { return  "t"  + number;  } 

Class Unary  is  the  one-operand  counterpart  of  class Arith: 

//  File  Unary.Java 

1) package  inter; 
2)  import  lexer.*;  import  symbols.*; 
3) public  class Unary extends  Op { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 

public  Expr  expr; 
public Unary(Token tok,  Expr x)  { 
super(tok, null);  expr = x; 
type = Type.max(Type.Int,  expr.type); 
if  (type == null )  error("type error"); 

> 
public Expr gen()  { return new Unary(op,  expr.reduce());  } 

// handles minus,  for  !  see Not 

11) 
12) } 

public  String toStringO  { return  op.toString()+"  "+expr.toStringO;  } 

A.6  Jumping  Code  for  Boolean  Expressions 

Jumping  code  for  a  boolean  expression  B  is  generated  by  method  jumping, 
which  takes  two  labels t  and  f  as  parameters,  called  the  t r ue  and  false  exits  of 
B,  respectively.  The  code  contains  a  j u mp  to t  if  B  evaluates  to  true,  and  a 
j u mp  to  f  if  B  evaluates  to  false.  By  convention,  the  special  label 0  means  t h at 
control  falls  through  B  to  the  next  instruction  after  the  code  for  B. 

We  begin  with  class Constant.  The  constructor Constant  on  line 4  takes 
a  token tok  and  a  type  p  as  parameters. 
It  constructs  a  leaf  in  t he  syntax 
tree  with  label tok  and  type  p.  For  convenience,  the  constructor Constant  is 
overloaded  (line 5)  to  create  a  constant  object  from  an  integer. 

//  File  Constant.Java 

public Constant(Token tok,  Type p) { super(tok,  p );  } 
public Constant(int i) { super(new Num(i),  Type.Int);  } 
public  static final  Constant 

True  = new Constant(Word.True,  Type.Bool), 
False = new Constant(Word.False,  Type.Bool); 

1) package inter; 
2)  import  lexer.*;  import  symbols.*; 
3) public  class  Constant  extends  Expr { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) } 

> 

public  void jumping(int  t,  int  f)  { 

if  ( this == True && t  !=  0 ) emit("goto L" + t ); 
else if  ( this == False && f  !=  0)  emit("goto L" + f ); 

Method  jumping  (lines 9-12,  file  Constant.Java)  takes  two  parameters,  labels 
t  and  f.  If  this  constant  is  the  static  object True  (defined  on  line 7)  and t  is 
not  the  special  label 0,  then  a j u mp  to t  is  generated.  Otherwise,  if this  is  t he 
object False  (defined  on  line 8)  and  f  is  nonzero,  then  a j u mp  to  f  is  generated. 

A.6. 

JUMPING  CODE  FOR  BOOLEAN  EXPRESSIONS 

975 

Class  L o g i c al  provides  some  common  functionality  for  classes  Or,  And,  and 
Not.  Fields  x  and  y  (line  4)  correspond  to  the  operands  of  a  logical  opera 
tor.  (Although  class  Not  implements  a  unary  operator,  for  convenience,  it  is  a 
subclass  of  L o g i c a l .)  The  constructor  L o g i c al ( t o k, a, b)  (lines  5-10)  builds 
In  doing  so  it  uses 
a  syntax  node  with  operator  t ok  and  operands  a  and  b. 
function  check  to  ensure  t h at  b o th  a  and  b  are  booleans.  Method  gen  will  be 
discussed  at  the  end  of  this  section. 

//  File  Logical.java 

public Expr exprl,  expr2; 
Logical(Token tok,  Expr xl,  Expr x2)  { 

1) package  inter; 
2) import  lexer.*;  import  symbols.*; 
3) public  class  Logical  extends  Expr { 
4) 
5) 
6) 
7) 
8) 
9) 

super(tok,  null); 
exprl = xl;  expr2 = x2; 
type = check(exprl.type,  expr2.type); 
if  (type == null )  error("type error"); 

// null type to start 

public Type  check(Type pi,  Type p2)  { 

if  ( pi == Type.Bool && p2 == Type.Bool  )  return Type.Bool; 
else return null; 

public Expr gen()  { 

int f = newlabelQ;  int  a = newlabelQ; 
Temp temp = new Temp(type); 
this.jumping(0,f); 
emit (temp. toStringO  + " = true"); 
emit("goto L" + a ); 
emitlabel(f);  emit(temp.toStringO  +  "  = false"); 
emitlabel(a) ; 
return  temp; 

public  String  toStringO  { 

return  exprl.toString()+"  "+op.toString()+"  "+expr2.toStringO; 

10)  } 
11) 
12) 
13) 
14)  } 
15) 
16) 
17) 
18) 
19) 
20) 
21) 
22) 
23) 
24)  > 
25) 
26) 
27)  } 
28) } 

In  class  Or,  method  jumping  (lines  5-10)  generates  jumping  code  for  a 
boolean  expression  B  =  B\  \  \B2.  For  the  moment,  suppose  t h at  neither  the 
t r ue  exit  t  nor  the  false  exit  f  of  B  is  the  special  label  0.  Since  B  is  true  if  B\ 
is  true,  the  true  exit  of  B\  must  be  t  and  t he  false  exit  corresponds  to  the  first 
instruction  of  B2 •  The  true  and  false  exits  of  B2  are  the  same  as  those  of  B. 

public 0r(Token tok, Expr xl, Expr x2) { super(tok, xl, x2);  } 
public  void jumping(int  t,  int  f)  { 

//  File  Or.Java 

1) package  inter; 
2) import  lexer.*;  import  symbols.*; 
3) public  class  Or  extends  Logical  i 
4) 
5) 
6) 
7) 
8) 
9) 

int label = t  != 0 ? t  : newlabel(); 
exprl.jumpingdabel, 0 ); 
expr2.jumping(t,f) ; 
if( t == 0 ) emitlabel(label); 

10)  > 
11) } 

976 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

In  t he  general  case, t,  t he  t r ue  exit  of B,  can  be  t he  special  label  0.  Variable 
label  (line  6,  file  Or.java)  ensures  t h at  t he  t r ue  exit  of  Bi  is  set  properly  to 
t he  end  of  t he  code  for  B.  If t  is  0,  t h en label  is  set  to  a  new  label  t h at  is 
emitted  after  code  generation  for  b o th  B\  a nd  B2. 

T he  code  for  class  And  is  similar  to  t he  code  for Or. 

public  And(Token  tok,  Expr  x l,  Expr  x2)  {  super(tok,  x l,  x2);  } 
i nt  f)  { 
public  void  jumping(int 
:  newlabel(); 

//  File  And.Java 

import  symbols.*; 

1) package  i n t e r; 
2)  import  l e x e r . *; 
3)  public  c l a ss  And  extends  Logical  { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) > 

t, 
i nt  l a b el  =  f  !=  0  ?  f 
exprl.jumping(0, 
e x p r 2 . j u m p i n g ( t , f ); 
i f(  f  ==  0  )  e m i t l a b e l ( l a b e l ); 

l a b e l ); 

} 

Class Not  has  enough  in  common  with  t he  other  boolean  operators  t h at  we 
make  it  a  subclass  of Logical,  even  t h o u gh Not  implements  a  u n a ry  operator. 
T he  superclass  expects  two  operands,  so b  a p p e a rs  twice  in  t he  call  to super 
on  line  4.  Only  y  (declared  on  line  4,  file  Logical.java)  is  used  in  t he  m e t h o ds 
on  lines  5-6.  On  line  5,  m e t h od jumping  simply  calls  y. jumping  with  t he  t r ue 
a nd  false  exits  reversed. 

//  File  Not.java 

l e x e r . *; 

import  symbols.*; 

1) package  i n t e r; 
2)  import 
3)  public  c l a ss  Mot  extends  Logical  { 
4) 
5) 
6) 

p u b l ic  Not(Token  t o k,  Expr  x2)  {  s u p e r ( t o k,  x2,  x2);  > 
public  void  jumping(int 
public  S t r i ng  t o S t r i n gO  {  r e t u rn  o p . t o S t r i n g ( ) +"  " + e x p r 2 . t o S t r i n g O;  } 

i nt  f)  {  expr2.jumping(f, 

t );  } 

t, 

7 )> 

Class Rel implements t he operators <,  <=,  ==,  ! =,  >=,  and  >.  Function check 

(lines  5-9)  checks  t h at  t he  two  operands  have  t he  same  t y pe  and  t h at  t h ey  are 

not  arrays.  For  simplicity,  coercions  are  not  p e r m i t t e d. 

//  File  Rel.java 

public  ReKToken  tok,  Expr  x l,  Expr  x2)  {  super(tok,  x l,  x2);  } 
public  Type  check(Type  p i,  Type  p2)  { 

if  (  pi  instanceof  Array  I  I  p2  instanceof  Array  )  r e t u rn  n u l l; 
e l se  i f(  pi  ==  p2  )  r e t u rn  Type.Bool; 
e l se  r e t u rn  n u l l; 

import  symbols.*; 

1) package  i n t e r; 
2)  import  l e x e r . *; 
3)  public  c l a ss  Rel  extends  Logical  { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) 

Expr  a  =  e x p r l . r e d u c e ( ); 
Expr  b  =  e x p r 2 . r e d u c e ( ); 

> 
public  void  jumping(int 

t, 

i nt  f)  { 

S t r i ng  t e st  =  a . t o S t r i n gO  +  "  "  +  o p . t o S t r i n gO  +  " 
f ); 

emitjumps(test, 

t, 

14) 
15) 
16) } 

} 

11  +  b . t o S t r i n g O; 

A.6. 

JUMPING  CODE  FOR  BOOLEAN  EXPRESSIONS 

977 

Method  jumping  (lines  10-15,  file  Rel.Java)  begins  by  generating  code  for  the 
subexpressions  x  and  y  (lines  11-12).  It  then  calls  method  emitjumps  defined 
on  lines  10-18,  file  Expr.java,  in  Section  A.5. 
If  neither  t  nor  f  is  the  special 
label  0,  then  emitjumps  executes  t he  following 

12) 
13) 

e m i t ( " if  "  +  t e st  +  "  goto  L"  +  t) ; 
emit("goto  L"  +  f ); 

//  File  Expr.java 

At  most  one  instruction  is  generated  if  either  t  or  f  is  the  special  label  0  (again, 
from  file  Expr.java): 

15) 
16) 
17) 

e l se  i f(  t  !=  0  )  emitC'if  "  +  t e st  +  "  goto  L"  +  t ); 
e l se  i f(  f  !=  0  )  e m i t C ' i f f a l se  "  +  t e st  +  "  goto  L"  +  f ); 
//  nothing  since  both  t  and  f  f a ll  through 
e l se 

; 

For  another  use  of  emitjumps,  consider  t he  code  for  class  A c c e s s.  T he 
source  language  allows  boolean  values  to  be  assigned  to  identifiers  and  array 
elements,  so  a  boolean  expression  can  be  an  array  access.  Class  Access  has 
method  gen  for  generating  "normal"  code  and  method  jumping  for  jumping 
code.  Method  jumping  (line  11)  calls  emitjumps  after  reducing  this  array 
access  to  a  temporary.  T he  constructor  (lines  6-9)  is  called  with  a  flattened 
array  a,  an  index  i,  and  the  type  p  of  an  element  in  the  flattened  array.  Type 
checking  is  done  during  array  address  calculation. 

//  File  Access.Java 

public  Id  a r r a y; 
public  Expr  index; 
public  Access(Id  a,  Expr  i,  Type  p)  { 

l e x e r . *; 

1) package  i n t e r; 
2)  import 
import  symbols.*; 
3)  public  c l a ss  Access  extends  Op  •[ 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) 
14) 
15)  } 

index  =  i; 

> 

> 
public  Expr  gen()  {  r e t u rn  new  Access(array, 
p u b l ic  void  jumping(int 
public  S t r i ng  t o S t r i n gO  { 

super(new  Word("[]",  Tag.INDEX),  p ); 
array  =  a; 

t , i nt  f)  {  e m i t j u m p s ( r e d u c e ( ) . t o S t r i n g O , t , f );  } 

i n d e x . r e d u c e ( ), 

t y p e );  } 

r e t u rn  array . t o S t r i n gO  +  "  [  "  +  index. t o S t r i n gO  +  "  ] "; 

//  p  is  element  type  a f t er 
//  f l a t t e n i ng  the  array 

Jumping  code  can  also  be  used  to  return  a  boolean  value.  Class  L o g i c a l, 
earlier  in  this  section,  has  a  method  gen  (lines  15-24)  t h at  returns  a  temporary 
temp,  whose  value  is  determined  by  the flow of control  through  the jumping  code 
for  this  expression.  At  the  true  exit  of this  boolean  expression,  temp  is  assigned 
t r u e;  at  the  false  exit,  temp  is  assigned  false.  The  temporary  is  declared  on 
line  17.  J u m p i ng  code  for  this  expression  is  generated  on  line  18  with  the  true 
exit  being  the  next  instruction  and  the  false  exit  being  a  new  label  f.  T he  next 
instruction  assigns  t r ue  to  temp  (line  19),  followed  by  a  j u mp  to  a  new  label 
a  (line  20).  The  code  on  line  21  emits  label  f  and  an  instruction  t h at  assigns 
f a l se  to  temp.  T he  code  fragment  ends  with  label  a,  generated  on  line  22. 
Finally,  gen  returns  temp  (line  23). 

978 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

A.7 

Intermediate  Code  for  Statements 

Each  statement  construct  is  implemented  by  a  subclass  of  Stmt.  T he  fields  for 
the  components  of  a  construct  are  in  the  relevant  subclass;  for  example,  class 
While  has  fields  for  a  test  expression  and  a  substatement,  as  we  shall  see. 

Lines  3-4  in  the  following  code  for  class  Stmt  deal  with  syntax-tree  con 
struction.  T he  constructor  S t m tO  does  nothing,  since  the  work  is  done  in  the 
subclasses.  The  static  object  S t m t . N u ll  (line  4)  represents  an  empty  sequence 
of  statements. 

//  File  Stmt.Java 

1) package  i n t e r; 
2)  public  c l a ss  Stmt  extends  Node  { 
3) 
4) 
5) 
6) 
7) 
8)> 

public  StmtO  {  } 
public  s t a t ic  Stmt  Null  =  new  S t m t O; 
public  void  gen(int  b, 
i nt  a f t er  = 0; 
//  saves 
public  s t a t ic  Stmt  Enclosing  =  Stmt.Null; 

i nt  a)  O  //  c a l l ed  with  l a b e ls  begin  and  a f t er 
l a b el  a f t er 

//  used  for  break  stmts 

Lines  5-7  deal  with  the  generation  of three-address  code.  T he  method  gen  is 
called  with  two  labels  b  and  a,  where  b  marks  the  beginning  of the  code  for  this 
statement  and  a  marks  the  first  instruction  after  the  code  for  this  statement. 
Method  gen  (line  5)  is  a  placeholder  for  the  gen  methods  in  the  subclasses. 
T he  subclasses  While  and  Do  save  their  label  a  in  the  field  a f t er  (line  6)  so 
it  can  be  used  by  any  enclosed  break  statement  to  j u mp  out  of  its  enclosing 
construct.  The  object  Stmt . E n c l o s i ng  is  used  during  parsing  to  keep  track 
of  the  enclosing  construct. 
(For  a  source  language  with  continue  statements, 
we  can  use  the  same  approach  to  keep  track  of  the  enclosing  construct  for  a 
continue  statement.) 

The  constructor  for  class  If  builds  a  node  for  a  statement  if  (E)  S.  Fields 
e x pr  and  s t mt  hold  the  nodes  for  E  and  5,  respectively.  Note  t h at  e x pr  in 
lower-case  letters  names  a  field  of  class  Expr;  similarly,  s t mt  names  a  field  of 
class  Stmt. 

//  File  If.Java 

1) package  i n t e r; 
2)  import  symbols.*; 
3)  public  c l a ss  If  extends  Stmt  { 
Expr  expr;  Stmt  stmt; 
4) 
5) 
public  If(Expr  x,  Stmt  s)  { 
6) 
7) 

expr  =  x; 
i f(  expr.type 

stmt  =  s; 

!=  Type.Bool  )  e x p r . e r r o r ( " b o o l e an  required  in  i f " ); 

8) 
9) 
10) 
11) 
12) 
13) 
14)  } 

> 
p u b l ic  void  g e n ( i nt  b, 

i nt  a)  { 

l a b el  =  n e w l a b e l O; 

i nt 
expr.jumping(0,  a ); 
e m i t l a b e l ( l a b e l );  s t m t . g e n ( l a b e l,  a ); 

//  l a b el  for  t he  code  for  stmt 
//  f a ll  through  on  t r u e,  goto  a  on  f a l se 

} 

The  code  for  an  If  object  consists  of jumping  code  for  e x pr  followed  by  t he 
code  for  s t m t.  As  discussed  in  Section  A.6,  the  call  e x p r. j u m p i n g (0 ,f )  on  line 

A.7. 

INTERMEDIATE  CODE  FOR 

STATEMENTS 

979 

11  specifies  t h at  control  must  fall  through  the  code  for expr  if expr  evaluates 
to  true,  and  must  flow  to  label a  otherwise. 

The  implementation  of  class  Else,  which  handles  conditionals  with  else 

p a r t s,  is  analogous  to  t h at  of  class If: 

//  File  Else.java 

1) package  inter; 
2) import  symbols.*; 
3) public  class Else  extends  Stmt  { 
Expr expr;  Stmt stmti,  stmt2; 
4) 
public Else(Expr x,  Stmt si,  Stmt s2)  { 
5) 
expr = x;  stmti = si;  stmt2 = s2; 
6) 
7) 
if( expr.type  != Type.Bool ) expr.error("boolean required in if"); 
8)  } 
9) 
10) 
11) 
12) 
13) 
14) 
15)  } 
16) > 

public void gen(int b,  int a)  { 
// labell for stmti 
int labell = newlabelO; 
// label2 for stmt2 
int label2 = newlabelO; 
expr.jumping(0,label2); 
// fall through to stmti on true 
emitlabel(labell); stmti.gen(label1, a ); emit("goto L" + a ); 
emitlabel(label2); stmt2.gen(label2, a ); 

T he  construction  of a While  object  is  split  between  the  constructor While (), 

which  creates  a  node  with  null  children  (line  5),  and  an  initialization  function 
init(x,s),  which  sets  child expr  to x  and  child stmt  to s  (lines  6-9).  Function 
gen(b,a)  for  generating  three-address  code  (line  10-16)  is  in  the  spirit  of  the 
corresponding  function gen()  in  class If.  The  difference  is  t h at  label a  is  saved 
in  field after  (line  11)  and  t h at  t he  code  for stmt  is  followed  by  a  j u mp  to  b 
(line  15)  for  the  next  iteration  of  the  while  loop. 

//  File  While.Java 

1) package  inter; 
2) import  symbols.*; 
3) public class While extends Stmt •{ 
4) 
5) 
6) 
7) 
8) 
9)  > 

Expr expr;  Stmt stmt; 
public WhileO •{ expr = null;  stmt = null; > 
public void init(Expr x,  Stmt  s)  { 

expr = x;  stmt = s; 
if( expr.type  != Type.Bool ) expr.error("boolean required in while"); 

10) 

public void gen(int b,  int a)  { 

11) 
12) 
13) 
14) 

15) 

16)  } 
17) > 

after = a; 
expr.jumping(0, a ); 
int label = newlabelO; 
emitlabel(label); stmt.gen(label, b ); 

// save label a 

// label for stmt 

emit("goto L" + b ); 

Class Do  is  very  similar  to  class While. 

1) package  inter; 
2) import  symbols.*; 
3) public class Do extends Stmt •[ 
Expr expr;  Stmt stmt; 
4) 

//  File  Do.java 

980 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

public Do() { expr = null;  stmt = null;  } 
public void init(Stmt s, Expr x) •[ 

expr = x;  stmt = s; 
if( expr.type  != Type.Bool ) expr.error("boolean required in do"); 

> 
public void gen(int b,  int a)  { 

after = a; 
int label = newlabelO; 
stmt.gen(b,label); 
emitlabel(label); 
expr.jumping(b,0); 

// label for expr 

5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) 
14) 
15) 
16)  > 
17) > 

Class  S et  implements  assignments  with  an  identifer  on  the  left  side  and  an 
expression  on  the  right.  Most  of the  code  in  class  S et  is  for  constructing  a  node 
and  checking  types  (lines  5-13).  Function  gen  emits  a  three-address  instruction 
(lines  14-16). 

id = i;  expr = x; 
if ( check(id.type, expr.type) == null ) error("type error"); 

//  File  Set.Java 

public Id id;  public Expr expr; 
public Set(Id i,  Expr x)  { 

1) package inter; 
2) import lexer.*;  import symbols.*; 
3) public  class Set extends  Stmt { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13)  > 
14) 
15) 
16)  } 
17) > 

public void gen(int b,  int a)  { 

} 
public Type check(Type pi,  Type p2)  { 

if ( Type.numeric(pi) && Type.numeric(p2)  ) return p2; 
else if  ( pi == Type.Bool && p2 == Type.Bool ) return p2; 
else return null; 

emit( id.toStringO + " = " + expr.gen() .toStringO  ); 

Class  SetElem  implements  assignments  to  an  array  element: 

//  File  SetElem.java 

1) package inter; 
2) import lexer.*;  import symbols.*; 
3) public  class SetElem extends  Stmt { 
4) 
5) 
6) 

public Id array;  public Expr index;  public Expr expr; 
public SetElem(Access x, Expr y) {. 

array = x.array;  index = x.index;  expr = y; 

if ( check(x.type, expr.type) == null ) errorC'type error"); 

> 
public Type check(Type pi, Type p2) •{ 

if ( pi instanceof Array  || p2 instanceof Array ) return null; 

else if  ( pi == p2 ) return p2; 
else if ( Type.numeric(pi) && Type.numeric(p2) ) return p2; 
else return null; 

public void gen(int b,  int a) •{ 

String si = index.reduce().toStringO; 
String s2 = expr.reduce().toStringO; 

7) 
8) 
9) 

10) 

11) 
12) 
13) 
14)  } 
15) 
16) 
17) 

A.8. 

PARSER 

981 

emit (array. toStringO  + "  [ " + si + " ] = " + s2); 

18) 
19) 
20)  } 

> 

Class Seq  implements  a  sequence  of  statements.  The  tests  for  null  state 
ments  on  lines  6-7  are  for  avoiding  labels.  Note  t h at  no  code  is  generated  for 
the  null  statement, Stmt.Null,  since  method gen  in  class Stmt  does  nothing. 

//  File  Seq.java 

if  ( stmti == Stmt.Null ) stmt2.gen(b,  a ); 
else if ( stmt2 == Stmt.Null ) stmti.gen(b,  a ); 
else  { 

1) package inter; 
2) public  class  Seq extends  Stmt  { 
Stmt  stmti;  Stmt  stmt2; 
3) 
public Seq(Stmt  si,  Stmt s2)  { stmti = si;  stmt2 = s2;  > 
4) 
5) 
public void gen(int b,  int  a)  { 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) 
14) 
15) } 

int  label = newlabelO; 
stmt1.gen(b,label); 
emitlabel(label); 
stmt2.gen(label,a); 

} 

> 

A  break  statement  sends  control  out  of  an  enclosing  loop  or  switch  state 
ment.  Class Break  uses  field stmt  to  save  the  enclosing  statement  construct 
(the  parser  ensures  t h at Stmt .Enclosing  denotes  the  syntax-tree  node  for 
the  enclosing  construct).  The  code  for  a Break  object  is  a  j u mp  to  the  la 
bel stmt.after,  which  marks  the  instruction  immediately  after  the  code  for 
stmt. 

//  File  Break.java 

1) package inter; 
2) public  class  Break extends  Stmt  { 
3) 
4) 
5) 
6) 

Stmt  stmt; 
public Break()  { 

if( Stmt.Enclosing == null )  error("unenclosed break"); 
stmt  = Stmt.Enclosing; 

7) 
8) 
9) 
10) 
11) > 

> 
public void gen(int b,  int  a)  { 
emit( "goto L" + stmt.after); 

} 

A.  8  Parser 

The  parser  reads  a  stream  of  tokens  and  builds  a  syntax  tree  by  calling  the 
appropriate  constructor  functions  from  Sections  A.5-A.7.  T he  current  symbol 
table  is  maintained  as  in  the  translation  scheme  in  Fig.  2.38  in  Section  2.7. 

Package parser  contains  one  class, Parser: 

1) package parser; 
2) import  java.io.*;  import  lexer.*;  import  symbols.*;  import  inter.*; 

//  File  Parser.Java 

982 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

// lexical analyzer for this parser 
//  lookahead tagen 
//  current  or top symbol table 
//  storage  used for declarations 

private  Lexer lex; 
private  Token look; 
Env top = null; 
int  used  = 0; 
public Parser(Lexer  1)  throws  IOException {  lex =  1;  move();  } 
void move()  throws  IOException {  look = lex.scanQ;  } 
void error(String s)  { throw new Error("near line  "+lex.line+":  "+s);  > 
void match(int  t)  throws  IOException { 

3)  p u b l ic  c l a ss  P a r s er  { 
4) 
5) 
6) 
7) 
8) 
9) 
10) 
11) 
12) 
13) 
14) 

> 

if( look.tag == t ) m o v e Q; 
else error("syntax error"); 

Like  the  simple  expression  translator  in  Section  2.5,  class  P a r s er  has  a  pro 
cedure  for  each  nonterminal.  T he  procedures  are  based  on  a  g r a m m ar  formed 
by  removing  left  recursion  from  the  source-language  g r a m m ar  in  Section  A . l. 

Parsing  begins  with  a  call  to  procedure  program,  which  calls  b l o c k ()  (line 
16)  to  parse  the  input  stream  and  build  the  syntax  tree.  Lines  17-18  generate 
intermediate  code. 

15) 
16) 
17) 
18) 
19) 

public  void programQ  throws  IOException  {  // program ->  block 

Stmt  s  =  b l o c k O; 
int begin = s. n e w l a b e l O;  int after = s. n e w l a b e l ( ); 
s.emitlabel(begin);  s.gen(begin,  after);  s.emitlabel(after); 

} 

Symbol-table  handling  is  shown  explicitly  in  procedure  b l o c k .3  Variable 
t op  (declared  on  line  5)  holds  the  top  symbol  table;  variable  savedEnv  (line  21) 
is  a  link  to  the  previous  symbol  table. 

20) 
21) 
22) 
23) 
24) 
25) 

Stmt  b l o c kO  throws  IOException  { 

//  block  ->  { decls  stmts  } 

match('-C');  Env  savedEnv  = top;  top = new Env(top); 
decls();  Stmt s = stmts(); 
match('}');  top = savedEnv; 
return s; 

} 

Declarations  result  in  symbol-table  entries  for  identifiers  (see  line  36).  Al 
though  not  shown  here,  declarations  can  also  result  in  instructions  to  reserve 
storage  for  the  identifiers  at  run  time. 

26) 
27) 
28) 
29) 
30) 
31) 
32) 
33) 
34) 
35) 

void decls()  throws  IOException { 

while(  look.tag == Tag.BASIC  )  {  // D -> type  ID  ; 

Type p = type(); Token tok = look; match(Tag.ID) ; matchC;'); 
Id  id = new  Id((Word)tok,  p,  used); 
top.put( tok,  id ); 
used = used + p.width; 

} 

} 
Type  type()  throws  IOException { 

Type  p =  (Type)look; 

//  expect  look.tag == Tag.BASIC 

3An  attractive  alternative  is  to  add  methods push  and pop  to  class Env,  with  the  current 

table  accessible  through  a  static  variable Env.top 

A.8. 

PARSER 

983 

match(Tag.BASIC); 
if( look.tag != '['  ) return p; // T -> basic 
else return dims(p); 

//  return array type 

Type dims(Type p)  throws  IOException { 

match('[');  Token tok = look;  match(Tag.NUM);  match(']'); 
if(  look.tag  = = ' [ ') 
p  =  dims(p); 
return new Array(((Mum)tok).value,  p ); 

45)  } 

Procedure  stmt  has  a  switch  statement  with  cases  corresponding  to  the 
productions  for  nonterminal  Stmt.  Each  case  builds  a  node  for  a  construct, 
using  the  constructor  functions  discussed  in  Section  A.7.  The  nodes  for  while 
and  do  statements  are  constructed  when  the  parser  sees  the  opening  keyword. 
T he  nodes  are  constructed  before  the  statement  is  parsed  to  allow  any  enclosed 
break  statement  to  point  back  to  its  enclosing  loop.  Nested  loops  are  handled 
by  using  variable Stmt .Enclosing  in  class Stmt  and savedStmt  (declared  on 
line  52)  to  maintain  the  current  enclosing  loop. 

Stmt  stmts()  throws  IOException { 

if ( look.tag == ' }' ) return Stmt.Null; 
else  return new S e q( s t m t ( ),  s t m t s O ); 

Stmt  stmt()  throws  IOException { 

Expr x;  Stmt s, si,  s2; 
Stmt  savedStmt; 
switch(  look.tag )  { 
case 

' ;'  : 
move(); 
return Stmt.Null; 

//  save enclosing loop for breaks 

case Tag.IF: 

match(Tag.IF); m a t c h( ' O );  x = boolQ; match(')'); 
si  =  stmt(); 
if( look.tag  != Tag.ELSE ) return new If(x,  si); 
match(Tag.ELSE); 
s2  =  stmt(); 
return new Else(x,  si, s2); 

case Tag.WHILE: 

While whilenode = new While(); 
savedStmt  = Stmt.Enclosing;  Stmt.Enclosing = whilenode; 
match(Tag.WHILE);  m a t c h( ' C );  x = boolQ; match(')'); 
si  =  s t m t ( ); 
whilenode.init(x, si); 
Stmt.Enclosing = savedStmt;  // reset  Stmt.Enclosing 
return whilenode; 

case Tag.DO: 

Do donode = new Do(); 
savedStmt  = Stmt.Enclosing;  Stmt.Enclosing = donode; 
match(Tag.DO); 
si  =  s t m t O; 
match(Tag. WHILE);  m a t c h ( ' C );  x = bool();  m a t c h ( ' ) ' );  m a t c h C ; ' ); 

donode.init(si,  x ); 

Stmt.Enclosing = savedStmt;  // reset  Stmt.Enclosing 

return donode; 

36) 
37) 
38) 
39)  } 
40) 
41) 
42) 
43) 
44) 

46) 
47) 
48) 
49)  } 
50) 
51) 
52) 
53) 
54) 
55) 
56) 
57) 
58) 
59) 
60) 
61) 
62) 
63) 
64) 
65) 
66) 
67) 
68) 
69) 
70) 
71) 
72) 
73) 
74) 
75) 
76) 
77) 

78) 

79) 

80) 

984 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

81) 
82) 
83) 
84) 
85) 
86) 
87) 
88) 

case Tag.BREAK: 

match(Tag.BREAK);  match(';'); 
return new BreakO ; 

case ' { ': 

return blockO; 

default: 

return assignO; 

> 

For  convenience,  the  code  for  assignments  appears  in  an  auxiliary  procedure, 

a s s i g n .' 

90) 
91) 
92) 
93) 
94) 
95) 
96) 

Stmt  a s s i g nO throws IOException •£ 
Stmt  stmt;  Token t = look; 
match(Tag.ID); 
Id  id = top.get(t); 
i f(  id == null  )  error(t.toStringO  +  "  undeclared"); 
if(  look.tag ==  > = '  )  { 

//  S ->  id = E  ; 

move();  stmt  = new Set ( i d,  b o o l O ); 

97) 
98) 
99) 
100) 
101) 
102) 
103) 
104)  } 

} 
else  { 

//  S -> L = E  ; 

Access x = offset(id); 
match('=');  stmt = new SetElem(x, bool()); 

> 
matchC';'); 
return stmt; 

T he  parsing  of  arithmetic  and  boolean  expressions  is  similar.  In  each  case, 
an  appropriate  syntax-tree  node  is  created.  Code  generation  for  the  two  is 
different,  as  discussed  in  Sections  A.5-A.6. 

105) 
106) 
107) 

108) 

109) 

110) 

Expr  b o o lO  throws  IOException { 

Expr x =  j o i n O; 
while(  look.tag == Tag.OR )  { 

Token tok = look;  move();  x = new 0r(tok,  x,  j o i n O ); 

} 

return x; 

111)  > 
112) 
113) 
114) 

115) 

116) 

117) 

118)  > 

Expr  j o i nO  throws  IOException { 

Expr  x =  e q u a l i t y O; 
while( look.tag == Tag.AND )  { 

Token tok = look;  move();  x = new And(tok,  x,  e q u a l i t y O ); 

} 

return x; 

119) 

Expr  e q u a l i t yO  throws  IOException  { 

120) 

121) 

122) 

123) 

124) 

125)  } 

Expr x = rel(); 

while( look.tag == Tag.EQ  II  look.tag == Tag.NE ) { 

Token tok = look;  moveO;  x = new Rel(tok,  x,  rel()); 

} 

return x; 

126) 

Expr rel() throws IOException { 

127) 

Expr x = expr(); 

A.8. 

PARSER 

985 

128) 
129) 
130) 
131) 
132) 
133) 
134) 
135) 
136) 
137) 
138) 
139) 
140) 
141) 
142) 
143) 
144) 
145) 
146) 
147) 
148) 
149) 
150) 
151) 
152) 
153) 
154) 
155) 
156) 
157) 

switch( 
case 

l o o k . t ag  )  { 

' < ':  case  Tag.LE:  case  Tag.GE:  case 

' > ': 

Token  tok  =  look;  move(); 

r e t u rn  new  R e l ( t o k,  x,  e x p r O ); 

d e f a u l t: 

r e t u rn  x; 

> 

> 
Expr  exprQ 

throws  IOException  { 

Expr  x  =  t e r m ( ); 
while(  l o o k . t ag  ==  ' + '  I  I  l o o k . t ag  ==  ' -'  )  { 

Token  tok  =  look;  move(); 

x  =  new  A r i t h ( t o k,  x,  t e r m O ); 

> 
r e t u rn  x; 

} 
Expr  termO 

throws  IOException  { 

Expr  x  =  u n a r y ( ); 
w h i l e ( l o o k . t ag  == 

' *' 

|| 

l o o k . t ag  == 

' /'  )  { 

Token  tok  =  look;  move(); 

x  =  new  A r i t h ( t o k,  x,  u n a r y O ); 

} 
r e t u rn  x; 

> 
Expr  unaryO 

i f(  l o o k . t ag  == 

throws  IOException  { 
' -'  )  { 

move(); 

r e t u rn  new  Unary (Word, minus,  u n a r y O ); 

} 
e l se  i f(  l o o k . t ag  == 

' \'  )  { 

Token  tok  =  look;  moveQ; 

r e t u rn  new  Mot(tok,  u n a r y O ); 

> 
e l se  r e t u rn  f a c t o r ( ); 

} 

T he  rest  of  t he  code  in  t he  parser  deals  with  "factors"  in  expressions.  T he 
auxiliary  procedure  o f f s et  generates  code  for  array  address  calculations,  as 
discussed  in  Section  6.4.3. 

158) 
159) 
160) 
161) 
162) 
163) 
164) 
165) 
166) 
167) 
168) 
169) 
170) 
171) 
172) 
173) 
174) 
175) 
176) 
177) 
178) 

Expr  f a c t o r () 

throws  IOException  { 

Expr  x  =  n u l l; 
switch(  l o o k . t ag  )  { 
case 

'  ( ': 

move();  x  =  b o o l ( );  m a t c h ( ' ) ' ); 
r e t u rn  x; 
case  Tag.NUM: 

x  =  new  Constant(look,  T y p e . I n t ); 

move();  r e t u rn  x; 

case  Tag.REAL: 

x  =  new  Constant(look,  Type.Float);  move();  r e t u rn  x; 

case  Tag.TRUE: 

x  =  Constant.True; 

case  Tag.FALSE: 

x  =  Constant.False; 

d e f a u l t: 

e r r o r ( " s y n t ax  e r r o r " ); 
r e t u rn  x; 
case  Tag.ID: 

move();  r e t u rn  x; 

move();  r e t u rn  x; 

S t r i ng  s  =  l o o k . t o S t r i n gO  ; 
Id  id  =  t o p . g e t ( l o o k ); 
i f( 

id  ==  n u ll  )  e r r o r ( l o o k . t o S t r i ng  ;()  +  "  undeclared"); 

986 

APPENDIX  A. 

A  COMPLETE  FRONT  END 

179) 
180) 
181) 
182) 
183) 
184) 
185) 
186) 
187) 
188) 
189) 
190) 
191) 
192) 
193) 
194) 
195) 
196) 
197) 
198) 
199) 
200) 
201) 
202)  } 

moveQ; 
if( look.tag != '[' ) return id; 
else return offset(id); 

} 

} 
Access offset(Id a) throws IOException {  // I ->  [E]  I  [E]  I 

Expr i;  Expr w;  Expr tl,  t 2;  Expr loc;  // inherit  id 
Type type = a.type; 
m a t c h C C );  i = boolO;  match(']'); 
type =  ((Array)type).of; 
w = new Constant(type.width); 
tl = new Arith(new TokenO*'), i, w ); 
loc = tl; 
while(  look.tag = = ' [ ' ){ 

// multi-dimensional I ->  [ E ]  I 

// first  index,  I ->  [ E ] 

match('['); i = boolO; match(']'); 
type =  ((Array)type).of; 
w = new Constant(type.width); 
tl = new Arith(new TokenO*'), i, w ); 
t2 = new Arith(new Token('+'),  loc, tl); 
loc  =  t 2; 

} 
return new Access(a, loc, type); 

} 

A.9  Creating  the  Front  End 

T he  code  for  the  packages  appears  in  five  directories:  main, lexer, symbol, 
parser,  and inter.  T he  commands  for  creating  the  compiler  vary  from  system 
to  system.  The  following  are  from  a  UNIX  implementation: 

javac  lexer/*.Java 
javac  symbols/*.Java 
javac  inter/*.Java 
javac parser/*.Java 
javac main/*.Java 

T he javac  command  creates  . class  files  for  each  class.  T he  translator  can 
then  be  exercised  by  typing j ava main. Main followed  by  the  source  program  to 
be  translated;  e.g.,  the  contents  of  file test 

//  File  test 

int  i;  int j;  float v;  float x;  float[100]  a; 
while( true ) { 

do i = i+1; while( a[i] < v ); 
do j = j- 1; while( a[j] > v ); 
if( i >= j ) break; 
x = a[i]; a[i] = a[j] ; a[j] = x; 

> 

1)  { 
2) 
3) 
4) 
5) 
6) 
7) 
8) 
9 )> 

On  this  input,  the  front  end  produces 

A.9. 

CREATING  THE  FRONT  END 

1)  L1:L3:  i = i + 1 
tl = i * 8 
2)  L5: 
t2 = a  [ tl ] 
3) 
if t2  <  v goto 
4) 
5)  L4: 
j = j - 1 
t3 = j  * 8 
6)  L7: 
t4 = a  [ t3 ] 
7) 
if t4  >  v goto 
8) 
9)  L6: 
iffalse i >= j 
10)  L9: 
11)  L8: 
12) 
13)  L10: 
14) 
15) 
16) 
17)  Lll: 
18) 
19) 
20)  L2: 

goto  L2 
t5 = i * 8 
x  = a  [ t5 ] 
t6 = i * 8 
t7 = j  * 8 
t8 = a  [ t7 ] 
a [ t6 ]  = t8 
t9 = j  * 8 
a  [ t9  ]  =  x 
goto LI 

Try  it. 

Appendix  B 

Finding  Linearly 
Independent  Solutions 

A l g o r i t hm  B . I:  Finds  a  maximal  set  of  linearly  independent  solutions  for 
Ax  >  0,  and  expresses  them  as  rows  of  matrix  B. 

I N P U T:  An  mx  n  matrix  A. 

O U T P U T:  A  matrix  B  of  linearly  independent  solutions  to  Ax  >  0. 

M E T H O D:  T he  algorithm  is  shown  in  pseudocode  below.  Note  t h at  X[y]  de 
notes  t he  yth.  row  of  matrix  X,  X[y  :  z]  denotes  rows  y  through  z  of  matrix  X, 
and  X[y  :  z][u  :  v]  denotes  the  rectangle  of  matrix  X  in  rows  y  through  z  and 
columns  u  through  v. 

• 

989 

990 

APPENDIX  B. 

FINDING  LINEARLY  INDEPENDENT  SOLUTIONS 

M  =  AT; 
ro  =  1; 
Co  =  1; 
B  —  Inxn',  /*  an  n-by-n  identity  matrix  */ 

w h i le  (  t r ue  )  { 

/*  1.  Make  M[r0  :  r'  -  l][c0  :  d  -  1]  into  a  diagonal  matrix  with 

positive  diagonal  entries  and  M[r'  :  n][co  :  m]  =  0. 
M[r'  :  n]  are  solutions.  */ 

r'  =  r0; 
c  =  c0; 
w h i le  (  there  exists  M[r][c]  ^  0  such  t h at 

r  —  r'  and  c —  d  are  both  >  0  )  { 

Move  pivot  M[r][c]  to  M[r'][c']  by  row  and  column 

interchange; 

Interchange  row  r  with  row  r'  in  B; 
if  (  M[r'][d]  <  0  )  { 

M[r']  =  -1  * M [ r ' ]; 
B[r']  = 

-l*B[r']; 

} 
for  (  row;  =  ro  to  n  )  { 

if  (  row  /  r'  and  Mjrowjfc']  / 0{ 
-{M[row][d]/M[r'][d]); 

u 
M[row]  =  M[row)  +  u  *  M [ r ' ]; 
5[row]  =  5 [row]  +  u  *  B[r']; 

= 

} 

/*  2.  Find  a  solution  besides  M[r'  :  n).  It  must  be  a 

nonnegative  combination  of  M [ r0  :  r'  -  1][CQ  :  m]  */ 

Find  kro,...  ,  A v -i  >  0  such  t h at 

Av0M[r0][c'  :  m]  +  •  •  •  +  A y - i M [ r'  -  l][c'  :  m]  >  0; 

if  ( t h e re  exists  a  nontrivial  solution,  say  A;r  >  0  )  { 
M[r]  =  kroM[r0]  +.•••  +  A v- i M [ r'  -  1]; 
false; 
NoMoreSoln  = 

} 

e l se  /*  M [ r'  :  n]  are  the  only  solutions  */ 

NoMoreSoln  — 

true; 

/*  3.  Make  M [ r0  :  rn  -  l][c0  :  m]  >  0  */ 
if  (  NoMoreSoln  )  {  /*  Move  solutions  M [ r'  :  n]  to  M [ r0  :  rn 

for  (  r  =  r'  to  n  ) 

Interchange  rows  r  and  ro  +  r  —  r'  in  M  and  B; 

rn  =  r0  +  n  -  r'  +  1; 

e l se  {  /*  Use  row  addition  to  find  more  solutions  */ 

rn  =  n  +  1; 
for  (  col  =  c'  to  m  ) 

if  (  there  exists  Mfrowjfco/]  <  0  such  t h at  row  >  ro 

if  (  there  exists  M[r][coZ]  >  0  such  t h at  r  >  ro  ) 

for  (  row  —  ro  to  rn  —  1  ) 

if  (  M[row][col]  <  0  )  { 

\(-M[row][col]/M[r][coV])]] 

u  = 
M[row]  =  M[row]  +u*M[r); 
B[row]  =  B[row]  +  u  *  B[r]; 

} 

e l se 

for  (  row  =  rn  —  1  to  ro  step  -1  ) 
if  (  M[row][col]  <  0  { 

Interchange  M[row]  with  M [ rn]; 
Interchange  5 [row]  with  i ? [ rn]; 

} 

} 

/*  4.  Make  M [ r0  :  rn  -  1][1  :  c0  -  1]  >  0  */ 
for  (  row  —  ro  to  rn  -  1  ) 

for  (  col  =  1  to  c0  —  1  ) 

if  (  M[row][col]  <  0  { 

Pick  an  r  such  t h at  M[r][coZ]  >  0  and  r  <  ro; 
u  =  r(-M[ro«;]M]/^MM])l; 
M[rou;]  =  M[row]  +  w  *  M [ r ]; 
B[row]  =  B[row]  +u*  B[r]] 

} 

APPENDIX  B. 

FINDING 

LINEARLY 

INDEPENDENT 

SOLUTIONS 

/*  5.  If  necessary,  repeat  with  rows  M[rn  :  n]  */ 
if  (  (NoMoreSoln  or  rn  >  n  or  rn  ==  ro)  { 

Remove  rows  rn  to  n  from  B; 
r e t u rn  B; 

} 
e l se  { 

cn  =  m  +  1; 
for  (  col  =  m  to  1  step  -1  ) 

if  (  there  is  no  M[r][co/]  >  0  such  t h at  r  <  rn  { 

=  cn 

1; 

Cn
Interchange  column  col  with  cn  in  M; 

} 

 
Index 

A 

Abstract  syntax  tree 
See  Syntax  tree 
Abu-Sufah,  W.  900 
Acceptance  149 
Accepting  state 

See  Pinal  state 
Access  link  434,  445-449 
Action  58-59,  249,  327 
Activation  record  433-452 
Activation  tree  430-433 
Actual  parameter  33,  434,  942 
Acyclic  call  string  910 
Acyclic  p a th  667 
Acyclic  test  821-822 
Ada  391 

Address  364,  374 
Address  descriptor  543,  545-547 
Address  space  427 
Advancing  edge  661 
Affine array access  781,  801-804,815¬ 

826 

Affine  expression  687,  770 
Affine  partitioning  781 
Affine  space  partition  830-838 
Affine  transformation  778-782,  846¬ 

851 

Aho,  A.  V.  189-190,  301,  579-580 
Aho-Corasick  algorithm  138-140 
Algebraic  identities  536,  552 
Alias  35,  713,  903,  917,  933 
Alignment  374,  428 
Allen,  F.  E.  704,  899-900,  962 
Allen,  R.  900 
Allocation,  of  memory  453 

993 

Alpha  703 
Alphabet  117 
Ambiguous  g r a m m ar  47,  203-204, 

210-212, 255, 278-283,291¬ 
294 

Amdahl's  law  774 
Analysis  4 
Ancestor  46 
Andersen,  L.  962 
Annotated  parse  tree  54 
Anticipated  expression  645-648,653 
Antidependence  711,  816 
Antisymmetry  619 
Antlr  300,  302 
Architecture  19-22 
Arithmetic  expression  49-50,  68-69, 
378-381,  971-974 
Array  373-375,  381-384,  537-539, 
541,584,  712-713,770,920 

See  also  Affine  array  access 

Array  contraction  884-887 
ASCII  117 
Assembler  3 
Assembly  language  13,  508 
Associativity 48,  122,  279-281, 293, 

619 

Atom  921 
Attribute  54,  112 

See  also  Inherited  attribute,  Main 
attribute,  Synthesized  at 
tribute 
Attribute  g r a m m ar  306 
Augmented  grammar  243 
Auslander,  M.  A.  580 
Auto-increment  739 
A u t o m a t on  147 

994 

INDEX 

See  also  Deterministic  finite  au 

Block  structure 

t o m a t o n,  LR(0)  automaton, 
Nondeterministic  finite  au 
tomaton 

See  Static  scope 

Blocking  770-771,  785-787,877-880, 

888 

Available  expression  610-615,  648¬ 

B NF 

649,  653 
Avots,  D.  962-963 

B 

Back  edge  662,  664-665 
Back  end  4,  357 
Backpatching  410-417 
Backus,  J.  W.  300-301 
Backus-Naur  form 
See  B NF 

Backward  flow  610,  615,  618,  627, 

669 
Baker,  H.  G.  J r.  502 
Baker's  algorithm  475-476,  482 
Ball,  T.  962 
Banerjee,  U.  900 
Banning,  J.  P.  962 
Barth,  J.  M.  962 
Base  address  381 
Base  register  762 
Basic  block  525-541,  597,  600-601, 

721-726 

Basic  type  371 
Bauer,  F.  L.  354-355 
BDD  951-958 
B d d b d db  961 
Bergin,  T.  J.  38 
Berndl,  M.  961-962 
Bernstein,  D.  766-767 
Best-fit  458 
Big-oh  159 
Binary  alphabet  117 
Binary  decision  diagram 

See  BDD 

Binary  translation  22 
Binning,  of  chunks  458 
Birman,  A.  301 
Bison  300 
Block  29,  86-87,  95 

See  also  Basic  block 

See  Context-free  g r a m m ar 

Body  43,  197,  923 
Body  region  673 
Boolean  expression  399-400,  403¬ 

409,  411-413,  974-977 

Bottom  element  619,  622 
Bottpm-up  parser  233-240 

See  also  LR  parser,  Shift-reduce 

parser 
Boundary  condition  615 
Boundary  tag  459 
Bounds  checking  19,  24,  920-921 
Bounimova,  E.  962 
Branch 

See  J u mp 

Branch-and-bound  824-825 
Break-statement  416-417 
Brooker,  R.  A.  354 
Bryant,  R.  E.  961-962 
Buffer  115-117 
Buffer  overflow  918,  920-921 
Burke,  M.  900 
Bus  772-773 
Bush,  W.  R.  962-963 
Bytecode  2 

C 

C  13,  18,  25,  28-29,  381,  498,  903, 

934 

Cache  20,  454-455,  457,  772,  783¬ 

785 
Cache  interference  788 
Cadar,  C.  963 
Call  365,423-424,467,  518-522,539, 

541 

Call  graph  904-906,  943-944 
Call  site  904,  950 
Call  string  908-910,  946-949 
Callahan,  D.  961,  963 
Call-by-name  35 

INDEX 

995 

Call-by-reference  34 
Call-by-value  34 
Calling  sequence  436-438 
Canonical  derivation 

See  Rightmost  derivation 
Canonical  LR  parser  259,  265-266, 

283 

Canonical  LR(1)  set  of  items  260¬ 

264 

Canonical  LR(0)  set  of  items  243, 

247 
Cantor,  D.  C.  300-301 
Carbin,  M.  963 
Case  sensitivity  125 
C FG 

See  G r a m m ar 
Chaitin,  G.  J.  580 
Chandra,  A.  K.  580 
Character  class  123,  126 
Charles,  P.  900 
Chelf,  B.  963 
Chen,  S.  766-767,  899,  901 
Cheney,  C.  J.  502-503 
Cheney's  algorithm  479-482 
Cheong,  G.  I.  901 
Child  46 
Chomsky,  N.  300-301 
Chomsky  Normal  Form  232,  300 
Chou,  A.  963 
Chow,  F.  579-580 
Chunk  457-459 
Church,  A.  502-503 
Circular  dependency  307 
CISC  21,  507-508 
Class  33,  376 
Class  variable  25-26 
Clock  708 
Cloning  910-911 
Closure 119,  121-122, 243-245, 261¬ 

262 

See  also  Positive  closure 
Closure,  of  transfer  functions  679 
Coalescing,  of  chunks  459-460 
Cocke,  J.  301,  579-580,  704,  900 

Cocke-Younger-Kasami  algorithm  232, 

301 

Code generation 10-11,  505-581, 707¬ 

767 

See  also  Scheduling 

Code  motion  592 

See  also  Downward  code  mo 

tion,  Loop-invariant  expres 
sion,  Partial  redundancy  elim 
ination,  Upward  code  mo 
tion 

Code  optimization  5 , 1 0 , 1 5 - 1 9,  368, 
583-705,  769-963 

Code  scheduling 

See  Scheduling 

Coercion  99,  388-389 
Coffman,  E.  G.  900-901 
Coherent  cache  protocol  772-773 
Collins,  G.  E.  503 
Coloring  556-557 
Column-major  order  382,  785 
Comment  77 
Common  subexpression  533-535,  588¬ 
590,  611,  639-641 
Communication  828,  881-882,  894 
Commutativity  122,  619 
Compile  time  25 
Complex  instruction-set  computer 

See  CISC 

Composition  624,  678,  693 
Computer  architecture 

See  Architecture 

Concatenation  119,  121-122 
Concurrent  garbage  collection  495¬ 

497 

Conditional  j u mp  513,  527 
Configuration  249 
Conflict  144,  565 

See  also  Reduce-reduce  conflict, 
Shift-reduce  conflict 

Conservative  data-flow  analysis  603 
Constant  78-79 
Constant  folding  536,  632-637 
Constant  propagation 

See  Constant  folding 

996 

Constraint 

See  Control-dependence  constraint, 
D a ta  dependence,  Resource 
constraint 

Context  sensitivity  906-908,  945-951 
Context-free  grammar 
See  G r a m m ar 

Context-free  language  200,  215-216 
Context-sensitive  analysis  906-907, 

945-950 
Contiguous  evauation  574 
Continue-statement  416-417 
Control  equivalence  728 
Control  flow  399-409,  413-417,  525 
Control  link  434 
Control-dependence  constraint  710, 

716-717 

Control-flow  equation  600,  605 
Convex  polyhedron  789-790,  795¬ 

796 
Cook,  B.  962 
Cooper,  K.  D.  580,  963 
Copy  propagation  590-591 
Copy  statement  544,  937 
Copying  garbage  collector  478-482, 

488,  497-498 

Corasick,  M.  J.  189-190 
Cousot,  R  704 
Cousot,  R.  704 
C ++  13,  18,  34,  498 
Critical  cycle  758 
Critical  edge  643 
Critical  p a th  725 
Cross  edge  662 
C UP  300,  302 
Cutset  645 
Cyclic  garbage  488 
CYK  algorithm 

See  Cocke-Younger-Kasami  al 

gorithm 

Cytron,  R.  704,  900 

D 

INDEX 

Dalton,  M.  962 
Dangling  else  210-212,  281-283 
Dangling  pointer  461 
Dantzig,  G.  900 
Das,  M.  961,  963 
D a ta  abstraction  18 
D a ta dependence  711-715,  732,  747¬ 
749,  771,781-782,804-805, 
815-826 

See  also  Antidependence,  Out 
put  dependence,  True  de 
pendence 

D a ta  locality  891-892 
See  also  Locality 

D a ta  reuse  804-815,  887-888 
D a ta  space  779-780 
Data-dependence  graph  722-723 
Data-flow  analysis  18,  23,  597-705, 

921 

Data-flow  analysis  framework  618 
Datalog  921-933 
Datalog  program  923 
Davidson,  E.  S.  767 
Dead  code  533,  535,  550,  591-592 
Dead  state  172,  183 
Dead  variable  608 
Deallocation,  of  memory  453,  460¬ 

463 

Declaration  32,  373,  376 
Declarative  language  13 
Decode  708 
Def  609 
Definition  32 
Definition,  of  a  variable  601 
Dependency  graph  310-312 
Depth,  of  a  flow  graph  665 
Depth-first  order  660 
Depth-first  search  57 
Depth-first  spanning  tree  660 
Dereferencing  461 
DeRemer,  F.  300-301 
Derivation  44-46,  199-202 

See  also  Leftmost  derivation,  Right 

DAG  359-362,  533-541,  951 
Dain,  J.  300-301 

most  derivation 

Descendant  46 

INDEX 

997 

Deterministic  finite  a u t o m a t on  149¬ 
156,164-166,170-186,  206 

DFA 

See  Deterministic  finite  automa 

ton 

Dijkstra,  E.  W.  502-503 
Diophantine  equation  818-820 
Directed  acyclic  graph 

See  DAG 

Direct-mapped  cache  457,  788 
Display  449-451 
Distributive  framework  625,  635-636 
Distributivity  122 
Do-across  loop  743-745 
Do-all  loop  738 
Domain,  of a  data-flow  analysis  599, 

615 

Domain,  of  a  relation  954 
Dominator  656-659,  672,  728 
Dominator  tree  657 
Donnelly,  C.  301 
Downward  code  motion  731-732 
Dumitran,  D.  963 
Dynamic  access  816 
Dynamic  loading  944 
Dynamic  policy  25 
Dynamic  programming  573-577 

See  also  Cocke-Younger-Kasami 

algorithm 
Dynamic  RAM  456 
Dynamic  scheduler  719,  737 
Dynamic  scope  31-33 
Dynamic  storage  429 

See  also  Heap,  Run-time  stack 

E 

Earley,  J.  301 
Earliest  expression  649-650,  654 
Eaves,  B.  C.  900 
E DB 

See  Extensional  database  pred 

icate 

Edge 

See  Advancing  edge,  Back edge, 
Critical  edge,  Cross  edge, 

Retreating  edge 

Emami,  M.  961,  963 
E m p ty  string  44,  118,  121 
Engler,  D.  963 
Entry  node  531,  605 
Environment  26-28 
Epilog  742 

€ 

See  E m p ty  string 

e-free  grammar  232 
e-production  63,  65-66 
Eqn  331 
Equivalence-based  analysis  935 
Error  correction  113-114,  192-196, 

228-231 

Error  production  196 
Error  recovery  283-284,  295-297 
Ershov,  A.  P  426,  579-580,  705 
Ershov  number  567-572 
Euclidean  algorithm  820 
Execution  p a th  597,  628 
Exit  block  677 
Exit  node  605 
Expression  94,  9 6 - 9 7 , 1 0 1 - 1 0 5,  359, 

568-572 

See  also  Arithmetic  expression, 
Boolean  expression,  Infix 
expression,  Postfix  expres 
sion,  Prefix expression,  Reg 
ular  expression,  T y pe  ex 
pression 

Extensional  database  predicate  924 

F 

Fahndrich,  M.  961,  963 
Fall-through  code  406 
Farkas'  lemma  872-875 
Feautrier,  P.  900 
Feldman,  S.  I.  426 
Fenichel,  R.  R.  502-503 
Ferrante,  J.  704,  900 
Fetch  708 
Field  377,  584,  935 
Field  load  937 
Field  store  937 

998 

INDEX 

Fifth-generation  language  13 
Final  state  130-131,  147,  205 
Finite  automaton 

See  Automaton 

F I R ST  220-222 
First-fit  458 
First-generation  language  13 
Firstpos  175-177 
Fischer,  C.  N.  580 
Fisher,  J.  A.  766-767 
Fission  848,  850,  854 
Fixedpoint 

See  Maximum  fixedpoint 

Flex  189-190 
Floating  garbage  484 
Flow  graph  529-531 

See  also  Reducible  flow  graph, 

Super  control-flow  graph 

Flow  sensitivity  933,  936-937 
Floyd,  R.  W.  300-301 
F O L L OW  220-222 
Followpos  177-179 
Formal  parameter  33,  942 
Fortran  113,  382,  779,  886 
Fortran  H  703 

Forward  flow  615,  618,  627,  668 
Fourier-Motzkin  algorithm  796-797 
Fourth-generation  language  13 
Fragmentation  457-460 
Framework 

See  Data-flow  analysis  frame 
work,  Distributive  frame 
work,  Monotone  framework 

Fraser,  C.  W.  580 
Free  chunk  457 
Free  list  459-460,  471 
Free  state  473 
Frege,  G.  502-503 
Front  end  4,  4 0 - 4 1,  357,  986 
Frontier 

See  Yield 
Full  redundancy  645 
Fully  permutable  loops  861,  864¬ 

867,  875-876 

Fully  ranked  matrix  808 

Function  29 

See  also  Procedure 

Function  call 
See  Call 

Function  type  371,  423 
Functional  language  443 
Fusion  848,  850 

G 

G a n a p a t h i,  M.  579-580 
Gao,  G.  902 
Garbage  collection  25,  430,  463-499 

See  also Mark-and-compact,  Mark-

and-sweep,  Short-pause  garbage 
collection 

G CD  818-820 
Gear,  C.  W.  705 
Gen  603,  611 
Generational  garbage  collection  483, 

488-489 
Gen-kill  form  603 
Geschke,  C.  M.  705 
Ghiya,  R.  961,  963 
Gibson,  R.  G.  38 
Glaeser,  C.  D.  767 
Glanville,  R.  S.  579-580 
Global  code  optimization 

See  Code  optimization 

Global  variable  442 
G NU  38,  426 
Gosling,  J.  426 
G O TO  246,  249,  261 
Graham,  S.  L.  579-580 
G r a m m ar  42-50,  197-199,  204-205 
See  also  Ambiguous  grammar, 
Augmented  grammar 

G r a m m ar  symbol  199 
Granularity  917 
Granularity,  of  parallelism  773-775 
G r a ph 

See  Call  graph,  DAG,  Data-de 

pendence  graph,  Dependency 
graph,  Flow graph,  Program-
dependence  graph 

Graph  coloring 

INDEX 

See  Coloring 

Greatest  common  divisor 

See  G CD 

Greatest  lower  bound  620,  622 
Gross,  T.  R.  766-767 
Ground  a t om  921 
Group  reuse  806,  811-813 
Grune,  D.  302 
G u p t a,  A.  900-901 

H 

Hallem,  S.  963 
Halstead,  M.  H.  426 
Handle  235-236 
Hanson,  D.  R.  580 
Hardware  register  renaming  714 
Hardware  synthesis  22 
Head  42,  197,  923 
Header  665,  672 
Heap  428-430,  452-463,  518,  935 
Hecht,  M.  S.  705 
Height,  of  a  semilattice  623,  626, 

628 
Heintze,  N.  961,  963 
Hendren,  L.  J.  961-963 
Hennessy,  J.  L.  38,  579-580,  766¬ 

767,  899,  901 

Hewitt,  C.  502-503 
Hierarchical  reduction  761-762 
Hierarchical  time  857-859 
Higher-order  function  444 
Hoare,  C.  A.  R.  302 
Hobbs,  S.  O.  705 
Hole  457 
Hopcroft,  J.  E.  189-190,  302 
Hopkins,  M.  E.  580 
Hudson,  R.  L.  502-503 
Hudson,  S.  E.  302 
Huffman,  D.  A.  189-190 
Huskey,  H.  D.  426 

I 

IDB 

See  Intensional  database  pred 

icate 

999 

Ideal  solution,  to  a  data-flow  prob 

lem  628-630 
Idempotence  122,  619 
Identifier  28,  79-80 
Identity  function  624 
If-statement  401 
Immediate  dominator  657-658 
Imperative  language  13 
Inclusion-based  analysis  935 
Increment  instruction  509 
Incremental  evaluation  928-930 
Incremental  garbage  collection  483¬ 

487 
Incremental  translation 

See  On-the-fly  generation 
Independent  variables  test  820-821 
Index  365 
Indexed  address  513 
Indirect  address  513 
Indirect  triples  368-369 
Induction  variable  592-596,  687-688 
Infix  expression  40,  52-53 
Ingerman,  P.  Z.  302 
Inheritance  18 
Inherited  a t t r i b u te  55,  304-305,  307 
Initial  state 

See  Start  state 

Initialization  615 
Initiation  interval  745 
Inlining  903-904,  914 
Input  buffering 
See  Buffer 

Instruction  pipeline  708-709 

See  also  Software  pipelining 
Integer  linear  programming  817-825 
Intensional  database  predicate  924 
Interleaving  887-890 
Intermediate  code  9,  91-105,  357¬ 
426,  507,  971-981 

Interpreter  2 
Interprocedural  analysis  713,  903¬ 

964 
Interrupt  526 
Intersection  612-613,  615,  620,  650 
Intraprocedural  analysis  903 

1000 

Irons,  E.  T.  354 
Item  242-243 

See  also  Kernel item,  Set  of items, 

Valid  item 

Iteration  space  779-780,  788-799 
Iterative  data-flow  algorithm  605¬ 

607,  610,  614,  626-628 

J 

Jacobs,  C.  J.  H.  302 
Java  2,  13,  18-19,  25,  34,  76,  381, 

903,  934,  944 
Java  virtual  machine  507-508 
Jazayeri,  M.  354 
JFlex  189-190 
Johnson,  R.  K.  705 
Johnson,  S.  C.  300-302,  355,  426, 
502-503,  579-580 

Join  621,  955 
J u mp  513,  527,  551-552 
Jumping  code  408,  974-977 
Just-in-time  compilation  508 
J VM 

See  Java  virtual  machine 

K 

Kam,  J.  B.  705 
Kasami,  T.  301-302,  705 
Kennedy,  K.  899-900,  963 
Kernel  777 
Kernel  item  245,  272-273 
Kernighan,  B.  W.  189-190 
Keyword  5 0 - 5 1,  79-80,  132-133 
Kill  601,  603,  611 
Killdall,  G.  704-705 
Kleene  closure 

See  Closure 
Kleene,  S.  C.  189-190 
Knoop,  J.  705 
Knuth,  D.  E.  189-190,300,  302,  354¬ 

355,  502-503 

Knuth-Morris-Pratt  algorithm  136¬ 

138 

Korenjak,  A.  J.  300,  302 

INDEX 

Kosaraju,  S.  R.  705 
Kuck,  D.  J.  766-767,  899-901 
Kung,  H.  T.  901 

L 

Label  46,  364,  366 
LALR parser  259,  266-275,283,  287 
Lam,  M.  S.  767,  899-902,  961-964 
Lamport,  L.  503,  766-767,  899-901 
Language  44,  118 

See  also  Java,  Source  language, 

Target  language 

Lastpos  175-177 
Latest  expression  649,  654 
Lattice  621 

See  also  Semilattice 
Lattice  diagram  621-622 
L-attributed  definition  313-314,331¬ 

352 

Law 

See  Associativity,  Commutativ-
ity,  Distributivity,  Idempo-
tence 

Lawrie,  D.  H.  900 
Lazy  code  motion 

See  Partial  redundancy  elimi 

nation 

Lea  458 
Leader  526-527 
Leaf  45-46 
Leaf  region  673 
Least  upper  bound  621 
LeBlanc,  R.  J.  580 
Left  side 

See  Head 
Left-associativity  48 
Left-factoring  214-215 
Leftmost  derivation  201 
Left-recursion  67-68,  71,  212-214, 

328-331 

Left-sentential  form  201 
Leiserson,  C.  E.  901 
Lesk,  M.  E.  189-190 
Leu,  T.  963 
Levin,  V.  962 

INDEX 

1001 

Lewis,  P.  M.  II  300,  302,  355 
Lex  126-127,140-145,166-167,189¬ 

Loop  fusion 

See  Fusion 

190,  294-295 

Lexeme  111 
Lexical  analyzer  5-7,  4 1,  76-84,  86, 

109-190,  209-210,294-295, 
967-969 
Lexical  error  194 
Lexical  scope 

See  Static  scope 
Lexicographic  order  791 
Liao,  S.-W.  901 
Lichtenber,  J.  962 
Lieberman,  H.  502-503 
Lim,  A.  W.  901 
Linear  programming 

See  Integer  linear  programming 

List  scheduling  723-726 
Literal  922 
Live  variable  528-529,  608-610,  615 
Livshits,  V.  B.  962-963 
LL  g r a m m ar  223 
LL  parser 

See  Predictive  parser 

LLgen  300 
Load  instruction  512 
Loader  3 
Local  code  optimization 
See  Basic  block 

Locality  455,  769 

See  also  Spatial  locality,  Tem 

poral  locality 

Location  26-28 
Logical  address  427 
Logical  error  194 
Lohtak,  O.  962 
Lookahead  78,144-145,171-172,  272¬ 

275 
Lookahead-LR  parser 
See  LALR  parser 

Loop  531,  554,  556,  655-656,  775 

See  also  Do-all  loop,  Fully  per 

mutable  loops,  Natural  loop 

Loop fission 

See  Fission 

Loop  nest  780,  791,  797,  862 
Loop  region  674 
Loop  reversal 

See  Reversal 

Loop  unrolling  735,  740-741,  743 
Loop-invariant  expression  641-642 
Loop-residue  test  822-823 
Loveman,  D.  B.  901 
Lowry,  E.  S.  579-580,  705 
LR(0)  a u t o m a t on  243,  247-248,  252 
LR parser 53-252,  275-277,  325,  348¬ 

352 

See  also  Canonical  LR  parser, 
LALR  parser,  SLR  parser 

L-value  26,  98 

See  also  Location 

M 

Machine  language  508 
Macro  13 
Main  a t t r i b u te  341 
Mark-and-compact  476-482 
Mark-and-sweep  471-476,  482 
Marker  nonterminal  349 
Markstein,  P.  W.  580 
Martin,  A.  J.  503 
Martin,  M.  C.  963 
Matrix  multiplication  782-788 
Maximum  fixedpoint  626-628,  630¬ 

631 
Maydan,  D.  E.  899,  901 
McArthur,  R.  426 
McCarthy,  J.  189-190,  502-503 
McClure,  R.  M.  302 
McCullough,  W.  S.  189-190 
McGarvey,  C.  962 
McKellar,  A.  C.  900-901 
McNaughton,  R.  189-190 
McNaughton-Yamada-Thompson  al 
gorithm  159-161 

Medlock,  C.  W.  579-580,  705 
Meet  605,  615,  618-619,  622-623, 

633,  678,  695 

1002 

INDEX 

Meet-over-paths  solution  629-631 
Memoization  823 
Memory  20,  772-773 

See  also  Heap,  Physical  mem 
ory,  Storage,  Virtual  mem 
ory 

Memory  hierarchy  20,  454-455 
Memory  leak  25,  461 
Message-passing  machine  773,  894 
META  300 
Metal  918,  962 
Method  29 

See  also  Procedure,  Virtual  method 

Method  call 
See  Call 

Method  invocation  33 
MGU 

See  Most  general  unifier 

Milanova,  A.  962-963 
Milner,  R.  426 
Minimization,  of  states  180-185 
Minsky,  M.  503 
ML  387,  443-445 
Mock,  G.  426 
Modular  resource-reservation  table 

746-747,758 

Modular  variable  expansion  758-761 
Monotone  framework  624-628,  635 
Moore,  E.  F.  189-190 
M OP 

See  Meet-over-paths  solution 

Morel,  E.  705 
Morris,  D.  354 
Morris,  J.  H.  189-190 
Moss,  J.  E.  B.  502-503 
Most  general  unifier  393 
See  also  Unification 

Motwani,  R.  189-190,  302 
Mowry,  T.  C.  900-901 
Multiprocessor  772-773,  895 

See  also  SIMD,  Single-program 

multiple  d a ta 
Muraoka,  Y.  766-767,  899,  901 
M u t a t or  464 

N 

NAA  690 
NAC  633 
Name  26-28 
Narrowing  388-389 
Natural  loop  667,  673 
Naur,  P.  300,  302 
Neighborhood  compaction  736 
Neliac  425 
Nested  procedure  declarations  442¬ 

445 

Next-fit  458-459 
NFA 

See  Nondeterministic  finite  au 

t o m a t on 

Node  46 
Node  merging  953 
Nondeterministic  finite  a u t o m a t on 
147-148,152-175,  205,  257 

Nonreducible  flow  graph 

See  Reducible  flow  graph 

Nonterminal  4 2 - 4 3,  45,  197-198 

See  also  Marker  nonterminal 

Nonuniform  memory  access  773 
Null  space  808-8Q9 
Nullable  175-177 
Nullity  808 
NUMA 

See  Nonuniform  memory  access 

O 

Object  code  358 

See  also  Code  generation 

Object  creation  937 
Object  ownership  462 
Object  program  427-428 
Object  sensitivity  950 
Object-oriented  language 
See  C + +,  Java 

Offset  377-378 
Ogden,  W.  F.  354 
Olsztyn,  J.  426 
Ondrusek,  B.  962 

INDEX 

1003 

On-the-fly  generation  340-343,380¬ 

381 
Optimization 

See  Code  optimization 

Ordered  BDD  952 
O u t p ut  dependence  711,  816 
Overloading  99,  390-391 

P 

Paakki,  J.  354-355 
P a d u a,  D.  A.  902 
Panic-mode  garbage  collection  492¬ 

493 

Panic-mode  recovery  195-196,  228¬ 

230,  283-284 

Panini  300 
Parafrase  899 
Parallel  garbage  collection  495-497 
Parallelism  19-20,  707-902,  917 
P a r a m e t er  422 

See  also  Actual  parameter,  For 
mal  parameter,  Procedure 
parameter 
P a r a m e t er  passing  33-35,  365 
Parametric  polymorphism  391 
See  also  Polymorphism 

Parent  46 
Parr,  T.  302 
Parse  tree  45-48,  201-204 

See  also  Annotated  parse  tree 
Parser  8,  4 1,  45,  6 0 - 6 1,  110-111, 
191-302,  981-986 

See  also  Bottom-up  parser,  Top-

down  parser 

Parser  generator 

See  Antlr,  Bison,  CUP,  LLgen, 

Yacc 

Parser  state  241-242 

See  also  Set  of  items 

Partially  ordered  set 
See  Poset 

Pass  11 
Patel,  J.  H.  767 
P a th 

See  Acyclic  p a t h,  Critical  p a t h, 
Execution  p a t h,  Meet-over-
paths  solution,  Weight,  of 
a  p a th 

P a t t e rn  111 
P a t t e rn  matching,  of  trees  563-567 
Patterson,  D.  A.  38,  579-580,  766¬ 

767,  899,  901 

Pause  time  465 

See  also  Short-pause  garbage  col 

lection 

P-code  386 
P DG 

See  Program-dependence  graph 

Peephole  optimization  549-552 
Pelegri-Llopart,  E.  580 
Permuation  849-850 
Peterson,  W.  W.  705 
P FC  899 
Phase  11 
Phoenix  38 
Phrase-level  recovery  196,  231 
Physical  address  427 
Physical  memory  454-455 
Pierce,  B.  C.  426 
Pincus,  J.  D.  962-963 
Pipeline 

See  Instruction  pipeline,  Pipelin 
ing,  Software  pipelining 

Pipelining  861-884 
P i t t s,  W.  189-190 
Pnueli,  A.  964 
Pointer  365,  373,  514,  539,  935 

See  also  Dangling  pointer,  Stack 

Partial  garbage  collection  483,  487¬ 

pointer 

494 

Pointer  analysis  713,  903,  917,  933¬ 

Partial  order  619-621,  623 
Partial  redundancy  elimination  639¬ 

655 

Partially  dead  variable  655 

951 

Poison  bit  718 
Polyhedron 

See  Convex  polyhedron 

1004 

Polymorphism  391-395 
Porterfield,  A.  900,  902 
Poset  619 
Positive  closure  123 
Postdominator  728 
Postfix  expression  40,  53-54 
Postfix  translation  scheme  324-327 
Postorder  traversal  58,  432 

See  also  Depth-first  order 

Postponable expression 646,  649,  651¬ 

654 

Power  set  620 
P r a t t,  V.  R.  189-190 
P RE 

See  Partial  redundancy  elimi 

nation 

Precedence  48,  121-122,  279-281, 

293-294 

Predecessor  529 
Predicate  921-922 
Predicated  execution  718,  761 
Predictive parser 64-68,  222-231,343¬ 

348 
Prefetch  457 
Prefetching  718,  896 
Prefix  119,  918,  962 
Prefix  expression  327 
Preorder  traversal  58,  432 
Preprocessor  3 
Prioritized  topological  order  725-726 
Private  31 
Privatizable  variable  758 
Procedure  29,  422-424 
Procedure  call 

See  Call 

Procedure  parameter  448-449 
Processor  space  779-781,  838-841 
Product  lattice  622-623 
Production  42-43,  45,  197,  199 
See  also  Error  production 

Proebsting,  T.  A.  580 
Program-dependence  graph  854-857 
Programming  language  12-14,  25¬ 

35 

INDEX 

See  also Ada,  C,  C + +,  Fortran, 

Java,  ML 

Projection  955 
Prolog  742 
Prosser,  R.  T.  705 
Protected  31 
Pseudoregister  713 
P T R AN  900 
Public  31 
Pugh,  W.  899,  902 
Purify  25,  462 

Q 

Qian,  F.  962 
Quadruple  366-368 
Quicksort  431-432,  585 

R 

Rabin,  M.  O.  189-190 
Rajamani,  S.  K.  962 
Randell,  B.  502-503 
Rank,  of  a  matrix  807-809 
Rau,  B.  R.  767 
Reaching  definitions  601-608,  615 
Read  barrier  486 
Record  371,  376-378,  584 
Recursive  descent  338-343 
Recursive  type  372 
Recursive-descent  parser  64,  219-222 
Reduced  instruction-set  computer 

See  RISC 

Reduce-reduce  conflict  238-240,  293 
Reducible flow graph 662,  664,  673¬ 

677,  684-685 

Reduction  234,  324 
Reduction in  strength 536,  552,  592¬ 

596 

Reference 

See  Pointer 

Reference  count  462-463,  466,  468¬ 

470 

Reference  variable  34,  686-689 
Reflection  944-945 
Reflexivity  619 

INDEX 

1005 

Region  672-686,  694-699,  733-734, 

911 

Region-based  allocation  463 
Register  18,  20,  454-455,  542-543, 

714-715 

See  also  Pseudoregister,  Rotat 

ing  register  file 

Register  allocation  510-512,  553-557, 
570-572,  716,  743 

Register  assignment  510,  556 
Register  descriptor  543,  545-547 
Register  pair  510 
Register  renaming 

See  Hardware  register  renam 

ing 
Regular  definition  123 
Regular  expression  116-122,159-163, 
179-180,  189,  210 

Rehof,  J.  961,  963 
Re-indexing  848,  850 
Relation  922,  954 
Relative  address  371,  373,  381 
Remembered  set  491 
Renvoise,  C.  705 
Reserved  word 

See  Keyword 
Resource  constraint  711 
Resource-reservation  table  719-720 

See  also  Modular  resource-reservation 

table 

Retreating  edge  661,  664-665 
Return  365,  467,  518-522,  906,  942 
Return  value  434 
Reuse 

See  D a ta  reuse 

Reversal  849-850 
Right  side 

See  Body 

Right-associativity  48 
Rightmost  derivation  201 
Right-sentential  form  201,  256 
Rinard,  M.  962-963 
RISC  2 1,  507-508 
Ritchie,  D.  M.  426,  502-503 
Rodeh,  M.  766-767 

Root  46 
Root  set  466-467,  488 
Rosen,  B.  K.  704 
Rosenkrantz,  D.  J.  355 
Rotating  register  file  762 
Rothberg,  E.  E.  900-901 
Rounds,  W.  C.  354 
Rountev,  A.  962-963 
Row 

See  Tuple 

Row-major  order  382,  785 
Roy,  D.  963 
Rule  922-923 
Run  time  25 
Run-time  environment  427 
Run-time  stack  428-451,  468 
Russell,  L.  J.  502-503 
Ruwase,  O.  962-963 
R-value  26,  98 
Ryder,  B.  G.  962-963 

S 

Sadgupta,  S.  767 
Safety 

See  Conservative  data-flow  anal 

ysis 
Samelson,  K.  354-355 
Sarkar,  V.  902 
S-attributed  definition  306,  312-313, 

324 

Scaling  848,  850 
Scanned  state  474 
Scanning  110 

See  also  Lexical  analyzer 

SCC 

See  Strongly  connected  compo 

nent 
Scheduling  710-711,  716 
Scholten,  C.  S.  503 
Schorre,  D.  V.  302 
Schwartz,  J.  T.  579,  581,  704 
Scope  86 
Scott,  D.  189-190 
Scott,  M.  L.  38 
Scripting  language  13-14 

1006 

SDD 

See  Syntax-directed  definition 

SDT 

See  Syntax-directed  translation 

SDV  962 
Secondary  storage  20 
Second-generation  language  13 
Sedgewick,  R.  585 
Self  reuse  806-811 
Semantic  analysis  8-9 
Semantic  error  194 
Semantic  rule 

INDEX 

Single  production  232 
Single-program  multiple  d a ta  776 
Skewing  849-850 
SLAM  962 
SLR  parser  252-257,  283 
SMP 

See  Symmetric  multiprocessor 

Software  pipelining  738-763,  895 
Software  productivity  23-25 
Software  vulnerability 

See  Vulnerability,  of  software 

SOR 

See  Syntax-directed  definition 

See  Successive  over-relaxation 

Semantics  40 
Semilattice  618-623 
Sensitivity 

See  Context  sensitivity,  Flow  sen 

sitivity 

Sentence  200 
Sentential  form  200 

Sound  type  system  387 
Source  language  1 
Space 

See  D a ta  space,  Iteration  space, 
Null  space,  Processor  space 
Space-partition  constraint  831-838 
Spatial  locality  455-457,  465,  777, 

See  also  Left-sentential  form,  Right-

884 

sentential  form 

Sentinel  116 
Set  associativity  457 
Set  of  items  243-246,  257 

See  also  Canonical  LR(0)  set 
of  items,  Canonical  LR(1) 
set  of  items 
Sethi,  R.  38,  579,  581 
Shannon,  C.  189-190 
Sharir,  M.  964 
Shift-reduce  conflict  238-240,  293 
Shift-reduce  parser  236-240 
Short-circuiting  953 
Short-pause  garbage  collection  483¬ 

494 

Shostak,  R.  902 
Side  effect  306,  314-316,  727 
Sielaff,  D.  J.  962-963 
Signature  361 
SIMD  21,  895-896 
Simple  syntax-directed  definition  56 
Simulation  23 
Single  instruction,  multiple  d a ta 

See  SIMD 

Spatial  reuse  806,  809-811 
Speculative  execution  708,  717-719 
Spilling,  of  registers  716 
S P MD 

See  Single-program  multiple  d a ta 

SQL  22-23 
SQL  injection  918-919 
SSA 

See  Static  single-assignment  form 

Stable  set  488 
Stack  325,  518,  520 

See  also  Run-time  stack 

Stack  machine  507 
Stack  pointer  437 
Stallman,  R.  301 
Start  state  131,  147,  205 
Start  symbol  43,  45,  197 
State  147,  205 

See  also  Dead  state,  Minimiza 
tion,  of states,  Parser state 
State  (of  the  program  store)  26-28 
Statement  93-94,  100-101,  978-981 

See  also  Break-statement,  Continue-
statement,  If-statement,  Switch-

INDEX 

1007 

statement,  While-statement 

Static  access  816 
Static  allocation  518,  524 
Static  checking  97-98,  357 

See  also  T y pe  checking 

Static  policy  25 
Static  R AM  456 
Static  scope  25,  2 8 - 3 1,  442 

See  also  Scope 

Static  single-assignment  form  369¬ 

370 
Static  storage  429,  442 
Steady  state  742 
Stearns,  R.  E.  300,  302,  355 
Steel,  T.  426 
Steensgaard,  B.  961,  964 
Steffens,  E.  F-  M.  503 
Storage 

Switch-statement  418-421 
Symbol  table  4 - 5,  11,  8 5 - 9 1,  423, 

970-971 
Symbolic  analysis  686-699 
Symbolic  constant  793 
Symbolic  m ap  690 
Symmetric  multiprocessor  772 
Synchronization  828,  832,  853-854, 

880-882 

Syntax  40 

See  also  G r a m m ar 

Syntax  analysis 
See  Parser 

Syntax  error  194 
Syntax  tree  4 1,  69-70,  92-93,  318¬ 

321,  358,  367,  981-986 

Syntax-directed  definition  54-56,  304¬ 

316 

See  Dynamic  storage,  Static  stor 

Syntax-directed  translation  40,  57¬ 

age 

Storage  layout  373 
Storage-related  dependence 

See  Antidependence,  O u t p ut  de 

pendence 

Store  instruction  512 
Stratified  Datalog  program  930-931 
Strength  reduction 

See  Reduction  in  strength 

String  118-119,  373 
Strong,  J.  426 
Strongly  connected  component  751, 

859 

Strongly  typed  language  387 
Structure 

See  Class,  Record 

Subgoal  923 
Subsequence  119 
Subset  construction  153-154 
Substring  119 
Successive  over-relaxation  863 
Successor  529 
Suffix  119 
Summary-based  analysis  911-914 
Super  control-flow  graph  906 
Superscalar  machine  710 

60,  324-352 

Synthesis  4 
Synthesized  a t t r i b u te  54-56,  304¬ 

305 

T 

Table 

See  Relation,  Resource-reservation 
table,  Symbol  table,  Tran 
sition  table 

Tail  recursion  73 
Takizuka,  T.  767 
Tamura,  E.  767 
Tardieu,  O.  961,  963 
Target  code 

See  Object  code 

Target  language  1 
Target  set  488 
Task  parallelism  776 
Temporal locality 455-457,  777,  884¬ 

885 

Temporal  reuse  806 
Terminal  42-43,  45,  197-198,  305 
TeX  331 
Third-generation  language  13 
Thompson,  K.  189-190 

1008 

INDEX 

Three-address  code  42,  99,  363-369 
Tick 

See  Clock 
Tiling  560-563 
Time-partition  constraint  868-875, 

989-992 
Tjiang,  S.  W.  K.  579-580 
T MG  300 
Token  4 1,  43,  76,  111 
Tokura,  N.  705 
Tokuro,  M.  767 
Top  element  619,  622 
Top-down  parser  61-68,  217-233 

See  also  Predictive parser,  Recursive-

descent  parser 

Topological  order  312 

T1-T2  reduction  677 
Tuple  954 
Type  938 

See  also  Basic  type,  Function 
type,  Recursive  type 

Type  checking  24,  98-99,  370,  386¬ 

398 

Type  Conversion  388-390 
See  also  Coercion 
Type  equivalence  372-373 
Type  expression  371-372,  393,  395 
Type  inference  387,  391-395 
Type  safety  19,  464-465 
Type  synthesis  387 
Type  variable  391 

See  also  Prioritized  topological 

U 

order 

Torczon,  L.  580,  963 
Towle,  R.  A.  902 
Trace-based  garbage  collection  470¬ 

471 

See  also  Mark-and-compact,  Mark-

and-sweep 
Train  algorithm  483,  490-493 
Transfer  barrier  486 
Transfer  function  599-600,  603-604, 

615, 623-624, 629, 634, 676¬ 
679,  691-693 

Transition  205 
Transition  diagram  130-131,  147¬ 

148 

See  also  Automaton 
Transition  function  147,  150 
Transition  table  148-149,  185-186 
Transitivity  619-620 
Traversal  56-57 

See  also  Depth-first  search,  Pos-
torder  traversal,  Preorder 
traversal 

Tree  46,  56 
Tree  rewriting  558-567 
Triple  367-368 
Tritter,  A.  426 
True  dependence  711,  815 

Ullman,  J.  D.  189-190,  301-302,  579, 
581,  705,  962,  964 

Umanee,  N.  962 
UNCOL  425 
U N D EF  633 
Unification  393,  395-398 
Union  119,  121-122,  605,  613,  615, 
620,  650,  955-957 

Unkel,  C.  963 
Unreachable  code 

See  Dead  code 

Unreached  state  473 
Unsafe  Datalog  rule  930 
Unsafe  language  498 
Unscanned  state  474 
Upward  code  motion  730-732 
Usage  count  554-555 
Use  609 
Use  before  definition  602 
Used  expression  649,  653-654 
Used  variable  528-529 
Ustuner,  A.  962 

V 

Valid  item  256 
Value  26-27 
Value-number  360-362,  390 

INDEX 

1009 

Variable  26-28 

See  also  Nonterminal,  Reference 

Write  barrier  486-487 
Wulf,  W.  A.  705 

Y 

Yacc  287-297,  354 
Yamada,  H.  189-190 
Yield  46-47,  201 
Yochelson,  J.  C.  502-503 
Younger,  D.  H.  301-302 

Z 

Zadeck,  F.  K.  704 
Zhu,  J.  961,  964 

variable 

Variable  expansion 

See  Modular  variable  expansion 

Variable-length  d a ta  438-440 
Vector  machine  886,  895-896. 
Very-busy  expression 

See  Anticipated  expression 

Very-long  instruction  word 

See  VLIW 

Viable  prefix  256-257 
Virtual  machine  2 

See  also  Java  virtual  machine 

Virtual  memory  454-455 
Virtual  method  904,  916-917,  934, 

941-944 
VLIW  19-21,  710 
Von  Neumann  language  13 
Vulnerability,  of  software  917-921 
Vyssotsky,  V.  704-705 

W 

Wavefronting  876-877 
Weber,  H.  300,  302 
Wegman,  M.  N.  704 
Wegner,  R  704-705 
Wegstein,  J.  426 
Weight,  of  a  p a th  822 
Weinberger,  R  J.  189-190 
Weinstock,  C.  B.  705 
Wexelblat,  R.  L.  38 
Whaley,  J.  961,  963-964 
While-statement  401 
White  space  4 1,  77-78 
Widening  388-389 
Widom,  J.  962,  964 
W i d t h,  of  a  type  374 
Wilderness  chunk  458 
Wilson,  R  R.  502-503 
Wirth,  N.  300,  302,  426 
Wolf,  M.  E.  900-902 
Wolfe,  M.  J.  902 
Wonnacott,  D.  899,  902 
Wood,  G.  767 

<  OMPII  ERS 

This  new  edition  of  the  classic  "Dragon"  book  has  been 
c o m p l e t e ly  revised  to  include  the  most  recent  d e v e l o p m e n ts  in  c o m p i l 
ing.  The  b o ok  provides  a  thorough  introduction  to  c o m p i l er  design  and 
c o n t i n u es  to  e m p h a s i ze  the  applicability  of  compiler  t e c h n o l o gy  to  a 
broad  range  of p r o b l e ms  in  software  design  and  d e v e l o p m e n t.  The  first 
half  of  the  b o ok  is  designed  for  use  in  an  undergraduate  c o m p i l e rs 
course,  while  the  second  half can  be  used  in  a  graduate  course  stressing 
c o de  o p t i m i z a t i o n. 

• 

New  chapters  include: 
(  hapter  7:  Run-Time  Environments 
Chapter 10: Instruction-I.evel Parallelism 
Chapter  11:  O p t i m i z i ng  for  Parallelism  and  locality 
Chapter  12:  Interprocedural  Analysis 

PPfl 
hfe^kL*Mj|LlA|^jA 

I  Gradianee  is  a  Web-based  h o m e w o rk  and  lab 
instructors. 
assessment  resource  for  students  and 
I  I  or  Compilers  it  offers  a  collection  of h o m e w o rk 
sets  using  a  special  technique  called  root  questions.  Students  work 
through  a  problem  as  if  it  were  a  normal  h o m e w o rk  assignment.  Their 
is  then  s a m p l ed  by  a  randomly  c h o s en 
k n o w l e d ge  of  the  s o l u t i on 
multiple-choice  question.  When  a  wrong  answer  is  selected,  they  receive 
a  hint  and  i m m e d i a te  advice  that  explains  why  the  answer  is  wrong  or 
suggests  a  general  approach  to  the  problem.  Students  are  then  allowed 
to  try  the  same  assignment  again.  This  approach  provides  immediate 
reinforcement  of compiler  concepts.  Using  Gradiance  allows  instructors 
to  assign,  test,  and  track  h o m e w o rk  automatically  and  e n h a n c es  their 
learning  experience.  A  c o m p l i m e n t a ry  subscription 
students'  overall 
is  offered  w h en  an  access  c o de  is  ordered  packaged  with  a  new  copy 
of  this  text.  Subscriptions  may  also  be  purchased  o n l i n e,  for  more 
information  about  Gradiance,  please  visit  a w . c o m / g r a d i a n c e. 

A d d i s on  W e s l ey  (  o i n p u l i ng 
I eading Authors • Quality Products 

PEARSON 

Addison 

Wesley 

Visit  a w . c o m / c o n ^ p u l i ng  loi  more 
i n f o r m a t i on  a b o ut  A d d i s o n - W e s l ey 
computing  b o o k s. 

o 

C/5 

U l l m an 

Second 
I  dition 

