0% found this document useful (0 votes)
18 views23 pages

CD Unit V - Material

The document discusses the runtime environment and memory allocation for data objects in programming, focusing on activation records and procedures. It outlines various memory allocation strategies, including stack and heap allocation, as well as parameter passing methods like call by value and call by reference. Additionally, it addresses code generation issues and instruction selection for efficient execution in target machines.

Uploaded by

Sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views23 pages

CD Unit V - Material

The document discusses the runtime environment and memory allocation for data objects in programming, focusing on activation records and procedures. It outlines various memory allocation strategies, including stack and heap allocation, as well as parameter passing methods like call by value and call by reference. Additionally, it addresses code generation issues and instruction selection for efficient execution in target machines.

Uploaded by

Sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIIT-VN

Code enetation

Runthme
The
¬nironment 8
attocafion a n d deatloca ton o data Vasir1hla
objeck aze

managd by the untme Suppot package.


t h e oxecution
d each pedure. s refered a
activation recddis) Actation
pocedure.
the epesentation odota obects ad unime is
de tommed by ?B tuP. fivation Rrcdd
Actvaon Trer
Achafon Rechd uses acfivation tree-for exctuion
a pmcedure thet Can be Spted by the
Compiler
Achvation Tre
The folloung aumpions ane used by he Compile
in pm&dluves dsng execution
1-Conhol floos Sequertiaty-thaB means the
ekecuhon a proqram (onsuts Squence of
sep with tonhol begtn at dbme specife
potnt in the p0q ram ot each st ep
Fach exccution a pmcedure stasks ak b innn
da pwceclue body and hetuvns Conbot
at end the pwcedure.
>Stovage dgarisations
* O Sstage mapping of.names and valuest

Enunnment
sBates

name
stonge Vales

Sub diision d vuntime memoy


Runtime stdage Can be. olded into thvce tupes
1. The qenetakd tatget Code
Data objects
3Counttr poat a Conhol stack keep track rotatne
proadare
achvations
(ode
Static data
trses Lfo 0 Urd at(C
L Sfack Pdai e'es ropll seiock alhy

13
Heap p sttncatt

Stracture Achvation ReChd


>TempbAlese
AftY Comilng aprogram Compiler geneaBes
intemedia (ode in that it Calls tempiay
Vaglables that Ctn be stdad
In memdy location.

ocal Data t
i thim O Souice fProgranm along oith main

function depend uon requiremenh dfferent


user

Sub functions aue aucilable ou thoie Punctions


QLe stved by ompller using locad Dota.
Save machine tatus-
Aftr Stoimg vasiables n memoy, Compi ler
uses dffrent machine instucticnt pefdming
openations by usng Sawed machne satu.

optiona (ondrol and Acees nkst

These links ae
optional y bcause eytne
wer doemo ue Subtunchisn whte developînq a
Source poqra but these ln ks aue activate d
ohenever Subfunctions e used lo prugram!
Acua paametut

Compiler auup ove prociy fs actual patamets


that Can be ued in
proqrau and pufdm
peufim opeLaha
opeLah
n hose vasiobles only
Reun vauest

y ekuy, Vallts fa achuot


tinatly mpiles qenttat
fov proram
poLamea -td qenetahng olp

Snc Alacaion stategieg -

heve aue tAre tupestboge alotahon shaleaics

Staht Allocahion
&stack Allbcahon
3- thap Attbcohom

4 shatic Atlocation:

A S he memoy veqcinow
Code fo (onsume
ud stoaqe totahions au
Corle 8 cduce Code kmown in aduance,
nuntme supdt packoo
Achivahin Retdd
F&memoy altotahn
8 Consun slatic deattocaRn is not
Oota Ttquue d
A chivahom Resd
| f s produce.
vaiables
onsune meon hohile Compiling poram

e stoed m mmemdy
Vasiabex oithin memdy,
medns aptestoinq
Droduce
vatiable s -fom umemdy.
acces
he Cormpilation data is bouod to a
m tRs alotaton
lbtaton in the mendy and
it doemot' chauge
red
when the prooram executes
Stack Atlocation6-
p a ae en and¥ pycedluve Catli and hely arivali,
An
etun vndae
Cond tunks and
Qte mamaged y mean qsta
Sawr dmachin e
States
memdy auotahon
Owors.1m ufo method and
lempdalles and
vCal data th attocaton shoaay is uey seful
atameks audF6 veculve oceure Call!
Aetutn Valuês
Cont nes and
Saved machine
States

Tempshe and
oCa Date.

Heap Atocation&

*Hap aloCaton is used to


Con fooC Gnk4 dyramitaly allocoli memdy to the
Vcutad dasm it bace when
he vastades aue no mde
Conho ink
|oquived
Comhotn 3 EXcept shahkally aluocakd mem
aua both stact
ancd heap memgy
Can oow and shink
dyramiaty and unexpekdy
they Capnot be pryvided otth a Hed omount
memdy mthe Systm
panametr pasfmgt
the
ohen ne proCedure Ccells noter, Phocecdare
is
uAuatt method CoYwunitatin blw Hhen
tfnowgh mames and thouqh patameers atled
pCectues
Thein ae cufevend tuprs patamets pastmg meehantpmw
here
-Ccet by Value
CoLL by vefevence
opy rest&e
Mame
4 Cau by

1. Call by value
actual pasame tës Qle valuaed
n Call by value
n pcedures

EX pogram Reference(tnput,output);
Va a,binteor
pYoceduvei Sosp (va y :inltger);
vah temp:inttg er ;
pascal
begn QnquOE.

s=omp s
nd
beqin
a t b-13
SwapCa,6)
o iteln (a =",a) s
unin (b=', b)
eud

Cau by Referencet
n Catl by refevence Cempiler ues addreas
vasl able

Ex t *x,*4$
Swap (1nt a, tot u)
tot tcmp
claog
poqraw
*y3

mobn c

int a-1, b-2


Suoopl a , &b);
pontt (a s d b is d n,a,b

Copy Restore e
* s alo Ccntled as Copy n, topybut
Tt a hybd blw CalL by value and Cal by
teference.
EXproqram Copyout( tnput,output)y
Van a : întqe"s
pceceue umtofe (vah t toltqa);

Dal (auquoq
a:0
eud

usten(a)
end

Name
4 Calt by
trad6onaty defned
as (opy rule pstolloase
Tt is
t teattd as maco -e; actua
1.The pwcedure
Such
Subsfitutd stor Pomaly
pasame tos ale
Catled a macoexpansion 6)
Substitution is
nlineunction-

au placed în palarthesis
9. The actua! posametos
f resewe the intqity
Ex Suoapt, alii) fy

alt-Aen
posibiono Code qeneiatovs

Sounce
font oamatat de rumko ode
end Code Code
opinitahin Nencoaton

Symbod
table

Tssues in the dtsign Codegeneator 6

tRere
e e ale differenttupe g isues in the desgm
Code enelation

. Irpuk to the tatge p Cocde geneldo


2.Tatget program t
3 Mendy Maagmcot
4Inshurtion Selecdon
5 Requtr Pltnhion
6 Choice evalution ddei
Approochea to Ccoole qenetatd.
1-Trput -to he Code genaator hinas wanbrs
l8)mor
Code hme ( o d e hinay
p-opimi 7cd 3 odHe'n tede p lolgel
Code
The p Code genetts 1s the intmecti ati qenelate d

the frnt end, aong oith infdmatlon in he


by addrees
that dettmines the un-tme
Smbot totie
he dada objeets demtd by the mames in the
inkemedhatr Yepreseodafon Tnkemediat Codes may

be Yepreentd motty n quackryles,inpla, indiart


hpdes, patR notahon, Sntontrers, dd ete

e s t proqram i- B iatny ipo enye phgo fehntyir

Test pmqram is the olp the Code qeneaat.


The blp
olp may be absout machine langua
languaq,
atoCata machine language, atsembly auguage

Absdut machne Tt 1s an olp has aduartage


that it Can be placed Ina Prmed memgu
toCation & Can be Immedtakety exetukd.

Relocatable machine: 9t 1 an olp alouws

Subpmgams and
Subnuknes to be (ompiled

Sepctakly makø he Codk


ASsembly 1t s an dlp
qneiakon easen

3memdy Momagment 6-
mames n the source pmaram to
Moppng the
areses data ebtels done by ront
end and the Code qenelatô" A în the name

three addra Stmt Yefes to the cumbol hble


thre
name A Comphng Snun pan Civnpile,
enty o
S 0tmohyn we in drttruo
Cache
CDO Man
ATnstnction Selectiom
tne effscienc
Sclechng best. mshuehons all mpyue
am 9t tnclucdes 1he insuetions hat
he proqr
Shoutd Complet And un fm. ansthe ton ipeai
and macin e dioms also pls o majo'olLe
khen ecienCy is Cortidaed. devriophra Soure mae
depd Cpon peiNuw C by n Us er oYn pile
a p +R . dfeot ps ns hurhons goeth
S&P+T
Hre m he stmt, fE is
Mov , Ro
tcdundont as the volu of pis
AOD R,Ro
boded again în that shmt Hat
MOV Ro, P
JU hce been S8ed rn he
mov P, Ro
ADD T Ro
pveious tmt
Mov RoS
6Reaß er AtloCation |h tornlin Sot ce (ooun (ompils chsrs ot
thmtne
we oresis krs moke the Computatbns -fashin
Compaissn to tha memdyThe we
rCou s 0e Sudivded ntb a &ub publems
. Recgck Alocahnt a select Gnly hase Set
vasiables
tha w'll reside n hie veais ta cu each
pt in the
poqram
9. e t r Assignment n H1s, he Specifhe seqfser
s picked to access the uaßiables
Fvaoiom 8rlEr S: Opetns, rf 4he p (o be pngi rr 9

The tocde genesato decides the dder in whkh he


inshuehm wil be extcuktd The dder Copdathns
affees the ef c reray eAne latget Code

Appwaches to Code
gmetatin isurst
Coe geneiah musB alon qcneiat the Csect
(ode t esenbal beCauwe a the o
Special Cases thal a Code enesatb mlqh
face. Some e tme desan qoals Code Cenas
Souncc
hile qenuaahg alp
C&t ucyan ctnei appilicalicn: aie
quide d bdE qntah ompsler
Easiy malitaiab
Testabl.
Ohrapmocheo the
o rcrencnaóye Kefe opi2eton)
4Maimleinab l

The Tasget machine.


*Instuior ot
40oding înshchion Cost
the iules ale as fotlovase
. the irnshmelion Mov Ro, R Cophes Contens of
Ro tnto , the nschon Cos haone
The tnsfur tion 5,M Copies the (ontnt
Mov
tns ehon
R to memdy otaon "m, the
Cout has too?

3-The tnsmebon ADD # , R hsch adds (onstant


t o the veqiuler R the tnsmehn Cost is "too'.
A the fnshurtion SuB y(eo) ,*12(21).Themsue horn
Cost ha
,

Ofnd ns hucton (osh for the follo uoing


mov b Ro 2

ADD CRo-2
mov Ro, a
-

Total cost s s

mov ba-3
ADO Ca 3

ADD Ra, * Ro -
2

Tota Cot two.

ADD P, Ri
Mov. Pi, a

T6Ba Cos's kAree.


Oops
sa -slectons nades n flow qraph Such tha
)AU he norles m the (olleohion ale honguy
Conneekd heom auy hade in e loop there
1s
pah length one (6)mde
The Coleckongle has a umique enhy e;
wode in the loop Such that tht only oayto
Alach a node he loopfiom anode outstde
the loop 8 -ht qo 4ough he emy
Coop ehat (ovtains ho.Other loop is Called
as inner loop

Representatim o Basie Blocks


easie
Basic blocks Con be eprescnted by wing difttont
tupes datostuetuves
data Shuctures a u ed by
Thue a u a Apes
the tompilr
ünea
2. n o n - l i n e a

Rmple Code qenciatd 3-

Conuert.an
Ihe man we Code geneatd fs-to
tnttrmediatu Code vepresentation
'into a Unea
enuencee machine insmueHons
Code qenesato we fastv nshurhions lew o-of
inshuckons, avoilable neqistu Onol auod
aedelet

ComputaNs
*Code qeneutd phases incude
4-Tnshurtion Selechon
Dnshon scheduin
3 Resis Aloca tion-

Simple Cedegeneats Alodnthrn gentals (ode-Fs 9inade


lock
M d fesue dustg Cole qenaion s decidnq he
egistesu
tefoltbiing aAe
principt uway4
waqt
1. Al he opelands must be 1
Aeqstons In dder
to pefdm opaaton
Reatst» aue wed b
. hol
d abbal ualue
S Recists alo used in. unime tdog
managmene
4 Machine inshuetios ane ued to
pufdm opeahans
On desstou
1 Regises ae tuse.d to hotd tempdasy ruutt
Sub erpestont
Cole enetation we decriptou t
keer rack
reistt ConBents, and.adkess -d nome
ehawe & tupes o desc ptoc aue tha T
Code qendaton . 9
1
Recse Deréptov-24 keeps tiaek of whad
&enty auaible 1o éachdisty- 2F s ued whenevey
new aeciser is Acquistd.
he
Acddres Descriptor N keeps drack otocoum
tht ukent value h e Mame con be found a
unfme. The totahm Can be a eoisty G)a
memdy address
Desgndhefuncipn qte
Code gantation alooitm uses a funchon qdReg uhich
Code
Sctecs a nenlu fd taoh nmemdy lotabyn thot
assoG akd wi addrey insmebs
the Aurndn qelkq has acces to the neteu cund acress
deacohptos Fo al the vaiade basie blocks

qeReq Aetuns +he (otaton((L) to hold the value


the ex X*yta
*Faxt sting the vaiabu in memdy lotahvn inctudes
the fotlowinq Auues
- oh an d y e stdad iis the Teofutas

&Df a n necitt and


sthed y is tthed m

wemdy totadon
3 ai stud in memdy and y i sBded m

4 seqiskus ae not auailable both the Uatiahle


auL dldectty stded ta memdy
Code qenetaton Alqbitbm
takes p Jeauen
atadithm
h e Ceocde genetatim
hatdrs a baic block
three addreu stmts

th tach three actihev shot q the-dm a*:yopt,


the tolowing achonss
Complle puftm
1Tnvoke a unchm aetRea to detumine,heloca
hun
o h a the esuth fhe putationyobr
ö i I UBULaly bta
Shutd be stSd whee tL)
lo Cabon ) a neaists.
memdy

onsult the addves cdauiphs o6 (y) to detmine


y) whee Culent (oCaHm o(y)(y)
pupo the necska fa () f the value (y)
is uAsentty bothin memoy and efsha-af
he val 4) not olltady tn
nsmue bov
tgenees
mov
yb slota o opy
3 Cenent the nshuefon op , whae the
Cuyent to Cobm (Eudat the addreu
decsipd t o inditat thet (a) is m ()
h e Snecidtu udat t eaciptb to
uda tHhat to jndicaathat Contoins h
vahue Ond emove () from au othei
nfoiski deacpds
4-9 the Guyent value yand t ha no ent
Ue lothn the bas blotk #hen the vaue
ase in
neqiskss inditat that au erecahin

Xvop those eajstns lonqA wil


(ontin y awd nesptchvey
Symbol Tblk
Syolaa sding vatiables in symbol toble is as
lookCp( unucde)
ollos )aeh¬I Ae vaslobl,
i t auovlo ble 1o
LSymbol name, Tupe, athihut.
aophma patt
Ext
iDt a
Compile oill takex like this
2a, int>
4 pum 0ptabn.
4. Tnsestt) insanq the vasiahe 10sa(ojnl )
2ldokup()Seaschngthe valiablu, en loorop(a)
in the ymbo) table
aHt.
we hav e hpes Symbol
1.dobal Sumbol tabl(
SCope tymbel Habe
pam - Gobal Symbxol table
Vae o3 Vaue valabe Tpr
pron in
oq-ome C)
p9-Cme p- 0
tone-1 Aymbo table

ne -2 MC V uxo-2 Va
e-3val n tuo3 V nt
mt me-3; nn
mone-45 Kop)
|oes/wytt ncs oyin
eyVauint u3va int
int bne-5 va lnt
nner stope
int one6
innu
int one_A; J
ept
3
pmg-tue co

int tuoo-1
i0to- 23
int two3 ion
fnt twou: ope3
Object Code Forms

Object code is the output generated by the code generation phase of a compiler. It represents the
lower-level, machine-specific code derived from the intermediate representation (IR) and is intended
to be executed on a specific hardware architecture.

Purpose of Object Code Forms:


• Bridges the gap between high-level programming languages and machine code.
• Provides a format that is more optimized and closer to hardware execution.
• Facilitates debugging and allows further optimization before final execution.

Types of Object Code Forms

Assembly Code
• A human-readable form of object code that uses mnemonic instructions instead of binary.
Ex:
MOV AX, BX; Move the value of BX into AX
ADD AX, 1; Increment the value in AX by 1
• Acts as an intermediate stage where the IR is translated into a form that can be further
processed into binary machine code by an assembler.
• Easier for humans to understand and debug, as it uses symbolic representations of machine
instructions.

Machine Code

• Binary code that is directly executed by the CPU.


Ex: 10110000 01100001 (binary sequence representing an instruction).
• Represents the final stage of code generation, where instructions are in a format that the
hardware can execute.
• Executable code loaded into memory for direct execution by the processor.

Intermediate Representation (IR)


• An abstract representation of the program that is between the source code and machine code.
Ex: t1 = b * 5
c = a + t1
• Simplifies the process of optimization and allows the compiler to perform machine-
independent optimizations.
• Easier to generate and modify before generating final target code. Examples include Three-
Address Code (TAC), Static Single Assignment (SSA), etc.
Relocatable Object Code

• code that can be placed at any memory address.


Ex: Produced as an output from an assembler, containing code and data that can be linked
with other modules.
• Enables flexibility in combining multiple object files into a final executable, allowing the
code to be loaded at different memory locations.
• Used during the linking phase to resolve addresses and create a final executable.

Absolute Object Code

• Contains machine instructions with fixed memory addresses.


Ex: The instructions specify exact memory locations.
• Directly loaded into memory for execution without the need for relocation.
• Rarely used due to lack of flexibility, often suitable for very simple systems where the
program's memory layout is predetermined.

Code Generation Process Overview

Code Generation Phase: Converts IR into machine-specific instructions.

• Instruction Selection: Maps IR operations to target machine instructions.


• Register Allocation: Assigns variables and temporaries to registers.
• Address Translation: Converts variable references into memory addresses or registers.

Linking and Loading:

• Linker: Combines multiple object files into a single executable, resolving references to
external symbols.

• Loader: Loads the executable file into memory, adjusting addresses and preparing the
program for execution.

Example of Object Code Generation

For a simple expression like c = a + b * 5, the following illustrates the translation process
[[

Intermediate Representation (IR):


t1 = b * 5
c = a + t1
Assembly Code:
MOV AX, b; Load b into AX
MUL AX, 5; Multiply AX by 5
MOV t1, AX; Store result in t1
MOV AX, a; Load a into AX
ADD AX, t1; Add t1 to AX
MOV c, AX; Store result in c
if x> y and so on.
• CJ < z - Jump to z if value is negative
Consider the following example:
x := y + z
if x < 0 goto z
The following would be the target code
MOV y, R0
ADD z, R0
MOV R0, x //x is the condition code
CJ < z
Register Allocation and Assignment:
Register allocation is only within a basic block. It follows top-down approach.
Local register allocation
– Register allocation is only within a basic block. It follows top-down approach.
– Assign registers to the most heavily used variables
– Traverse the block
– Count uses
– Use count as a priority function
– Assign registers to higher priority variables first
Need of global register allocation:
• Local allocation does not take into account that some instructions (e.g. those in loops)
execute more frequently. It forces us to store/load at basic block endpoints since each
block has no knowledge of the context of others.
• To find out the live range(s) of each variable and the area(s) where the variable is
used/defined global allocation is needed. Cost of spilling will depend on frequencies
and locations of uses.
Register allocation depends on:
– Size of live range
– Number of uses/definitions
– Frequency of execution
– Number of loads/stores needed.
– Cost of loads/stores needed.

12
Usage Counts:
A simple method of determining the savings to be realized by keeping variable x in a register
for the duration of loop L is to recognize that in our machine model we save one unit of cost
for each reference to x if x is in a register.
An approximate formula for the benefit to be realized from allocating a register to x within a
loop L is:

∑ (𝑢𝑠𝑒(𝑥, 𝐵) + 2 ∗ 𝑙𝑖𝑣𝑒(𝑥, 𝐵))


𝑏𝑙𝑜𝑐𝑘𝑠 𝐵 𝑖𝑛 𝐿

where,
-use(x, B) is the 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 0 otherwise.
Example: Consider the basic block in the inner loop in Fig 5.3 where jump and conditional
jumps have been omitted. Assume R0, R1 and R2 are allocated to hold values throughout the
loop. Variables live on entry into and on exit from each block are shown in the figure.

Fig 5.3 Flow graph of an inner loop


Fig 5.4 shows the assembly code generated from Fig 5.3.

Fig 5.4 Code sequence using global register assignment

13

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy