SlideShare a Scribd company logo
1 of 51
Run-Time Environment
Lecture 15
Run time Addressing
• Given a variable reference in the code, how
can we find the correct instance of that
variable?
• Things are trickier – variables can live on the
stack.
• Tied to issues of scope
Storage and access for locally declared data
• The executing procedure uses the frame pointer to
quickly access values in its stack frame as the
frame pointer points to the start of the frame.
• Then add the variable’s offset from the start of the
frame. Calculating local data’s offset (to be stored
in the symbol table)
• However problem arise for variable length data
• Goal:
Allow a routine to have variable-length data
(i.e., dynamically-sized arrays) as local data in frame
• Option 1:
Allocate the variable on the heap
Work with pointers to the data
Auto free the data when the routine returns
• Option 2:
Create the variable on the stack, dynamically
Effectively: Enlarge the frame as necessary
Still need to work with pointers
Variable-Length Local Variables
Variable Length Data
return value
actual parameters
optional control link
optional access link
saved machine
status
local data
pointer a
pointer b
temporaries
array a
array b
Control link and saved status
Control link and saved status
………
Pointer to a
Pointer to b
….
Array a
Array b
Activationrecord
forp
Activation
record
forq
Arrays
ofp
Arrays
ofq
top
Variable length data is allocated after
temporaries, and there is a link to from
local data to that array.
top_sp
Variable-Length Local Variables
Local Variables at fixed offsets from
FP
Dynamically sized variables use
hidden pointers
All references to “a” and “b” will be
indirect through hidden pointers
Frame
Data Access Without Nested Procedures
• Does not allow nested procedure declaration
– Variables are either local or global
• Allocation and access to variables are simple
– Global variables
• Allocated static storage
• Locations remain fixed and known at compile time
• Access possible using statically determined address
– Local variables may be accesses using top_sp
pointer
Scope
The scope of a variable is that portion of the programs
to which the variable applies.
• A variable islocal to a procedure if the declaration
occurs in that procedure.
• A variable is non-local to a procedure if it is not local
to that procedure but the declaration occurs in an
enclosing scope of that procedure.
• A variable is global if it occurs in the outermost
scope.
Types of Scoping
• Static – scope of a variable determined from the
source code. Scope A is enclosed in scope B if
A's source code is nested inside B's source
code.
• Dynamic – current call tree determines the
relevant declaration of a variable use.
Static Scoping Rules
Dynamic Scoping Rules
Local / Non-Local Variables
Local / Non-Local Variables
Local / Non-Local Variables
Local / Non-Local Variables
The Static Link
The Static Link
The Static Link
Given a variable usage...
How do we find the frame containing the right
variable?
Assume that x is declared at lexical level M.
Assume that x is used at lexical level N.
(We must have N  M)
At runtime...
Follow N-M static links to find the right frame.
Use the offset of x within that frame.
Initializing the Static Link
Initializing the Static Link
• At runtime, we can’t know where the relevant
activation record holding the variable exists on the
stack
• Use static (access) links to enable quick location
– addr(x) = # static links + x's offset
– Local: (0,offset)
– Immediately enclosing scope: (1,offset)
Runtime Addressing in Stack Allocation
Display Registers
To access a non-local variable
How to Maintain the Display Registers?
How to Maintain the Display Registers?
How to Maintain the Display Registers?
How to Maintain the Display Registers?
How to Maintain the Display Registers?
How to Maintain the Display Registers?
How to Maintain the Display Registers?
How to Maintain the Display Registers?
Various approaches to passing data into and out of a
procedure via parameters
1. Call-by-value – data is copied at the callee into
activation and any item changes do not affect
values in the caller.
• Ex: C parameters
2. Call-by-reference – pointer to data is placed in the
callee activation and any changes made by the
callee are indirect references to the actual value in
the caller.
• C++ - call-by-value and call-by-reference
Parameter Passing
var a,b : integer
procedure swap(x,y : integer);
var t: integer;
begin t := x; x := y; y := t; end;
begin
a := 1;b := 2;
swap(a,b);
write ('a = ',a);
write ('b = ',b);
end.
value reference
write(a) 1 2
write(b) 2 1
Call-by-value vs Call-by-reference
3. Call-by-value-result (copy-restore) – hybrid of
call-by-value and call-by-reference. Data
copied at the callee. During the call, changes do
not affect the actual parameter. After the call,
the actual value is updated.
4. Call-by-name – the actual parameter is in-line
substituted into the called procedure. This
means it is not evaluated until it is used.
Parameter Passing
var a: integer
procedure foo(x: integer);
begin a := a + 1; x := x + 1; end;
begin
a := 1;
foo(a);
write ('a = ',a);
end.
Value-result reference
write(a) 2 3
Call-by-value-result vs. Call-by-reference
var a : array of integer; i: integer
procedure swap(x,y : integer);
var t: integer;
begin t := x; x := y; y := t; end;
begin
i := 1;
swap(i,a[i]);
write (‘i,a[i] = ’,i,a[i]);
end.
Call-by-name vs. Call-by-reference
Heap
• Heap is used for data that lives indefinitely or until
the program explicitly deletes it
• Local variables become inaccessible when
their procedures end
• Many language enable us to create objects or
other data whose existence is not tied to their
procedure activations
– In C++/Java we can create objects using new
keyword and may be passed to other procedures
Heap Management
• Memory Manager
– Allocates and deallocates space within the heap.
– Serves as an interface between application programs
and operating system
– For some languages that need to deallocate space
manually MM is responsible for implementing that.
• Garbage Collector
– Responsible for finding spaces within the heap that are
no longer used by the program and the deallocate them
– GC is an important subsystem of the memory manager
Memory Manager
• Keeps track of all the free space in heap storage at all
times.
• Two basic functions
– Allocation –
• In response to some request MM produces a chunk of
contiguous heap memory
• If not possible then seeks to increase heap storage from
virtual memory
– Deallocation –
• MM returns deallocated space to the pool of free space
Memory Manager
• MM would be simpler if
– All requests were for the same sized chunks
– Storage were released in first-allocated first-deallocated
style
• BUT!! None is possible in most languages
• MM should be prepared to
– Serve requests in any order
– Serve requests of any size
Properties of Memory Manager
• Desired properties of MM
– Space Efficiency
• Should minimize the total heap spaced needed
• Can be achieved by minimizing fragmentation
– Program Efficiency
• Should make good use of the memory to allow program
to run faster
• Should take advantage of ‘locality’ characteristics of
program
– Low Overhead
• Allocation and deallocation operations should be as
efficient as possible
Memory Hierarchy
• Registers are managed by the generated code
• All other levels are managed automatically
• With each memory access the machine searches each level of the
memory in succession starting from the lowest level
Virtual Memory (Disk)
Physical Memory
2nd-Level Cache
1st-Level Cache
Registers (Processor)
Typical Sizes
> 2 GB
256MB-2GB
128KB-4MB
16KB-64KB
32 Words
Typical Access Times
3-15 ms
100-150ns
40-60ns
5-10ns
1ns
Memory Hierarchy
• Data is transferred as blocks of contiguous storage
• Larger blocks are used with the slower levels of the
hierarchy
• Cache lines
– Data blocks transferred between main memory and
cache
– Typically from 32 to 256 byets
• Pages
– Data transferred between virtual memory and main
memory
– Typically between 4K and 64K
Fragmentation
• Variable-sized chunks of memory are
allocated.
• Some chunks are freed (in more-or-less
random order).
• The resulting free space become
“fragmented”.
• Need to allocate more space?
• Adequate space is available
... but it is not contiguous!
• Even if holes are larger than the request
…. We need to split the hole
…. Creating yet smaller hole
Holes
Fragmentation Reduction
• Control how the MM places new objects in the heap
• Best-Fit Algorithm
– Allocate the requested memory in the smallest
available hole that is large enough
– Spares larger holes for subsequent larger requests
– Good strategy for real-life programs
• First-Fit Algorithm
– Object is placed in the first hole in which it fits
– Takes less time to place objects
– Overall performance is inferior to best-fit
Managing Free Space
• Coalescing a recently feed chunk to the adjacent free
chunk forms larger chunk
– We can always use a larger chunk to do the work of
small chunks of equal total size
• For bins of one fixed size we don’t want to coalesce
– Simple to keep track of allocation/deallocation using bit
map
• 1 indicates allocated
• 0 indicates free
Problems with Manual Deallocation
• Two common mistakes
1. Memory Leak
• Failing ever to delete data that will never be referenced
• Slow down the program due to increased memory
usage
• Critical for long running/nonstop program such as OS or
server
• Does not affect program correctness
• Automatic garbage collection gets rid of it
– Even the program may use more memory than necessary
Problems with Manual Deallocation
• Two common mistakes
2. Dangling Pointer Reference
• Delete some storage and try to refer to the data
in the deallocated storage
• Once the freed storage is reallocated any read,
write or deallocation via dangling pointer can
produce random effects
• Dereferencing a dangling pointer creates program
error hard to debug

More Related Content

What's hot

Chapter One
Chapter OneChapter One
Chapter One
bolovv
 
System Programing Unit 1
System Programing Unit 1System Programing Unit 1
System Programing Unit 1
Manoj Patil
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generation
rawan_z
 
System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit III
Manoj Patil
 
Lec 04 intro assembly
Lec 04 intro assemblyLec 04 intro assembly
Lec 04 intro assembly
Abdul Khan
 
Workshop Assembler
Workshop AssemblerWorkshop Assembler
Workshop Assembler
Tuhin_Das
 

What's hot (20)

Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environment
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compiler
 
Chapter One
Chapter OneChapter One
Chapter One
 
Assemblers
AssemblersAssemblers
Assemblers
 
System Programing Unit 1
System Programing Unit 1System Programing Unit 1
System Programing Unit 1
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generation
 
System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit III
 
Lec 04 intro assembly
Lec 04 intro assemblyLec 04 intro assembly
Lec 04 intro assembly
 
C basics
C basicsC basics
C basics
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Assembler Language Tutorial for Mainframe Programmers
Assembler Language Tutorial for Mainframe ProgrammersAssembler Language Tutorial for Mainframe Programmers
Assembler Language Tutorial for Mainframe Programmers
 
Workshop Assembler
Workshop AssemblerWorkshop Assembler
Workshop Assembler
 
Chap 1-language processor
Chap 1-language processorChap 1-language processor
Chap 1-language processor
 
Run time storage
Run time storageRun time storage
Run time storage
 
P code
P codeP code
P code
 
Introduction to compilers
Introduction to compilersIntroduction to compilers
Introduction to compilers
 
Compiler designs presentation final
Compiler designs presentation  finalCompiler designs presentation  final
Compiler designs presentation final
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Compiler unit 4
Compiler unit 4Compiler unit 4
Compiler unit 4
 

Similar to Lecture 15 run timeenvironment_2

Similar to Lecture 15 run timeenvironment_2 (20)

Runtimeenvironment
RuntimeenvironmentRuntimeenvironment
Runtimeenvironment
 
7. Key-Value Databases: In Depth
7. Key-Value Databases: In Depth7. Key-Value Databases: In Depth
7. Key-Value Databases: In Depth
 
Intro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsIntro to Data Structure & Algorithms
Intro to Data Structure & Algorithms
 
Building Big Data Streaming Architectures
Building Big Data Streaming ArchitecturesBuilding Big Data Streaming Architectures
Building Big Data Streaming Architectures
 
.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves.NET UY Meetup 7 - CLR Memory by Fabian Alves
.NET UY Meetup 7 - CLR Memory by Fabian Alves
 
Heap Memory Management.pptx
Heap Memory Management.pptxHeap Memory Management.pptx
Heap Memory Management.pptx
 
The Case for a Signal Oriented Data Stream Management System
The Case for a Signal Oriented Data Stream Management SystemThe Case for a Signal Oriented Data Stream Management System
The Case for a Signal Oriented Data Stream Management System
 
Hadoop Ecosystem and Low Latency Streaming Architecture
Hadoop Ecosystem and Low Latency Streaming ArchitectureHadoop Ecosystem and Low Latency Streaming Architecture
Hadoop Ecosystem and Low Latency Streaming Architecture
 
Cosmos DB at VLDB 2019
Cosmos DB at VLDB 2019Cosmos DB at VLDB 2019
Cosmos DB at VLDB 2019
 
Architecting for the cloud elasticity security
Architecting for the cloud elasticity securityArchitecting for the cloud elasticity security
Architecting for the cloud elasticity security
 
CPP19 - Revision
CPP19 - RevisionCPP19 - Revision
CPP19 - Revision
 
Hadoop
HadoopHadoop
Hadoop
 
Apache Big Data 2016: Next Gen Big Data Analytics with Apache Apex
Apache Big Data 2016: Next Gen Big Data Analytics with Apache ApexApache Big Data 2016: Next Gen Big Data Analytics with Apache Apex
Apache Big Data 2016: Next Gen Big Data Analytics with Apache Apex
 
COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time Environments
 
General Programming Concept
General Programming ConceptGeneral Programming Concept
General Programming Concept
 
Fault tolerant presentation
Fault tolerant presentationFault tolerant presentation
Fault tolerant presentation
 
HDFS_architecture.ppt
HDFS_architecture.pptHDFS_architecture.ppt
HDFS_architecture.ppt
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
 
Lecture-7 Main Memroy.pptx
Lecture-7 Main Memroy.pptxLecture-7 Main Memroy.pptx
Lecture-7 Main Memroy.pptx
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programming
 

More from Iffat Anjum

Qo s based mac protocol for medical wireless body area sensor networks
Qo s based mac protocol for medical wireless body area sensor networksQo s based mac protocol for medical wireless body area sensor networks
Qo s based mac protocol for medical wireless body area sensor networks
Iffat Anjum
 

More from Iffat Anjum (20)

Fog computing ( foggy cloud)
Fog computing  ( foggy cloud)Fog computing  ( foggy cloud)
Fog computing ( foggy cloud)
 
Cognitive radio network_MS_defense_presentation
Cognitive radio network_MS_defense_presentationCognitive radio network_MS_defense_presentation
Cognitive radio network_MS_defense_presentation
 
Lecture 16 17 code-generation
Lecture 16 17 code-generationLecture 16 17 code-generation
Lecture 16 17 code-generation
 
Lecture 12 intermediate code generation
Lecture 12 intermediate code generationLecture 12 intermediate code generation
Lecture 12 intermediate code generation
 
Lecture 13 intermediate code generation 2.pptx
Lecture 13 intermediate code generation 2.pptxLecture 13 intermediate code generation 2.pptx
Lecture 13 intermediate code generation 2.pptx
 
Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2
 
Lecture 09 syntax analysis 05
Lecture 09 syntax analysis 05Lecture 09 syntax analysis 05
Lecture 09 syntax analysis 05
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
 
Lecture 07 08 syntax analysis-4
Lecture 07 08 syntax analysis-4Lecture 07 08 syntax analysis-4
Lecture 07 08 syntax analysis-4
 
Lecture 06 syntax analysis 3
Lecture 06 syntax analysis 3Lecture 06 syntax analysis 3
Lecture 06 syntax analysis 3
 
Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2
 
Lecture 03 lexical analysis
Lecture 03 lexical analysisLecture 03 lexical analysis
Lecture 03 lexical analysis
 
Lecture 04 syntax analysis
Lecture 04 syntax analysisLecture 04 syntax analysis
Lecture 04 syntax analysis
 
Lecture 02 lexical analysis
Lecture 02 lexical analysisLecture 02 lexical analysis
Lecture 02 lexical analysis
 
Compiler Design - Introduction to Compiler
Compiler Design - Introduction to CompilerCompiler Design - Introduction to Compiler
Compiler Design - Introduction to Compiler
 
Distributed contention based mac protocol for cognitive radio
Distributed contention based mac protocol for cognitive radioDistributed contention based mac protocol for cognitive radio
Distributed contention based mac protocol for cognitive radio
 
On qo s provisioning in context aware wireless sensor networks for healthcare
On qo s provisioning in context aware wireless sensor networks for healthcareOn qo s provisioning in context aware wireless sensor networks for healthcare
On qo s provisioning in context aware wireless sensor networks for healthcare
 
Data link control
Data link controlData link control
Data link control
 
Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Pnp mac preemptive slot allocation and non preemptive transmission for provid...Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Pnp mac preemptive slot allocation and non preemptive transmission for provid...
 
Qo s based mac protocol for medical wireless body area sensor networks
Qo s based mac protocol for medical wireless body area sensor networksQo s based mac protocol for medical wireless body area sensor networks
Qo s based mac protocol for medical wireless body area sensor networks
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

Lecture 15 run timeenvironment_2

  • 2. Run time Addressing • Given a variable reference in the code, how can we find the correct instance of that variable? • Things are trickier – variables can live on the stack. • Tied to issues of scope
  • 3. Storage and access for locally declared data • The executing procedure uses the frame pointer to quickly access values in its stack frame as the frame pointer points to the start of the frame. • Then add the variable’s offset from the start of the frame. Calculating local data’s offset (to be stored in the symbol table) • However problem arise for variable length data
  • 4. • Goal: Allow a routine to have variable-length data (i.e., dynamically-sized arrays) as local data in frame • Option 1: Allocate the variable on the heap Work with pointers to the data Auto free the data when the routine returns • Option 2: Create the variable on the stack, dynamically Effectively: Enlarge the frame as necessary Still need to work with pointers Variable-Length Local Variables
  • 5. Variable Length Data return value actual parameters optional control link optional access link saved machine status local data pointer a pointer b temporaries array a array b Control link and saved status Control link and saved status ……… Pointer to a Pointer to b …. Array a Array b Activationrecord forp Activation record forq Arrays ofp Arrays ofq top Variable length data is allocated after temporaries, and there is a link to from local data to that array. top_sp
  • 6. Variable-Length Local Variables Local Variables at fixed offsets from FP Dynamically sized variables use hidden pointers All references to “a” and “b” will be indirect through hidden pointers Frame
  • 7. Data Access Without Nested Procedures • Does not allow nested procedure declaration – Variables are either local or global • Allocation and access to variables are simple – Global variables • Allocated static storage • Locations remain fixed and known at compile time • Access possible using statically determined address – Local variables may be accesses using top_sp pointer
  • 8. Scope The scope of a variable is that portion of the programs to which the variable applies. • A variable islocal to a procedure if the declaration occurs in that procedure. • A variable is non-local to a procedure if it is not local to that procedure but the declaration occurs in an enclosing scope of that procedure. • A variable is global if it occurs in the outermost scope.
  • 9. Types of Scoping • Static – scope of a variable determined from the source code. Scope A is enclosed in scope B if A's source code is nested inside B's source code. • Dynamic – current call tree determines the relevant declaration of a variable use.
  • 12. Local / Non-Local Variables
  • 13. Local / Non-Local Variables
  • 14. Local / Non-Local Variables
  • 15. Local / Non-Local Variables
  • 18. The Static Link Given a variable usage... How do we find the frame containing the right variable? Assume that x is declared at lexical level M. Assume that x is used at lexical level N. (We must have N  M) At runtime... Follow N-M static links to find the right frame. Use the offset of x within that frame.
  • 19.
  • 20.
  • 21.
  • 24. • At runtime, we can’t know where the relevant activation record holding the variable exists on the stack • Use static (access) links to enable quick location – addr(x) = # static links + x's offset – Local: (0,offset) – Immediately enclosing scope: (1,offset) Runtime Addressing in Stack Allocation
  • 26. To access a non-local variable
  • 27. How to Maintain the Display Registers?
  • 28. How to Maintain the Display Registers?
  • 29. How to Maintain the Display Registers?
  • 30. How to Maintain the Display Registers?
  • 31. How to Maintain the Display Registers?
  • 32. How to Maintain the Display Registers?
  • 33. How to Maintain the Display Registers?
  • 34. How to Maintain the Display Registers?
  • 35. Various approaches to passing data into and out of a procedure via parameters 1. Call-by-value – data is copied at the callee into activation and any item changes do not affect values in the caller. • Ex: C parameters 2. Call-by-reference – pointer to data is placed in the callee activation and any changes made by the callee are indirect references to the actual value in the caller. • C++ - call-by-value and call-by-reference Parameter Passing
  • 36. var a,b : integer procedure swap(x,y : integer); var t: integer; begin t := x; x := y; y := t; end; begin a := 1;b := 2; swap(a,b); write ('a = ',a); write ('b = ',b); end. value reference write(a) 1 2 write(b) 2 1 Call-by-value vs Call-by-reference
  • 37. 3. Call-by-value-result (copy-restore) – hybrid of call-by-value and call-by-reference. Data copied at the callee. During the call, changes do not affect the actual parameter. After the call, the actual value is updated. 4. Call-by-name – the actual parameter is in-line substituted into the called procedure. This means it is not evaluated until it is used. Parameter Passing
  • 38. var a: integer procedure foo(x: integer); begin a := a + 1; x := x + 1; end; begin a := 1; foo(a); write ('a = ',a); end. Value-result reference write(a) 2 3 Call-by-value-result vs. Call-by-reference
  • 39. var a : array of integer; i: integer procedure swap(x,y : integer); var t: integer; begin t := x; x := y; y := t; end; begin i := 1; swap(i,a[i]); write (‘i,a[i] = ’,i,a[i]); end. Call-by-name vs. Call-by-reference
  • 40. Heap • Heap is used for data that lives indefinitely or until the program explicitly deletes it • Local variables become inaccessible when their procedures end • Many language enable us to create objects or other data whose existence is not tied to their procedure activations – In C++/Java we can create objects using new keyword and may be passed to other procedures
  • 41. Heap Management • Memory Manager – Allocates and deallocates space within the heap. – Serves as an interface between application programs and operating system – For some languages that need to deallocate space manually MM is responsible for implementing that. • Garbage Collector – Responsible for finding spaces within the heap that are no longer used by the program and the deallocate them – GC is an important subsystem of the memory manager
  • 42. Memory Manager • Keeps track of all the free space in heap storage at all times. • Two basic functions – Allocation – • In response to some request MM produces a chunk of contiguous heap memory • If not possible then seeks to increase heap storage from virtual memory – Deallocation – • MM returns deallocated space to the pool of free space
  • 43. Memory Manager • MM would be simpler if – All requests were for the same sized chunks – Storage were released in first-allocated first-deallocated style • BUT!! None is possible in most languages • MM should be prepared to – Serve requests in any order – Serve requests of any size
  • 44. Properties of Memory Manager • Desired properties of MM – Space Efficiency • Should minimize the total heap spaced needed • Can be achieved by minimizing fragmentation – Program Efficiency • Should make good use of the memory to allow program to run faster • Should take advantage of ‘locality’ characteristics of program – Low Overhead • Allocation and deallocation operations should be as efficient as possible
  • 45. Memory Hierarchy • Registers are managed by the generated code • All other levels are managed automatically • With each memory access the machine searches each level of the memory in succession starting from the lowest level Virtual Memory (Disk) Physical Memory 2nd-Level Cache 1st-Level Cache Registers (Processor) Typical Sizes > 2 GB 256MB-2GB 128KB-4MB 16KB-64KB 32 Words Typical Access Times 3-15 ms 100-150ns 40-60ns 5-10ns 1ns
  • 46. Memory Hierarchy • Data is transferred as blocks of contiguous storage • Larger blocks are used with the slower levels of the hierarchy • Cache lines – Data blocks transferred between main memory and cache – Typically from 32 to 256 byets • Pages – Data transferred between virtual memory and main memory – Typically between 4K and 64K
  • 47. Fragmentation • Variable-sized chunks of memory are allocated. • Some chunks are freed (in more-or-less random order). • The resulting free space become “fragmented”. • Need to allocate more space? • Adequate space is available ... but it is not contiguous! • Even if holes are larger than the request …. We need to split the hole …. Creating yet smaller hole Holes
  • 48. Fragmentation Reduction • Control how the MM places new objects in the heap • Best-Fit Algorithm – Allocate the requested memory in the smallest available hole that is large enough – Spares larger holes for subsequent larger requests – Good strategy for real-life programs • First-Fit Algorithm – Object is placed in the first hole in which it fits – Takes less time to place objects – Overall performance is inferior to best-fit
  • 49. Managing Free Space • Coalescing a recently feed chunk to the adjacent free chunk forms larger chunk – We can always use a larger chunk to do the work of small chunks of equal total size • For bins of one fixed size we don’t want to coalesce – Simple to keep track of allocation/deallocation using bit map • 1 indicates allocated • 0 indicates free
  • 50. Problems with Manual Deallocation • Two common mistakes 1. Memory Leak • Failing ever to delete data that will never be referenced • Slow down the program due to increased memory usage • Critical for long running/nonstop program such as OS or server • Does not affect program correctness • Automatic garbage collection gets rid of it – Even the program may use more memory than necessary
  • 51. Problems with Manual Deallocation • Two common mistakes 2. Dangling Pointer Reference • Delete some storage and try to refer to the data in the deallocated storage • Once the freed storage is reallocated any read, write or deallocation via dangling pointer can produce random effects • Dereferencing a dangling pointer creates program error hard to debug