OPTIMIZING COMPILATION OF ARRAY
ACCESSES IN SOLIDITY SMART
CONTRACTS
COMPILACIÓN OPTIMIZANTE DE
ACCESOS A ARRAYS EN CONTRATOS
INTELIGENTES EN SOLIDITY
T abajo de Fin de G ado
Cu so 2022–2023
Au o
Ja ie Sande Ríos
Di ec o
Jesús Co eas Fe nández
G ado en Ingenie ía In o má ica
Facul ad de In o má ica
Uni e sidad Complu ense de Mad id
OPTIMIZING COMPILATION OF
ARRAY ACCESSES IN SOLIDITY
SMART CONTRACTS
COMPILACIÓN OPTIMIZANTE DE
ACCESOS A ARRAYS EN CONTRATOS
INTELIGENTES EN SOLIDITY
T abajo de Fin de G ado en Ingenie ía In o má ica
Au o
Ja ie Sande Ríos
Di ec o
Jesús Co eas Fe nández
Con oca o ia: Junio 2023
G ado en Ingenie ía In o má ica
Facul ad de In o má ica
Uni e sidad Complu ense de Mad id
May 28, 2023
Ag adecimien os
A mis pad es po b inda me la opo unidad de es udia . Jun o a ellos, a mi
he mana y a oda mi amilia po el cons an e ca iño y apoyo incondicional que
siemp e me han b indado.
A mis compañe os y amigos po odos los momen os inol idables que hemos
compa ido a lo la go de es e camino.
A la Uni e sidad y a odos sus p o eso es po su dedicación e incansable es ue zo,
especialmen e du an e los di íciles años de la pandemia, po en enseña nos y p o-
po ciona nos los ecu sos necesa ios pa a con e i nos en excelen es p o esionales.
Po úl imo, pe o no menos impo an e, quie o exp esa mi más p o undo ag adec-
imien o a mi di ec o en es e abajo, Jesús Co eas Fe nández, po su guía du an e
odo el p oceso y po su es ue zo pa a adap a se a las di icul ades que implicó la
di e encia ho a ia
Abs ac
On E he eum, sma con ac s mus ha e wo key cha ac e is ics: e iciency, an
essen ial ea u e in sma con ac s wi h a di ec economic impac on he use , and
secu i y. The compile o Solidi y, he mos widely used language o p og amming
E he eum sma con ac s, au oma ically inco po a es a ious secu i y checks o
a oid p og amming e o s. This is he case o bounds checks on a ay accesses.
Ne e heless, hese checks in oduce some compu a ional o e head, which migh be
unnecessa y in some scena ios.
In his p ojec , wo app oaches a e p oposed o educe he cos s associa ed wi h
hese con ols and, consequen ly, a ay accesses. Fi s , we in oduce a new Solidi y
code cons uc ha allows you o disable bounds checks in hose sec ions o code
ha p og amme s deem unnecessa y. Secondly, we p opose a new compile op i-
miza ion phase ha akes ad an age o he high-le el language s uc u es o he
p og am in o de o op imize low-le el accesses o a ays and elax he applicabili y
condi ions o cu en op imiza ions. Finally, we con i m h ough expe imen al e-
sul s he e ec i eness o bo h solu ions in educing he compu a ional cos o a ay
accesses.
Keywo ds
E he eum, blockchain, sma con ac , Solidi y, op imizing compile , un ime check.
ii
Resumen
En E he eum, los con a os in eligen es deben ene dos ca ac e ís icas cla e:
e iciencia, ca ac e ís ica esencial con un impac o económico di ec o en el usua io, y
la segu idad. El compilado de Solidi y, el lenguaje más u ilizado pa a p og ama
con a os in eligen es en E he eum, inco po a au omá icamen e a ios con oles de
segu idad pa a e i a e o es de p og amación. Es e es el caso de los con oles de
lími es en los accesos a a ays. No obs an e, es as comp obaciones in oducen cie a
sob eca ga compu acional, que puede se innecesa ia en algunos escena ios.
En es e p oyec o, se p oponen dos en oques pa a educi los cos os asociados con
es os con oles y, en consecuencia, con el acceso a a ays. P ime o, p esen amos
una nue a cons ucción de código de Solidi y que pe mi e deshabili a las comp o-
baciones de lími es en aquellas secciones de código en las que los p og amado es
las conside an innecesa ias. En segundo luga , p oponemos una nue a ase de op i-
mización en el compilado , que ap o echa las es uc u as del lenguaje de al o ni el
del p og ama pa a op imiza los accesos de bajo ni el a los a ays y elaja las condi-
ciones de aplicabilidad de las op imizaciones ac uales. Finalmen e, con i mamos a
a és de esul ados expe imen ales la e ec i idad de ambas soluciones pa a educi
el cos o compu acional de los accesos median e índice a a ays.
Palab as cla e
E he eum, blockchain, con a os in eligen es, Solidi y, compilado op imizado , com-
p obaciones en iempo de ejecución.
ix
In oduc ion
E he eum is one o he mos impo an blockchain ne wo ks in he cu en land-
scape. I s launch al e ed he blockchain wo ld due o i s sma con ac s, p og ams
whose code and s a e can be s o ed in he blockchain ne wo k o be execu ed by all
use s.
Sma con ac s, commonly de eloped using he Solidi y language, a e used by
ne wo k use s h ough ansac ions and execu ed in he nodes. These nodes, known
as mine s, a e economically ewa ded p opo ionally o he compu a ional cos o
he execu ed ansac ion. This compensa ion, paid by he use , makes he e iciency
o he con ac s essen ial, encou aging esponsible use o he blockchain and a oiding
a acks ha block ne wo k esou ces.
Ano he essen ial ea u e o sma con ac s is secu i y. These p og ams o en
manage and s o e digi al asse s o g ea alue, exposed o all ne wo k use s. The e-
o e, con ac s mus be as secu e as possible. Howe e , some imes secu i y and
e iciency clash, as in he case o a ay accesses on Solidi y sma con ac s.
The use o a ays is a widesp ead p ac ice in p og amming. A ays a e a lexible
da a ype, ex emely use ul o s o ing and s uc u ing da a in p og ams, and sma
con ac s a e no excep ion. Howe e , he cos o accessing a ays is conside ably
high in Solidi y sma con ac s. In o de o a oid p og amming e o s, he Solidi y
compile au oma ically gene a es bounds checks on each index access. The e o e,
each access o an index in ol es wo memo y loads o access he leng h and he
alue, signi ican ly inc easing he cos . This high cos implies a limi a ion in hei
use, especially when s o ing non- ola ile da a, one o he mos common uses o
a ays. The e o e, he op imiza ion o a ay accesses is o g ea in e es .
In his p ojec , we p opose wo possible solu ions o his p oblem. On he one
hand, we will p opose a Solidi y language cons uc ha allows p og amme s o
elimina e bounds checks hey conside unnecessa y. On he o he hand, we will
p opose a new compile op imiza ion o educe he a ay leng h loads when possible
and, consequen ly, educe he cos o accessing a ays.
1
2
Goals
The main goal o his p ojec is o design, implemen and es wo op imiza ion
p oposals o educe he gas consump ion associa ed wi h a ay accesses in Solidi y
sma con ac s. In o de o achie e i , we ini ially se he ollowing goals:
Unde s and how he cu en p oduc ion compile wo ks, i s in e nal and in-
e media e ep esen a ions o he code, and i s compila ion phases.
Unde s and cu en app oaches o he Solidi y language and i s compile o
gene a e op imized code, hei applicabili y, and limi a ions.
Implemen an op imiza ion a he language le el ha allows de elope s o
disable bounds checks on a ay index accesses.
Implemen a new op imiza ion able o educe a ay access gas cos in si ua ions
he cu en op imiza ion modules canno .
Planning
This p ojec was di ided in o wo main phases de eloped be ween Sep embe
2022 and May 2023. Each p ojec phase ocused on one o he wo a ay op imiza ion
p oposals.
Language op imiza ion block. Du ing he i s phase, be ween Sep embe and
Decembe , we ocused on implemen ing a new language cons uc in Solidi y, called
uncheckedA ay block, o p o ide de elope s wi h a ool o disable bounds checks
in a ay accesses o educe gas consump ion. In o de o implemen his language
ex ension, we i s pe o med a deep s udy o he Solidi y language, i s compile ,
and a simila solu ion ha he language p o ides o educe gas consump ion on
a i hme ic ope a ions. Then, we decided how o name and s uc u e his new block,
i s possible use, and i s limi a ions. Finally, we implemen ed he block o es and
analyze he eal pe o mance o his new op imiza ion ool on sma con ac s.
Compile op imiza ion. In he second phase o he p ojec , we implemen ed a
new op imiza ion a compile ime o educe he cos o a ay accesses inside loops.
Du ing his phase, we used all he knowledge abou he compile acqui ed in he
i s phase. Ne e heless, we needed o pe o m some esea ch and expe imen s
in o de o unde s and he op imiza ions cu en ly pe o med by he compile , i s
pe o mance, and i s limi a ions. Once we had a clea idea o how we could imp o e
3
he op imiza ions, we ocused on es ablishing he cons ain s needed o gua an ee he
soundness o ou new op imiza ion. Finally, we implemen ed an expe imen al e sion
o he p oposed op imiza ion and in eg a ed i in o a p oduc ion e sion o he o icial
compile . We measu ed he po en ial impac on he gas consump ion o eal sma
con ac s by pe o ming se e al es s wi h non- i ial benchma k p og ams.
Du ing bo h phases, we main ained weekly mee ings o discuss he di icul ies
ound, decisions aken, implemen a ion de ails, and expe imen al e alua ion, as well
as he esul s ob ained wi h benchma k p og ams and conclusions ou lining some
lines o u u e wo k.
Code eposi o ies
The de eloped op imiza ions a e a ailable in he ollowing Gi Hub eposi o y:
h ps://gi hub.com/ja ie Sande/solidi y
This eposi o y is a o k om he o iginal Solidi y eposi o y1, and i is publicly
a ailable. The eposi o y is composed o ou di e en b anches:
de elop b anch: con ains he e sion o he o icial de elop b anch we used as
a base o ou de elopmen , co esponding o e sion 0.8.192o he compile
as o Feb ua y 23, 2023.
uncheckedA ay b anch: con ains he basic implemen a ion o he uncheckedA ay
block as p esen ed in Sec ion 2 o Chap e 3.
a ge edUncheckedA ay b anch: con ains he inal implemen a ion o he
uncheckedA ay block as p esen ed in Sec ion 3 o Chap e 3.
a ayLoopOp imiza ion b anch: con ains he implemen a ion o he compile
op imiza ion as p esen ed in Chap e 4.
Addi ionally, he benchma ks de eloped o he e alua ion o he op imiza ion
p esen ed in Chap e 4 a e a ailable in he ollowing Gi Hub eposi o y:
h ps://gi hub.com/ja ie Sande/solidi y-benchma ks
The README page o he eposi o y con ains he se up ins uc ions o pe o m
gas cos e alua ions o code gene a ed by an o icial o expe imen al e sion o he
Solidi y compile .
1The o icial Solidi y eposi o y can be ound a h ps://gi hub.com/e he eum/solidi y.
2Commi 983407762c3423e9c301d5ae56ac7b6d951655d
4
S uc u e o he documen
This memo y con ains he backg ound, implemen a ion de ails, and conclusion
o he p oposed op imiza ions. The documen is s uc u ed as ollows:
Chap e 1: in oduces E he eum, he E he eum Vi ual Machine, and Solid-
i y language. This chap e p o ides he heo e ical and echnical backg ound
o unde s and he necessi y and possibili ies o c ea ing op imiza ions.
Chap e 2: in oduces he Solidi y compile , i s compila ion p ocess, and
s a e o he a on Solidi y code op imiza ions.
Chap e 3: p esen s he uncheckedA ay block, a new Solidi y s uc u e o
allow de elope s o disable sa e y checks in a o o e iciency.
Chap e 4: p esen s a new compile op imiza ion phase ha akes ad an age
o a highe le el o code ep esen a ion o op imize a ay accesses inside loops.
Conclusions and Fu u e Wo k: p esen s he conclusions o he op imiza-
ions de eloped in ou p ojec and p oposes lines o wo k o u u e de elop-
men o he p oposed op imiza ions.
Chap e 1
E he eum
E he eum is an open-sou ce, decen alized blockchain ne wo k concei ed by Vi-
alik Bu e in in 2013 and o icially launched in 2015 [25]. I is ounded on he
basis o he blockchain p o ocol, i s p oposed by Da id Chaum in 1982, and i s
implemen ed by Sa oshi Nakamo o1in 2008 wi h he c ea ion o Bi coin [19].
As a blockchain, E he eum is a dis ibu ed ledge whe e ansac ions a e eco ded
in o blocks linked using c yp og aphic hashes. Like many o he blockchain ne wo ks,
i has i s own digi al cu ency, e he , used o s o e alue, pe o m exchanges, pay
ees, and ewa d pa icipan s o he ne wo k, such as he mining nodes.
Wha makes E he eum special is ha i was he i s p og ammable blockchain.
This means ha he ne wo k can be used o execu e p og ams. Those p og ams a e
known as sma con ac s, a concep i s coined in he 1990s by Nick Szabo, who
de ined hem as:
A se o p omises, speci ied in digi al o m, including p o ocols wi hin
which he pa ies pe o m on hese p omises. [22]
Sma con ac s a e p og ams whose code and s a e a e s o ed on he ne wo k
a a speci ic add ess, allowing anyone o in e ac wi h hem h ough unc ion calls
execu ed in he E he eum Vi ual Machine(EVM). When a blockchain use wan s o
communica e wi h he sma con ac , i sends a ansac ion o i s add ess speci ying
he unc ion o he con ac i wan s o execu e. Then, his ansac ion is alida ed
by he ne wo k nodes, which execu e he co esponding unc ion using he EVM on
i s local machine.
The possibili y o s o ing and execu ing p og ams in a decen alized en i onmen
in a secu e manne has opened he doo o a la ge numbe o new echnologies, such
1Pseudonymous pe son o g oup o pe sons who de eloped Bi coin.
5
6Chap e 1. E he eum
as decen alized apps, known as dApps,Non- ungible okens (NFTs) and he Web3.
All o hem a e based on he sma con ac echnology in oduced by E he eum.
E he eum is, a he ime o his w i ing, a sys em wi h a ma ke capi aliza ion
o $200B, which pe o ms mo e han 1 million ansac ions and has hal a million
ac i e add esses daily2. I is a ne wo k in con inuous g ow h, laying he ounda ions
o he u u e o decen alized sys ems.
1.1. E he eum Vi ual Machine
The E he eum Vi ual Machine (EVM) is a i ual machine capable o Tu ing-
comple e compu a ion. I is a un ime en i onmen execu ed by he blockchain
nodes o p ocess he blockchain ansac ions, including he unc ion calls o sma
con ac s. The EVM can be seen as he s a e unc ion o he E he eum ne wo k [25].
I akes an inpu (s a e o he blockchain, i s con ac s, and code o be execu ed),
pe o ms some compu a ions, and ou pu s a new s a e.
Figu e 1.1: Rep esen a ion o he EVM om EVM Illus a ed [23]
The EVM is a simple s ack-based a chi ec u e wi h a 1024-elemen s ack. The
wo d size is 256 bi s in he s ack, and in all i s memo y egions3, in o de o acili-
a e c yp og aphic ope a ions such as hashing and ellip ic cu es. As illus a ed in
Figu e 1.1, he EVM is composed o he ollowing elemen s:
2These and mo e s a is ics abou E he eum can be consul ed a h ps://e he scan.io.
3Vola ile memo y is bo h wo d and by e-add essable. We conside he same wo d size o all
egions o simplici y.
1.2. Gas 7
The p og am coun e (PC).
A ROM memo y con aining he code o execu e.
The gas a ailable o pe o m he ope a ions, a pa ame e ha limi s he com-
pu a ion done in a ansac ion.
The s ack ha con ains he local alues used on he ope a ions.
A ola ile memo y egion o s o e da a du ing he execu ion.
A pe sis en memo y egion called s o age, whe e he con ac s a e is s o ed.
The EVM execu es he by ecode o he compiled con ac in e p e ed as a se-
quence o opcodes4, ins uc ions ha pe o m s ack-bases ope a ions (e.g., PUSH,
ADD,PUSH) and o he blockchain and c yp og aphic ela ed ope a ions such as BLOCKHASH,
BALANCE and KECCAK256.
1.2. Gas
The EVM can execu e Tu ing-comple e p og ams. Howe e , i is a quasi-Tu ing-
comple e machine since i s compu a ion is bounded h ough a pa ame e called
gas, which limi s he amoun o compu a ion pe o med in a single ansac ion.
This compu a ion limi has a secu i y eason. I limi s he execu ion on he EVM
and, consequen ly, in he blockchain, p e en ing buggy o malicious con ac s om
execu ing inde ini ely, hanging he ne wo k (Denial o Se ice).
Mo eo e , his cos model has ano he essen ial du y: ewa ding he mine s.
Each uni o gas has an associa ed p ice se in e he 5de e mined by he use s
ha issue he ansac ion. Wi h his amoun o e he , mine s a e ewa ded o he
compu a ional e o o execu ing he ope a ion and a e incen i ized o p io i ize
ce ain ansac ions. Use s can se highe gas p ices o p io i ize ansac ions o
lowe p ices i hey do no mind he ansac ion aking longe o p ocess. The
a e age gas p ice o each mined block can be consul ed in eal- ime on pla o ms
such as E he scan.
Along wi h speci ying he gas p ice, he use ha ini ializes he ansac ion o
con ac call speci ies he amoun o gas ha can be des ina ed o i s execu ion on
he EVM. Each EVM ins uc ion has a p ede ined gas cos 6wi hd awn om he
4Read mo e abou EVM opcode a h ps://e he eum.o g/en/de elope s/docs/e m/
opcodes/
5Usally, gas p ice is speci ied in gwei ha co esponds o 10−9e he .
6The cas cos o each EVM ins uc ion can be consul ed a h ps://e he eum.o g/en/
de elope s/docs/e m/opcodes/.
8Chap e 1. E he eum
o al amoun o gas when i is execu ed. The non-consumed gas is e u ned o he
calle a e he unc ion call. Howe e , i he EVM uns ou o gas while execu ing
he unc ion call o he execu ion ails, he con ac s a e e e s, bu he gas is no
e unded o he calle .
The gas cos mechanism is a undamen al ea u e o he E he eum blockchain. I
ensu es ha he ne wo k emains secu e and economically incen i ized o mine s.
Ne e heless, his mechanism u ges he con ac s in he ne wo k o be as e icien
as possible since hey ha e a di ec mone a y cos on hei use s.
1.3. P og amming Languages
De elope s can use se e al p og amming languages o de elop sma con ac s
o he E he eum blockchain. Di e en languages can a ge he EVM, such as LLL
(Lisp Like Language) [18], one o he i s languages de eloped o E he eum, o
Vype [24], an expe imen al language. Howe e , he as majo i y o sma con ac s
in he E he eum blockchain a e coded in one pa icula language, Solidi y. Acco ding
o E he scan, he e e ence analy ics pla o m o E he eum, his language is used
by mo e han 99% o he con ac s used in he blockchain7.
In his p ojec , we aim ou op imiza ions o each he la ges numbe o sma
con ac s possible. The e o e, we ocused on he Solidi y language, i s compila ion
in o EVM by ecode, and i s in e media e ep esen a ion, Yul.
1.3.1. Solidi y
Solidi y is an objec -o ien ed language ha a ge s he E he eum Vi ual Ma-
chine (EVM). I was p oposed in 2014 by Ga in James Wood and de eloped by
membe s o he E he eum Founda ion led by Ch is ian Rei wiessne . I is mainly
in luenced by C++, bu i also has bo owed concep s om o he languages such
as Py hon and Ja aSc ip . This simila i y wi h o he popula languages has made
Solidi y an easy language o adop o de elope s who wan o de elop sma con-
ac s.
Solidi y is he mos popula p og amming language in he E he eum blockchain.
I is used o de eloping sma con ac s ha can be compiled in o EVM by ecode o
be deployed in he ne wo k. In Solidi y, ou ypes o p og ams can be de eloped8:
7These and mo e s a is ics abou sma con ac s can be consul ed a h ps://e he scan.io/
dashboa ds/con ac -s a is ics.
8Read mo e abou con ac s, in e aces, and lib a ies in Solidi y a h ps://docs.
solidi ylang.o g/en/ 0.8.19/con ac s.h ml.
1.3. P og amming Languages 9
Con ac s. They can be seen as Ja a o C++ classes. They ep esen he
sma con ac deployed a he ne wo k wi h i s s a e a iables, unc ions, and
cons uc o . They a e de ined using he con ac keywo d, and, as shown in
Figu e 1.2, hey usually ha e he ollowing s uc u e:
•Decla a ion o i s s a e a iables ha may include a de aul alue (Lines
2 and 3).
•Cons uc o , a unc ion decla ed wi h he cons uc o keywo d only
execu ed when he con ac is c ea ed (Lines 5 o 7). I no decla ed, he
con ac has an implici cons uc o wi h no pa ame e s.
•Func ions o he con ac (Lines 9 o 11).
1con ac C {
2uin size;
3uin [] a;
4
5cons uc o (uin _size) {
6size = _size;
7}
8
9 unc ion ge Fi s () public iew e u ns (uin ) {
10 e u n a[0];
11 }
12 }
Figu e 1.2: Example o Solidi y sma con ac
Abs ac con ac s. Con ac s ha a e used as he base o implemen o he
con ac s. They con ain a leas one unc ion ha is no implemen ed, and
hey canno be deployed. They a e decla ed using he abs ac keywo d
be o e he con ac keywo d.
In e aces. Simila o abs ac con ac s, bu canno p o ide he implemen a-
ion o he unc ions de ined. They a e decla ed using he in e ace keywo d.
Lib a ies. Lib a ies a e a special kind o con ac ha con ains eusable code.
They a e usually deployed only once on he blockchain, and hei code is used
by o he con ac s using unc ion calls. They a e decla ed using he lib a y
keywo d.
On Solidi y, he ollowing alue ypes can be used:
Booleans wi h wo possible alues: ue o alse.
16 Chap e 1. E he eum
The a ay is a e e ence ype con aining elemen s o a speci ic ype. In Solidi y,
p og amme s can de ine a ays o any alue, e e ence, mapping, o unc ion ype.
They can be loca ed in memo y, callda a, o s o age and can ha e a s a ic o dynamic
size.
1con ac C {
2uin [4] a ayA; // Fixed-size a ay
3uin [] a ayB = [1,2]; // Fixed-size a ay
4uin [] a ayC; // Dynamic a ay
5
6 unc ion (uin size, uin [] callda a callA ay, uin [5] callda a
callA ayB) public {
7uin [5] memo y memA ayA;
8in [] memo y memA ayB = new in [](size);
9bool[] memo y memA ayC;
10 memA ayC = new bool[](size);
11
12 o (uin i = 0; i < size; i++)
13 {
14 a ayC.push(i);
15 a ayC.pop();
16 }
17
18 uin leng h = a ayC.leng h;
19 alue = a ayC[0];
20 uin [] memo y slice = callA ay[1:4];
21 }
22 }
Figu e 1.8: Example o a ays in Solidi y
Memo y. A ays in memo y a e c ea ed inside he body o a unc ion using a
local a iable poin e . They a e decla ed in wo di e en ways, depending on how
hei size is se . In unc ion (Lines 6 o 21 o Figu e 1.8), we can obse e he
di e en ways o decla ing a memo y a ay. A ays alloca ed in memo y always
ha e a ixed size ha can be se s a ically (Line 7) o dynamically (Line 8 o Lines
9 and 10). Like any memo y alue, hey a e alloca ed on c ea ion, s a ing a he
i s ee memo y posi ion, whe e he leng h is s o ed, and consecu i ely s o ing all
he a ay alues. In he case o dynamic size a ays, hei local a iable (Line 9)
ini ially poin s o he ze o memo y slo (0x60) while hey a e no ini ialized (Line
10).
Callda a. A ays in callda a a e only eadable and a e used as a gumen s o e u n
alues o con ac unc ions. Callda a a ays can ha e a s a ic o dynamic immu able
1.5. A ays access in E he eum 17
size. I hey ha e a dynamic size, hei leng hs a e calcula ed based on he ange
o add esses i comp ises in he callda a egion. Line 6 o Figu e 1.8 shows he
decla a ion o a dynamic and a s a ic callda a a ays as unc ion a gumen s .
S o age. A ays alloca ed in s o age a e c ea ed as con ac s a e a iables wi h
a ixed o dynamic size. In he con ac o Figu e 1.8, we can obse e he wo ways
o decla ing a ixed-size a ay in s o age: wi hou ini ializing i s alues (Line 2) o
ini ializing i s alues (Line 3). Addi ionally, a Line 4, we can see he decla a ion o a
dynamic a ay. Dynamic a ays can only be decla ed in s o age and can pe o m he
push and pop ope a ions in o de o append o emo e a alue a he las posi ion
o he a ay.
In Solidi y, a ays can be accessed in h ee di e en ways:
Leng h access. The numbe o elemen s o he a ay can be consul ed using
he leng h membe o he a ay poin e . A Line 18 o Figu e 1.8, we can
obse e an example o leng h access o an a ay.
Index access. The elemen s o he a ay can be accessed using hei index
(<a ay base>[index]), as shown a Line 19 o Figu e 1.8.
Index Range access. A subse o con inuous elemen s o he a ay can be
ob ained using hei index ange (<a ay base>[ om: o]), as shown a
Line 20 o Figu e 1.8. Index ange accesses a e only a ailable o dynamic
callda a a ays.
In Solidi y sma con ac s, an ou -o -bounds check is always pe o med when
accessing an a ay by index. This check compa es he index being accessed wi h he
a ay leng h, aising an excep ion i he index is no lowe . Ou -o -bounds checking
helps o p o ide sa e code, a oiding o e lows on a ay accesses. Howe e , hey also
ha e a nega i e impac on gas consump ion. When accessing memo y o s o age
a ays wi h a dynamically se leng h (dynamic a ays o ixed-size a ays wi h size
se a un ime), hei leng h mus be loaded in o de o pe o m he bounds check.
The e o e, on each access, wo loads ha e o be done: he leng h o he a ay and
he alue being accessed. This makes index accesses e y expensi e, especially in
he case o s o age a ays. The leng h load is no equi ed o ixed-size a ays wi h
s a ically se sizes since hei leng h is known a compile ime. The e is also a gas
consump ion inc ease o all a ay indexes accessed due o all he o he ins uc ions
pe o med du ing he check.
In his p ojec , we will p opose wo di e en op imiza ions o he a ay index
access o educe i s gas consump ion by a oiding he leng h load needed o he
ou -o -bounds checks.
Chap e 2
The Solidi y Compile
In o de o de ine a compile , we will quo e he de ini ion gi en by he classic e -
e ence book on compile echnology, Compile s: p inciples, echniques, and ools [1]
popula ly known as he D agon Book:
A compile is a p og am ha can ead a p og am in one language, he
sou ce language, and ansla e i in o an equi alen p og am in ano he
language, he a ge language. [1, p. 1]
The compila ion o a p og am is a complex p ocess composed o di e en phases.
The adi ional phases o he compila ion p ocess, as p esen ed in he D agon Book
and shown in Figu e 2.1, a e:
Lexical Analysis. I is he i s phase o he compila ion p ocess. Du ing his
phase, he compile p ocesses he sou ce p og am as a s eam o cha ac e s,
g ouping hem in o lexemes s o ed as okens.
Syn ax Analysis o Pa sing. The compile gene a es a ee s uc u e ep-
esen ing he s uc u e o he ob ained okens ollowing he sou ce language
g amma . This s uc u e is called he syn ax ee.
Seman ic Analysis. The compile checks ha he code complies wi h he
seman ic ules o he sou ce language.
In e media e Code Gene a ion. This op ional phase is whe e he compile
may gene a e an in e media e ep esen a ion (IR) om he syn ax ee.
Code Op imiza ion. Du ing his phase, he compile ans o ms he in e -
media e code in o de o be able o gene a e a mo e e icien a ge code. The
op imiza ions in his phase a e machine-independen since hey ans o m he
in e media e ep esen a ions wi hou in ol ing speci ic de ails o he a ge ed
19
20 Chap e 2. The Solidi y Compile
machine as egis e s o memo y alloca ion.
Code Gene a ion. The compile maps he in e media e ep esen a ion (o
he syn ax ee in case he IR was no gene a ed) in o he a ge code. Du ing
his phase, he compile is in cha ge o he egis e alloca ion o he gene a ed
a iables o hei posi ion on he s ack in he case o s ack-based machines (as
he EVM).
Figu e 2.1: Phases o he compila ion p ocess om he D agon Book [1]
Finally, he a ge code gene a ed may be subjec o machine-dependen op i-
miza ions ha ans o m he code o achie e a be e pe o mance based on ea u es
speci ic o he a ge ed machine.
In his chap e , we will in oduce he compila ion o Solidi y sma con ac s in o
he inal by ecode execu ed by he E he eum Vi ual Machine. As we will see, he
compile p ocess esembles he adi ional phase di ision p e iously p esen ed, wi h
minimal a ia ions. This explana ion o he Solidi y compile will mainly ocus on
he compile ea u es and phases ha a e modi ied o ex ended in he implemen a-
ion o ou p oposed op imiza ions and which will be men ioned in la e chap e s.
2.1. Phases o he Solidi y Compile 21
2.1. Phases o he Solidi y Compile
The Solidi y compile is he so wa e ha eads a p og am in Solidi y and ans-
la es i in o an equi alen p og am in EVM by ecode. The compile was eleased
in 2014 wi h he publica ion o he Solidi y language by he E he eum Founda ion.
I is an open-sou ce compile ha can be consul ed in i s Gi Hub eposi o y [15],
whe e communi y con ibu o s help o de elop and imp o e i , led by he E he eum
Founda ion o icial de elope s.
The Solidi y compile is cons an ly e ol ing o adap i sel o he changes in
he EVM and he Solidi y language. A he momen o his p ojec , he Solidi y
compile is in e sion 0.8.19.
The compile , w i en in C++, is a complex p og am consis ing o se e al mod-
ules ha handle di e en phases o he compila ion p ocess. Figu e 2.2 illus a es
he main phases o a Solidi y sma con ac compila ion.
Pa se Analyze
Sou ce
code in
Solidi y
By ecode
IR code
ASM code
AST Checked AST Gene a e and
Op imize
Figu e 2.2: Phases o he Solidi y compile
In his sec ion, we will e iew he mos ele an compile phases and modules,
he unde s anding o which is c i ical o he op imiza ions we will pe o m in bo h
he Solidi y language and he compile .
2.1.1. Pa sing
Pa sing is he i s phase o he compila ion p ocess o a Solidi y sma con ac .
Du ing his phase, he compile gene a es an in e nal ep esen a ion o he code con-
aining all he in o ma ion included in he sou ce iles. This in e nal ep esen a ion,
called Abs ac Syn ax T ee (AST), will be used in he ollowing phases o in e p e ,
analyze and gene a e he EVM by ecode.
22 Chap e 2. The Solidi y Compile
2.1.1.1. Abs ac Syn ax T ee
The Abs ac Syn ax T ee (AST) is a hie a chical ep esen a ion o he code
con aining he in o ma ion needed o analyze he sou ce code and gene a e he
machine- eadable code. Du ing his phase, he compile gene a es an AST o each
sou ce ile.
1p agma solidi y >=0.8.4;
2
3con ac C {
4uin [] a;
5
6 unc ion () public iew e u ns (uin ) {
7 e u n a[0] + 2;
8}
9}
Figu e 2.3: Example o Solidi y sma con ac
We will use he minimal code shown in Figu e 2.3 as a unning example o his
sec ion. The AST gene a ed by he compile when compiling he code in Figu e 2.3
is ep esen ed in Figu e 2.5.
E e y AST node o he Solidi y compile has he ollowing a ibu es:
An iden i ie o he AST node ha is unique.
The loca ion in he sou ce ile.
An Anno a ion objec ha con ains in o ma ion abou he objec ype and
o he anno a ions.
Apa om hose a ibu es, all AST nodes ha e he ollowing me hods:
The == and != ope a o unc ions ha check i wo nodes ha e he same id.
An accep unc ion o be a e sed by a isi o (checke s o code gene a o s).
The AST o a gi en sou ce ile can be expo ed as a JSON using he –as -compac -
json command line op ion o he cu en compile . In Figu e 2.4, we can see pa o
he gene a ed JSON ep esen ing AST o he add exp ession in he unc ion de ined
in Figu e 2.3.
2.1. Phases o he Solidi y Compile 23
1"exp ession":{
2"commonType":{" ypeIden i ie ":" _uin 256"," ypeS ing":"uin 256"},
3"id":15,
4"isCons an ": alse,"isLValue": alse,"isPu e": alse,"
lValueReques ed": alse,
5"le Exp ession":{
6"baseExp ession":{
7"id":11, "name":"a",
8"nodeType":"Iden i ie ",
9"s c":"154:1:0",
10 " ypeDesc ip ions":{" ypeIden i ie ":"
_a ay$_ _uin 256_$dyn_s o age"," ypeS ing":"uin 256[] s o age
e "}
11 },
12 "id":13,
13 "indexExp ession":{
14 "id":12, "name":"i",
15 "nodeType":"Iden i ie ",
16 "s c":"156:1:0",
17 " ypeDesc ip ions":{" ypeIden i ie ":" _uin 256"," ypeS ing":"
uin 256"}
18 },
19 "isCons an ": alse,"isLValue": ue,"isPu e": alse,
20 "lValueReques ed": alse,
21 "nodeType":"IndexAccess",
22 "s c":"154:4:0",
23 " ypeDesc ip ions":{" ypeIden i ie ":" _uin 256"," ypeS ing":"
uin 256"}
24 },
25 "nodeType":"Bina yOpe a ion",
26 "ope a o ":"+",
27 " igh Exp ession":{
28 "id":14,
29 "isCons an ": alse,"isLValue": alse,"isPu e": ue,
30 "kind":"numbe ","lValueReques ed": alse,
31 "nodeType":"Li e al",
32 "s c":"161:1:0",
33 " ypeDesc ip ions":{" ypeIden i ie ":" _ a ional_2_by_1"," ypeS ing
":"in _cons 2"},
34 " alue":"2"
35 },
36 "s c":"154:8:0",
37 " ypeDesc ip ions":{" ypeIden i ie ":" _uin 256"," ypeS ing":"
uin 256"}
38 }
Figu e 2.4: Example o AST Exp ession node ep esen ed as JSON
24 Chap e 2. The Solidi y Compile
Roo
P agmaDi ec i e
nodesnodes
Con ac De ini ion
ypeName
Va iableDecla a ion
pa ame e e u nPa ame e s
body
Func ionDe ini ion
s a emen s
Block
pa ame e s
Pa ame e Lis
pa ame e s
Pa ame e Lis
ypeName
Va iableDecla a ion
Elemen a yTypeName
exp ession
Re u n
le Exp ession igh Exp ession
Bina yOpe a ion
baseExp ession indexExp ession
IndexAccess Li e al
baseType
A ayTypeName
Elemen a yTypeName
ypeName
Va iableDecla a ion
Elemen a yTypeName
Iden i ie Iden i ie
Figu e 2.5: Example o he AST o a con ac
Visi o pa e n. The compile implemen s he Visi o Pa e n [17] in o de o
allow he di e en analyze s and code gene a o s o a e se he AST. In o de
o implemen his pa e n, classes ASTVisi o and ASTCons Visi o 1a e de ined,
p o iding a de aul implemen a ion o he me hods o isi each kind o AST Node,
as shown in Figu e 2.6.
The compile analyze s and code gene a o s, which will be discussed in la e
sec ions, inhe i om ei he he ASTVisi o o ASTCons Visi o classes. Each o
hem o e w i es he isi me hods o pe o m i s co esponding ac ions o e he
sou ce code elemen s ep esen ed by each AST node. The use o his pa e n makes
he AST ully modula and simpli ies he ex ension and modi ica ion o he AST
nodes, as well as he ex ension o e e y module ha wo ks o e he AST (i.e., ype
checking o IR gene a ion).
1Sou ce code a ailable a h ps://gi hub.com/ja ie Sande/solidi y/blob/de elop/
libsolidi y/as /ASTVisi o .h
2.1. Phases o he Solidi y Compile 25
1 i ual bool isi (Block& _node) { e u n isi Node(_node); }
2 i ual oid endVisi (Block& _node) { endVisi Node(_node); }
3
4/// Gene ic unc ion called by de aul o each node, o be
o e idden by de i ed classes
5/// i beha io unspeci ic o a node ype is desi ed.
6 i ual bool isi Node(ASTNode&) { e u n ue; }
7/// Gene ic unc ion called by de aul o each node, o be
o e idden by de i ed classes
8/// i beha io unspeci ic o a node ype is desi ed.
9 i ual oid endVisi Node(ASTNode&) { }
Figu e 2.6: Example o de aul me hods used by he AST isi o s
Rele an AST nodes. While o e 60 di e se ypes o AST nodes a e used o
ep esen di e en syn ac ic elemen s o sou ce code, i is beyond he scope o his
documen o desc ibe all o hem in de ail. Ins ead, we will ocus on he mos
pe inen ypes o ou compile modi ica ions.
S a emen node. The AST S a emen node is one o he mos basic ypes
o nodes in he Solidi y AST. I se es as a base o ep esen a wide ange
o di e en code s a emen s, such as a iable decla a ions, unc ion calls, o
con ol low s a emen s (i -else o loop cons uc ions). Each possible code
s a emen is ep esen ed by a co esponding AST node ha inhe i s om he
S a emen node. Figu e 2.7 shows an example o a s a emen ha ep esen s
a e u n s a emen (Re u n class).
1con ac C {
2uin [] a;
3
4 unc ion () public iew e u ns (uin ) {
5 e u n a[0] + 2;
6}
7}
Figu e 2.7: Example o s a emen
Block. The AST Block node is one o he mos ele an AST nodes o he
compile in he con ex o his p ojec . A block is a ype o s a emen con-
aining a g oup o ze o o mo e code s a emen s enclosed wi hin cu ly b aces.
I ep esen s di e se s uc u es such as he body o con ac s, unc ions, i -else
s a emen s, o loops. Addi ionally, blocks can also con ain o he nes ed blocks.
32 Chap e 2. The Solidi y Compile
All he gene a ed code is s eamed in o a single s ing a iable ha is la e pa sed
in o a Yul AST3 o be analyzed. Finally, i he –op imize lag is se , he IR code is
op imized using he Yul op imiza ion module explained in Sec ion 2.2.1.2.
2.1.3.2. EVM Assembly gene a ion
The gene a ion o EVM assembly code, o ASM code, is he p e ious s ep o
he inal bina ies gene a ion. The assembly code is a human- eadable low-le el
ep esen a ion o he ins uc ions ha he EVM will execu e. ASM code can be
gene a ed di ec ly om he Solidi y sou ce code o om he gene a ed IR code
(– ia-i ).
Gene a e om sou ce code. By de aul , he assembly code o he sma con-
ac s is gene a ed di ec ly om he Solidi y sou ce code, using he AST gene a ed
a he pa sing phase and comple ed du ing he analysis phase. In o de o ans-
o m he code s uc u es in o assembly code, he compile uses wo di e en me hods
depending on he complexi y and usage equency o he s uc u e:
T ans o m s a emen s di ec ly o assembly code, as shown in Figu e 2.15.
1m_con ex << dupIns uc ion(1 + _s ackDep h);
2swi ch (_a ayType.loca ion())
3{
4case Da aLoca ion::CallDa a:
5// leng h is s o ed on he s ack
6b eak;
7case Da aLoca ion::Memo y:
8m_con ex << Ins uc ion::MLOAD;
9b eak;
10 case Da aLoca ion::S o age:
11 m_con ex << Ins uc ion::SLOAD;
12 i (_a ayType.isBy eA ayO S ing())
13 m_con ex .callYulFunc ion(m_con ex .u ilFunc ions().
ex ac By eA ayLeng hFunc ion(), 1, 1);
14 b eak;
15 }
Figu e 2.15: Compile code exce p ha illus a es he di ec ans o ma ion o
assembly
3The Yul Abs ac Syn ax T ee is a syn ax ep esen a ion o he Yul code simila o he one
used o Solidi y code, bu much simple wi h only 18 ypes o nodes. See h ps://gi hub.com/
e he eum/solidi y/blob/28593839d9913a740e9c8514d2ba607241d54398/libyul/AST.h o
mo e in o ma ion
2.1. Phases o he Solidi y Compile 33
Use p ede ined unc ion empla es w i en in Yul, as in he IR gene a ion, and
gene a e he co esponding assembly code. This me hod is used o ans o m
complex in e nal ope a ions such as copying an a ay om s o age o memo y,
as in he example shown in Figu e 2.16. The p ede ined Yul empla es a e also
used o unc ions in cha ge o ABI4encoding, decoding, and ype con e sions.
1m_con ex .callYulFunc ion(m_con ex .u ilFunc ions().
copyBy eA ayToS o ageFunc ion(_sou ceType, _ a ge Type), 3, 0);
Figu e 2.16: Compile code exce p ha illus a es he usage o p ede ined Yul
unc ion
Gene a e om IR. The EVM assembly gene a ion om he IR code (Yul) is
ela i ely s aigh o wa d. Since bo h ep esen a ions ope a e a a simila ly low
le el, each Yul s a emen can be ansla ed in o only a ew assembly ins uc ions.
Howe e , when gene a ing he assembly code, he compile has o ack he e olu ion
o he s ack size and he posi ion o each a iable on i , making his p ocess highly
complex.
In o de o pe o m he code ans o ma ion, he compile uses he p e iously
gene a ed AST o he IR, isi ing each node and appending he ans o ma ions
in o an Assembly objec con aining he inal assembly code. Figu e 2.17 shows an
example o a unc ion used o ans o m an i s uc u e in Yul o assembly code.
1 oid CodeT ans o m::ope a o ()(I cons & _i )
2{
3 isi Exp ession(*_i .condi ion);
4m_assembly.se Sou ceLoca ion(o iginLoca ionO (_i ));
5m_assembly.appendIns uc ion(e masm::Ins uc ion::ISZERO);
6Abs ac Assembly::LabelID end = m_assembly.newLabelId();
7m_assembly.appendJumpToI (end);
8(* his)(_i .body);
9m_assembly.se Sou ceLoca ion(o iginLoca ionO (_i ));
10 m_assembly.appendLabel(end);
11 }
Figu e 2.17: Compile code exce p ha illus a es he ans o ma ion om IR o
assembly
4See mo e abou he ABI speci ica ion a h ps://docs.solidi ylang.o g/en/ 0.8.19/
abi-spec.h ml
34 Chap e 2. The Solidi y Compile
2.1.3.3. By ecode gene a ion
The by ecode gene a ion is he las phase o code gene a ion in he compile . In
his phase, he assembly code is linked and assembled in o he c ea ion and un ime
by ecode. The gene a ed by ecode is he lowes -le el language p oduced by he
compile , he hexadecimal ep esen a ion o he EVM ins uc ions, as he example
shown in Figu e 2.18.
6080604052348015600 57600080 d5b506004361060285760003560e01c806326121 014
602d575b600080 d5b60336047565b604051603e91906072565b60405180910390 35b60
0060026000546056919060ba565b905090565b6000819050919050565b606c81605b565b
82525050565b6000602082019050608560008301846065565b92915050565b7 4e487b71
000000000000000000000000000000000000000000000000000000006000526011600452
60246000 d5b600060c382605b565b915060cc83605b565b925082820190508082111560
e15760e0608b565b5b9291505056 ea2646970667358221220148429967791ea8a3 39c34
3c7247dc5662860 0c6e71d1c1440a899503ee0ac64736 6c637827302e382e32302d63692
e323032322e31302e382b636 6d6d69742e65376430363665342e6d6 640058
Figu e 2.18: Run ime by ecode o he con ac o Figu e 2.3
In addi ion o gene a ing EVM by ecode as a sequence o hexadecimal opcodes,
he Solidi y compile can also ou pu a human- eadable ep esen a ion o he EVM
ins uc ions. This ou pu can be gene a ed using he command-line op ion –opcodes.
Figu e 2.19 shows an example o he opcode ep esen a ion o he by ecode.
1PUSH 80
2PUSH 40
3MSTORE
4CALLVALUE
5DUP1
6ISZERO
7PUSH 0x0
8JUMPI
9PUSH 0
Figu e 2.19: Opcodes ep esen a ion o he i s ins uc ions on Figu e 2.18
2.2. Code op imiza ions 35
2.2. Code op imiza ions
Du ing he code gene a ion, compile s y o gene a e a a ge code as e icien
as possible. In o de o do ha , he compile ans o ms he code in o a new, mo e
e icien code. Howe e code op imiza ion is no a i ial ask, as explained on he
ollowing pa ag aph ex ac ed om he D agon Book [1]:
The challenge is ha , ma hema ically, he p oblem o gene a ing an op-
imal a ge p og am o a gi en sou ce p og am is undecidable; many
o he subp oblems encoun e ed in code gene a ion such as egis e allo-
ca ion a e compu a ionally in ac able. In p ac ice, we mus be con en
wi h heu is ic echniques ha gene a e good, bu no necessa ily op imal,
code. Fo una ely, heu is ics ha e ma u ed enough ha a ca e ully de-
signed code gene a o can p oduce code ha is se e al imes as e han
code p oduced by a nai e one. [1, p. 505]
The e is a g ea a ie y o di e en code op imiza ions ha compile s can pe -
o m, a ge ing di e en le els o abs ac ion and a ge ing di e en objec i es, such
as ime e iciency, memo y e iciency, o a ge code size. We can dis inguish wo
main ypes o code op imiza ions on compile s:
Machine-independen code. These op imiza ions a e pe o med a an op i-
miza ion phase p io o he a ge code gene a ion, whe e he compile ans-
o ms he IR in o a new IR code om which a mo e e icien code can be
gene a ed. A his le el, he op imiza ions a e no ied o speci ic ea u es o
he a ge ed a chi ec u e, such as egis e o memo y alloca ion.
Machine-dependen code. These op imiza ions a e pe o med o e he a -
ge code a he end o he code gene a ion p ocess. A his le el, op imiza ions
a e ied o he speci ic ea u es o he a ge ed a chi ec u e, such as he s ack
alloca ion on he EVM.
In he E he eum blockchain, he e iciency o sma con ac s is c i ical. The
execu ion o each con ac call has an associa ed gas cos which ansla es di ec ly
in o an economic cos o he use . In a ne wo k whe e hund eds o housands o
con ac calls a e pe o med daily, educing he execu ion cos o con ac calls is
c ucial o de elope s, con ac owne s, and clien s, especially when dealing wi h
la ge-scale sma con ac s. Acco dingly, he e is a high in e es in gene a ing he
mos e icien code possible ega ding gas consump ion, and he code op imiza ion
p ocess o any code a ge ing he EVM is subjec o in ense esea ch.
In his sec ion, we will discuss he s a e o he a on code op imiza ions in
E he eum. On he one hand, we will in oduce he wo op imiza ion modules in
he Solidi y compile , which espec i ely pe o m ans o ma ions on he IR and
gene a ed code in o de o ou pu he mos e icien code possible. On he o he
36 Chap e 2. The Solidi y Compile
hand, we will co e some p oposed wo k on p e and pos -gene a ion op imiza ions
o code a ge ing he EVM.
2.2.1. Solidi y compile op imiza ions
The Solidi y compile has wo di e en op imize modules ha op imize he
gene a ed code in o de o make i mo e e icien in e ms o execu ion cos and code
size. The op imize modules o he compile ope a e a wo di e en le els. The ‘old’
module ope a es a he opcode le el and ocuses on pe o ming small ans o ma ions
on he gene a ed code in o de o imp o e i s e iciency. In con as , he ‘new’
op imize ope a es a he IR code le el and plays he ole o he machine-independen
code op imiza ion module ans o ming he IR du ing he code gene a ion p ocess.
On he cu en compile e sion, bo h op imiza ion modules a e disabled by de-
aul and can be ac i a ed using he command line pa ame e –op imize. Addi ion-
ally, we can use he pa ame e –op imize- uns o indica e an app oxima e numbe
o imes he con ac is expec ed o be execu ed ac oss i s li e ime. This expec ed
numbe o execu ions allows de elope s o es ablish on he op imize a adeo be-
ween he code size, which a ec s he deploymen cos , and he execu ion gas cos
once deployed. In a con ac ha will be used only a ew imes, he compile will
p io i ize p oducing a sho e code o e he execu ion cos educ ion. In con as ,
o con ac s ha will be execu ed many imes, he op imize will gene a e mo e
e icien code wi hou ca ing abou he leng h o he inal op imized code. Howe e ,
an op imized con ac will p obably consume less gas o deploymen as well as o
unc ion calls.
2.2.1.1. Opcode op imize
The opcode op imize was he i s code op imize implemen ed in he Solidi y
compile . I ope a es a he opcode (by ecode) le el applying simpli ica ion ules
and emo ing unused and duplica ed code. The opcode op imiza ion akes place a
he end o he code gene a ion p ocess, ans o ming he gene a ed by ecode in o a
mo e e icien by ecode. The e o e, his module i s in o he de ini ion o a machine-
dependen code op imize since i wo ks di ec ly on he a ge code ins ead o he
IR.
The op imize di ides he sequence o ins uc ions on blocks delimi ed by JUMP
ins uc ions. Then i analyzes he ins uc ions inside hose blocks, keeping ack o
he s ack, memo y, o s o age modi ica ions. Finally, i applies se e al op imiza ion
phases in a loop un il no op imiza ion is possible. The op imiza ions applied a e:
FullInline : eplaces jumps o blocks con aining simple ins uc ions wi h a
copy o he ins uc ions in he block.
2.2. Code op imiza ions 37
Jumpdes Remo e : emo es unused JUMPDEST ins uc ions and hei e e enced
ags.
PeepholeOp imise : op imizes small windows o ins uc ions, eplacing hem
wi h a mo e e icien sequence o ins uc ions ha p oduces he same esul .5
BlockDeduplica o : uni ies duplica ed blocks.
CommonSubexp essionElimina o : inds and combines equal exp essions.
Cons an Op imise : eplaces cons an exp essions by hei compu ed alues
a compile ime.
The opcode op imize module can be e y e ec i e a applying simple op imiza-
ions o he by ecode, educing he gas consump ion o a con ac . Howe e , i has
some limi a ions. Because i ope a es on a e y low le el, i has limi ed in o ma ion
and unde s anding o he code. I can op imize small se s o by ecode ins uc ions
bu canno pe o m op imiza ions o high-le el s uc u es. Fu he mo e, because
he low-le el code is excep ionally complex o in e p e , implemen ing new op i-
miza ions and p o ing i s co ec ness is e y challenging. Fo ou pu pose, i would
be almos impossible o de elop an op imiza ion s ep o a ay accesses, as i would
be e y di icul o speci ically a ge he by ecode sec ions co esponding o op i-
mizable a ay accesses, and e e y change on he by ecode o op imize he accesses
would ha e side-e ec s on he s ack o he EVM.
2.2.1.2. Yul op imize
The Yul op imize [14] was in oduced in e sion 0.4.20 o he compile [7]. I is
an op imiza ion module ha ope a es on Yul code ( he IR) and se es he ole o
he machine-independen code op imize ans o ming he IR code du ing he code
gene a ion p ocess in a way i leads o a mo e e icien gene a ed by ecode.
This module is much mo e powe ul han he opcode op imize . Since i ope a es
a a highe le el o abs ac ion, i can pe o m mo e sophis ica ed op imiza ions
aking ad an age o he seman ics o he con ac code. Fu he mo e, because he e
is no possibili y o pe o ming a bi a y jumps in Yul, he op imize can compu e he
side e ec s o each unc ion call. This allows he op imize o pe o m sophis ica ed
op imiza ions, such as code eo de ing o e en unc ion call emo al. Finally, because
i ope a es a a highe le el o abs ac ion, i is easie o de elope s o unde s and,
main ain and ex end he op imize . Now, de elope s do no ha e o igu e ou how
o a ge op imizable pa e ns on he EVM assembly code no deal wi h he side
e ec s o he op imiza ions on he s ack. This module gene a es an op imized IR
code ha he compile will ans o m in o ASM code. Consequen ly, i he op imized
5Read mo e abou he peephole op imiza ion in he D agon Book [1, p. 549]
38 Chap e 2. The Solidi y Compile
IR code is equi alen o he o iginal IR code, he gene a ed ASM code is gua an eed
o be equi alen o he ASM code ha would be gene a ed om he o iginal code.
The Yul op imize pe o ms a p ede ined sequence o op imiza ion s eps o he
AST o he gene a ed IR, ans o ming i o op imize he code o o allow u he
op imiza ions. This se o s eps can be pe sonalized by he de elope using he
–yul-op imiza ions command-line pa ame e . These a e some o he mos ele an
op imiza ion s eps de ailed in he Yul op imize documen a ion [14]:
LoadResol e : eplaces loads om memo y o s o age o i s alue i known.
DeadCodeElimina o : emo es un eachable code.
EqualS o eElimina o : emo es s o e ins uc ions o memo y o s o age i
he e is an iden ical call wi hou any changes on he pa ame e alues in be-
ween.
LoopIn a ian CodeMo ion: mo es a iable decla a ions ou side he loop i
such a iables emain cons an du ing he loop and ha e only ead side e ec s
o no side e ec s.
Fo LoopCondi ionIn oBody: mo es he condi ion exp ession o he loop in o
he body.
Exp essionInline and FullInline : eplace unc ion calls wi h a copy o
he co esponding unc ion body.
When he op imiza ion op ion on he compile is ac i a ed, he Yul op imiza ion
can ake place in wo di e en phases o he compila ion p ocess.
De aul ASM gene a ion. In he case he – ia-i lag is no se , he EVM
assembly code is di ec ly gene a ed om he o iginal Solidi y code, as seen
in sec ion 2.1.3.2. Howe e , as explained in he p e iously men ioned sec ion,
his code gene a ion p ocess uses, in some cases, p ede ined unc ion empla es
coded in Yul. When he op imiza ions a e ac i a ed, he gene a ed Yul unc-
ions om hose empla es and he Yul code inside he inline assembly blocks
will be op imized by he Yul module be o e being ans o med in o EVM as-
sembly code. In his scena io, he Yul op imiza ion has a limi ed e ec on
he inal ASM code and, consequen ly, he by ecode. This is because i only
op imizes small independen sec ions o he con ac bu does no op imize he
con ac as a whole.
ASM gene a ion ia IR. I he – ia-i lag is se , he IR code is used o
gene a e he EVM assembly code. The e o e, when he op imiza ions a e en-
abled, he Yul op imize module will op imize he IR code, and his op imized
IR code will be used o gene a e he EVM assembly code. Consequen ly, in
2.2. Code op imiza ions 39
his scena io, he Yul op imize has a much mo e signi ican impac on he
code because all he code will be op imized as a whole, being able o cap u e
ela ions be ween all he elemen s o he code.
2.2.2. Rela ed wo k on code op imiza ions
In addi ion o he compile op imiza ion modules, de elope s can ind a g ea
a ie y o ex e nal op imiza ion ools ocused on imp o ing e iciency in E he eum
sma con ac s.
A ele an example o ex e nal op imiza ions o EVM code is GASPER, an op i-
miza ion ool p oposed in he a icle Unde -Op imized Sma Con ac s De ou You
Money [6]. In his a icle, a g oup o esea che s om di e en Chinese uni e si ies
desc ibed se en cos ly code pa e ns no being op imized by he Solidi y compile .
Those pa e ns we e sepa a ed in o wo ca ego ies. The useless code- ela ed pa e ns
ca ego y includes si ua ions whe e a nes ed condi ional e alua es o ue o o alse
unde all ci cums ances due o i s ela ion wi h he condi ion hey a e enclosed in o.
Besides, he loop- ela ed pa e ns collec simple loop pa e ns whe e expensi e ope -
a ions can be mo ed ou side he loop o duplica ed ope a ions can be combined o
emo ed. Finally, hey implemen ed GASPER, a ool ha au oma ically iden i ies
he code- ela ed pa e ns and expensi e ope a ions on loops, gi ing he de elope
aluable in o ma ion o op imize he code.
Ano he ele an wo k on he same a ea was p esen ed in Cha ac e izing E i-
ciency Op imiza ions in Solidi y Sma Con ac s [5], whe e a g oup o esea che s
om he Vienna Uni e si y o Technology analyze he applicabili y o 25 op imiza-
ion s a egies o Solidi y sma con ac s. Those s a egies a e di ided in o:
Time- o -Space Rules whe e memo y and s o age usage is educed by no
s o ing any alue ha can be compu ed when needed, which on he o he
hand, inc eases he execu ion ime.
Space- o -Time Rules whe e execu ion ime is educed by s o ing p ecom-
pu ed o equen ly used da a, which on he o he hand, inc eases he use o
memo y and s o age.
Loop Rules ha desc ibe s a egies o mo e code ou o he loop, o educe
he numbe o condi ional exp essions inside he loop body, and o usion loops.
Logic Rules ela ed o logic e alua ions. These ules exploi iden i y p ope -
ies, eo de e alua ions, p ecompu e condi ions, and eplace boolean a iables
wi h condi ion exp essions.
P ocedu e Rules ha educe he numbe o unc ions by pe o ming inlining,
40 Chap e 2. The Solidi y Compile
ans o ming i e a i e unc ions in o ecu si e unc ions o
Exp ession Rules ha exploi iden i ies emo e common subexp essions and
combine exp essions.
They concluded ha while no all o he s a egies discussed could be applied
o p og ams a ge ing EVM o p o iding gas cos educ ion, mos o hem, 21 ou
o 25, ha e di ec applicabili y o sma con ac s and ha e he po en ial o educe
gas consump ion.
Among hese examples o esea ch on sma con ac s op imiza ion, i is manda-
o y o men ion he esea ch ca ied ou by he Cos a G oup6, a esea ch g oup
o he Complu ense Uni e si y o Mad id, in which his wo k has been de eloped.
This g oup, dedica ed o he esea ch o op imiza ion, e i ica ion, and unde s and-
ing o p og ams, has ca ied ou ele an publica ions ela ed o sma con ac s
op imiza ion in ecen yea s.
An example o hei esea ch wo k is GASOL (Gas AnalysiS and Op imiza ion
ooL) [2], a gas analyze and op imize o sma con ac s. GASOL is a ool able o
analyze Solidi y unc ions acco ding o di e en cos models ha he p og amme
can selec . I in e s he gas cos associa ed wi h he a ge ed p og am as well
as he numbe o EVM ins uc ions ha will equi e. Mo eo e , his ool de ec s
op imizable pa e ns ela ed o s o age usage and op ionally gene a es an op imized
e sion o he Solidi y code. Op imiza ions consis o subs i u ing mul iple accesses
o he same s o age alue, which a e expensi e, by accesses o a copy o he alue
s o ed in memo y, which is conside ably cheape . Howe e , his ans o ma ion is
only iable when he cos o c ea ing he a iable copy and upda ing he o iginal
a iable wi h he inal alue is paid o by he sa ed gas on he memo y accesses.
Thus, i uses he cos analysis pe o med o e he code o de ec code sec ions whe e
his ans o ma ion educes gas cos s.
The analysis and op imiza ion capabili ies o e ed by GASOL make i an ex-
emely powe ul ool o de elope s seeking o c ea e e icien Solidi y sma con-
ac s.
The a icle In e ing Needless W i e Memo y Accesses on E he eum By ecode [3]
is ano he example o ex e nal op imiza ion de eloped by his g oup. This a icle
desc ibes a s a ic analyze ha de ec s unnecessa y memo y w i e ins uc ions on
he EVM by ecode. The desc ibed analyze iden i ies memo y slo alloca ion, eads
and w i es, and de ec s memo y w i e ins uc ions o access a memo y slo ha
is no being ead a e wa d. This pos -compila ion op imiza ion has p o ed o be
use ul in de ec ing op imiza ion oppo uni ies on eal sma con ac s, acco ding o
he esul s p o ided in he men ioned a icle.
6See mo e abou Cos a G oup a hei websi e: h ps://cos a. di.ucm.es/web/.
2.2. Code op imiza ions 41
I is wo h no ing ha he men ioned p oposals om he Cos a G oup ocus on
educing he execu ion cos by op imizing he usage o he memo y layou (s o age
o memo y) since he cos o loading o s o ing alues om s o age o memo y
o en causes a signi ican po ion o he o al gas expense. In line wi h his sha ed
mo i a ion, he ollowing chap e s will in oduce wo new op imiza ion p oposals o
educe gas consump ion on a ay accesses.
48 Chap e 3. Op ional Checking
Finally, we adap ed he block pa sing unc ion o he compile o he new
g amma . To do so, we added a new s ep, shown in Figu e 3.5, o check i he
uncheckedA ay oken p ecedes he b acke s ha open he block being p ocessed.
1bool cons uncheckedA ayBlock = m_scanne ->cu en Token() == Token::
UncheckedA ay;
Figu e 3.5: Modi ica ion on he pa se o he uncheckedA ay block
I is impo an o no e ha we ha e added a new pa se e o in his phase,
which is issued when an uncheckedA ay block is ound ou side a egula block.
Figu e 3.6 shows he in oduced pa sing e o .
1i (!_allowUncheckedA ayBlock)
2pa se E o (5297_e o , " " uncheckedA ay " blocks can only
be used inside egula blocks.");
3ad ance();
Figu e 3.6: New pa se e o
3.2.2.3. Syn ax checking
In o de o ensu e he co ec syn ax o uncheckedA ay blocks, he compile
mus check ha hey do no appea nes ed in he code. To do so, we ha e ex ended
he Syn axChecke wi h a a iable o ack when i is inside an uncheckedA ay
block. This a iable is upda ed when an uncheckedA ay block is accessed and
exi ed du ing he syn ax checking (pe o med using he isi o pa e n) and used
when an uncheckedA ay block is accessed o check i he accessed block is inside
ano he uncheckedA ay block. Addi ionally, we ha e added a check in he block
isi unc ion o gua an ee ha he isi ed uncheckedA ay block is no inside
ano he one.
3.2.2.4. Type checking
The uncheckedA ay block does no impac how ypes mus be checked wi hin
he block. The e o e, no modi ica ion is equi ed.
3.2. Unchecked A ay 49
3.2.2.5. Code gene a ion
Finally, he compile has been modi ied o gene a e he co ec code o index
accesses pe o med inside an uncheckedA ay block. Bounds checks on he a ay
index a ay accesses a e gene a ed a an IR o ASM le el, depending on whe he he
IR code is used o gene a e he ASM code. Consequen ly, we ha e only modi ied
how he a ay index accesses a e gene a ed in he IR and ASM code. As seen in
Chap e 2, he Solidi y compile has wo modules in cha ge o gene a ing hese
ep esen a ions: he IR gene a o and he ASM gene a o .
IR Code gene a ion. The IR code gene a ion o a ay index accesses uses p ede-
ined Yul u il unc ions. The e o e, new u il unc ions ha e been de ined o gene a e
he a ay accesses o each ype o memo y loca ion, as he one being shown in
Figu e 3.7.
1 unc ion < unc ionName>(a ay, index) -> slo , o se {
2<?mul ipleI emsPe Slo >
3<?isBy esA ay>
4swi ch l (a ayLeng h, 0x20)
5case 0 {
6slo , o se := <indexAccessNoChecks>(a ay, index)
7}
8de aul {
9o se := sub(31, mod(index, 0x20))
10 slo := a ay
11 }
12 <!isBy esA ay>
13 le da aA ea := <da aA eaFunc>(a ay)
14 slo := add(da aA ea, di (index, <i emsPe Slo >))
15 o se := mul(mod(index, <i emsPe Slo >), <s o ageBy es>)
16 </isBy esA ay>
17 <!mul ipleI emsPe Slo >
18 le da aA ea := <da aA eaFunc>(a ay)
19 slo := add(da aA ea, mul(index, <s o ageSize>))
20 o se := 0
21 </mul ipleI emsPe Slo >
22 }
Figu e 3.7: P ede ined Yul u il unc ion o a s o age index access inside an
uncheckedA ay block
Since hose new unc ions a e inse ed in he esul ing code by he IRCodeGene a o ,
using he in o ma ion om he AST node and he IRGene a ionCon ex , we ha e
50 Chap e 3. Op ional Checking
ex ended he con ex so he gene a o can de e mine whe he a ay access mus
include bounds checks. The solu ion is o include a new a iable wi h wo possible
enum alues: Checked o Unchecked. This a iable s o es he alue Unchecked while
he gene a o a e ses he nodes inside an uncheckedA ay block, and he alue
Checked o he wise. Then, he gene a o uses ha in o ma ion om i s con ex o
decide which p ede ined a ay access unc ion o inse , as shown in Figu e 3.8.
1m_con ex .uncheckedA ays() ?
2m_u ils.s o ageUncheckedA ayIndexAccessFunc ion(a ayType) :
3m_u ils.s o ageA ayIndexAccessFunc ion(a ayType))
Figu e 3.8: Call o gene a e a s o age a ay access in IR code
EVM assembly code gene a ion. The EVM assembly code gene a ion is highly
complex because o how local a iables a e ea ed on he limi ed s ack o he EVM
(Sec ion 1.4 Chap e 1). Fo una ely, he gene a ed code o mos o he basic op-
e a ions is p ede ined, as i is on he IR code gene a ion explained in he p e ious
pa ag aph. This is he case o a ay ope a ions such as push,pop, o leng h accesses,
whose gene a ed assembly code is de ined in he A ayU ils class.
The modi ica ions needed he e a e minimal as he unc ion in cha ge o gene -
a ing he a ay index access code al eady con empla ed he possibili y o no doing
bounds checks o e he a ay leng h. The o icial compile e sion uses his op ion
when he access is pa o o he la ge ope a ions, such as a push o an assignmen
o an a ay om memo y o s o age (copy o he a ay), whe e he soundness o
he a ay accesses is gua an eed by cons uc ion. The e o e, we ha e ex ended he
co esponding compile con ex , as we did wi h he IR gene a ion con ex , so he
Exp essionCompile can de e mine whe he o add he bounds checks o he EVM
assembly code. Figu e 3.9 shows he modi ica ion made on he gene a o code in
o de o enable o disable he checks on a ay accesses based on he in o ma ion o
he compile con ex .
1checkAccess = !m_con ex .uncheckedA ays();
2A ayU ils(m_con ex ).accessIndex(a ayType, checkAccess);
Figu e 3.9: Call o gene a e he EVM assembly code o a s o age a ay access
3.3. Ta ge ed Unchecked A ay
To inc ease he powe o his new gas-sa ing mechanism, we wan i o suppo
a ge ing speci ic a ays inside he block. Wi h his sligh imp o emen , de elope s
3.3. Ta ge ed Unchecked A ay 51
can include a he opening o he uncheckedA ay block a lis o he a ay bases
ha should no be checked on index access. The lis is op ional, and i i is no
p o ided, none o he a ays accessed inside he block will pe o m bounds checks.
In Figu e 3.10, we can see how his new ea u e o he uncheckedA ay block is
used.
1// SPDX-License-Iden i ie : BSD-4-Clause
2p agma solidi y >=0.8.4;
3
4con ac C {
5uin 256[] a A;
6uin 256[] a B;
7
8 unc ion (uin idx) pu e public e u ns (uin ) {
9// a A access will no check ou -o -bounds.
10 uncheckedA ay(a A) {
11 e u n a A[idx] + a B[idx];
12 }
13 }
14 }
Figu e 3.10: Example o usage o a ge ed uncheckedA ay block
3.3.1. Cons ain s
In addi ion o he uncheckedA ay block cons ain s (Sec ion 3.2.1), he e is
a signi ican limi a ion when a ge ing a ay accesses. Since exp essions canno be
e alua ed a compila ion ime, a ay bases ha e o be li e ally compa ed. The e o e,
a ay base exp essions need o be ans o med in o s ings o be compa ed.
To a oid possible misunde s andings, we ha e ex ended he compile wi h a new
wa ning, shown in Figu e 3.11. This wa ning ises when an exp ession di e en om
an iden i ie is lis ed as a a ge ed a ay base.
1Wa ning: The a ay accesses pe o med o e a base lis ed he e will
no pe o m index ou -o -bounds checks. Compa ison be ween a ay
bases is li e al. Only in hose accesses wi h he same li e al
base he uncehckedA ay will ake e ec .
2--> c.sol:11:22:
3|
411 | uncheckedA ay(ma ix[i]) {
5| ^^^^^^^^^
Figu e 3.11: Wa ning abou li e al compa isons o he a ge ed a ay bases
52 Chap e 3. Op ional Checking
3.3.2. Implemen a ion
The implemen a ion o he op ional a ge lis on he uncheckedA ay block
equi ed o ex end mos o he compila ion phases o iginally modi ied3. We had
o modi y he AST block node and he pa sing in o de o e ie e and s o e he
a ge s lis , he di e en analyze s o check ha each elemen in he lis is alid and
an a ay base, and inally, he code gene a o o only disable he bounds checks on
he accesses o a ge ed a ays when speci ied.
3.3.2.1. AST Rep esen a ion
In addi ion o he o iginal changes o he block node, we needed o ex end he
block node o s o e he lis o he a ge ed a ay bases when p o ided. In o de
o do ha , a ec o o exp essions has been added o he block a ibu es. Those
p o ided exp essions became hen child en o he block node in he AST. The e o e,
he accep unc ion ( isi o pa e n) o he block has also been modi ied o allow
he isi o s o access he a ay base lis . This ex ension is undamen al o ensu e
ha all he compile checks a e pe o med o e he elemen s o he a ge s lis .
Finally, a me hod nodeToS ing has been de ined o all he exp ession ype
nodes, so hey can be li e ally compa ed be ween hem (see 3.3.1). Figu e 3.12
shows an example o he nodeToS ing() me hods o ep esen membe accesses.
1ASTS ing cons Membe Access::nodeToS ing() cons {
2 e u n exp ession().nodeToS ing() + TokenT ai s:: oS ing(Token::
Pe iod) + membe Name();
3}
Figu e 3.12: Membe access nodeToS ing me hod
3.3.2.2. Pa sing
The only di e ence when pa sing his new e sion o he block is ha he
uncheckedA ay block can now ecei e a lis o pa ame e s be ween he iden i-
ie and he opening b aces o he block. The e o e, we ha e ex ended he g amma
wi h his new ea u e, as shown in Figu e 3.13, and modi ied he pa se phase. Now,
when he pa se inds he uncheckedA ay keywo d, i looks o an opening pa en-
hesis o pa se he a ge lis . I i ounds an opening b ace ins ead, i will ea
3All changes pe o med o he o iginal compile in o de o implemen his e sion o he
uncheckedA ay block he can be ound a h ps://gi hub.com/e he eum/solidi y/compa e/
de elop...ja ie Sande:solidi y: a ge edUncheckedA ay.
3.3. Ta ge ed Unchecked A ay 53
he block as an uncheckedA ay block whe e he bounds checks a e disabled on all
a ay index accesses.
1/**
2* A cu ly-b aced block o s a emen s. Opens i s own scope.
3*/
4block:
5LB ace ( s a emen | uncheckedBlock | uncheckedA ayBlock )*
RB ace;
6
7uncheckedBlock: Unchecked block;
8
9uncheckedA ayBlock:
10 UncheckedA ay block | UncheckedA ay LPa en (exp ession? ( Comma
exp ession?)* ) RPa en block;
Figu e 3.13: G amma o pa se blocks
3.3.2.3. Syn ax checking
This new ea u e o he uncheckedA ay block has no o he e ec on he syn-
ax checking han ex ending he checking o e he exp essions on he a ge s lis .
Howe e , his was al eady sol ed when we adap ed he accep unc ion o he block
node.
3.3.2.4. Type checking
When a lis o a ge s is speci ied in an uncheckedA ay block, he compile mus
pe o m ype-checking on he exp essions on ha lis . As wi h syn ax checking, his
was sol ed when we adap ed he accep unc ion o he block node. Howe e , we
also needed o implemen a new ype check o e he pa ame e lis o gua an ee
ha all he pa ame e s con o m o alid a ay bases. In o de o do ha , we ha e
modi ied he ype checke so i a e ses he lis o bases, checking ha i s ype
belongs o he A ay ca ego y and is no a s ing o by e a ay. Finally, we ha e
modi ied he checke so i aises he wa ning desc ibed in Sec ion 3.3.1 (Figu e 3.11)
whene e i inds on he a ge s lis an a ay base exp ession ha is no an iden i ie .
3.3.2.5. Code gene a ion
The only change in he code gene a ion is how he IR and EVM assembly code
gene a o s decide whe he a ay access mus include he bounds checks. Now, we
54 Chap e 3. Op ional Checking
ha e h ee possibili ies:
The uncheckedA ay block has no a ge s, so he bounds o all he a ays a e
unchecked.
The uncheckedA ay block has a lis o a ge s, so only he bounds o a ge ed
a ays a e unchecked.
We a e ou side any uncheckedA ay block, so he bounds o all he a ay
accesses a e checked.
Consequen ly, we ha e modi ied he gene a ion con ex s o be able o s o e he
equi ed in o ma ion o iden i y hese h ee scena ios. We keep he p e iously added
a iable, indica ing i we a e inside an uncheckedA ay block ha a ec s all he
a ays (Unchecked) o no (Checked), and a new ec o has been c ea ed in o de
o s o e he a ge ed bases, i any.
Now, he code gene a o will que y i s con ex whe he he a ay access mus
bypass bounds checks, as shown in Figu e 3.14. Wi h ou modi ica ions, he con ex
will now answe a i ma i ely i he code is in o an uncheckedA ay block wi hou
a ge s (whe e all accesses a e unchecked) o i he a ay base is li e ally equal o
one o he a ge s s o ed in he con ex .
1checkAccess = !m_con ex .isA ayUnchecked(baseExp ession);
2A ayU ils(m_con ex ).accessIndex(a ayType, checkAccess);
Figu e 3.14: Call o gene a e a s o age a ay access in EVM assembly code
3.4. Resul s and expe imen s
As explained a he beginning o his chap e , skipping he ou -o -bounds check-
ing on a ay index accesses educes he consumed gas. By doing his, we sa e he
cos o he leng h e ie al, he compa ison, and o he ins uc ions ha ake pa in
he bounds check.
Once we implemen ed he uncheckedA ay block o bypass such bounds checks,
we wan ed o quan i y he gas sa ings on a ay accesses. In o de o do ha , o each
kind o access (in s o age, memo y, and callda a), we ha e pe o med a s udy on he
bounds check by ecode, i s ins uc ions, and cos , quan i ying he heo e ical gas
sa ing o emo ing he check. Finally, we ha e execu ed di e en sma con ac s
o measu e he eal impac o he uncheckedA ay block.
3.4. Resul s and expe imen s 55
3.4.1. S o age gas sa ing
Since accessing s o age has he highes gas cos among all he possible memo y
accesses, we expec he uncheckedA ay block o ha e he mos impo an gas
educ ion when applied o s o age a ay accesses. In Figu e 3.15, we can obse e
he main pa o he bounds check in he EVM assembly code:
1DUP2
2SLOAD // Load leng h
3DUP2
4LT // Compa e
5PUSH2
60x75
7JUMPI // Jump o panic unc ion
Figu e 3.15: Example o EVM assembly code o bounds checks on s o age a ays
F om he obse ed code and acco ding o he cu en gas cos s published by he
E he eum ounda ion a EIP-2929 [8], by bypassing ha check, we will sa e gas by
no execu ing he ollowing ins uc ions:
Two DUP2 ins uc ions, wi h a cos o 3 gas uni s each.
A load om s o age (SLOAD), wi h a cos o 2100 uni s on he i s access o
he add ess and o 100 in la e accesses.
A compa ison (LT), wi h a cos o 3 gas uni s.
APUSH2 ins uc ion, wi h a cos o 3 gas uni s.
AJUMPI ins uc ion, wi h a cos o 10 gas uni s.
This esul s in an es ima ed gas sa e o 122 uni s. I is a heo e ical esul ,
and his gas-sa ing can be sligh ly di e en in p ac ice since o he ins uc ions may
be a oided o in oduced o keep ack o a iables in he s ack o he EVM, and
he s uc u e o EVM by ecode may be di e en , esul ing in a di e en di ision
o he code in o blocks and, consequen ly, a di e en numbe o jump ope a ions.
Addi ionally, i he a ay leng h has no been p e iously accessed, we will sa e 2100
gas uni s on he i s a ay access.
Expe imen al esul s. To measu e he gas sa ings using he uncheckedA ay
block, we ha e de eloped a simple benchma k. I comp ises a sma con ac wi h
an a ay in s o age and a unc ion ha i e a es ha a ay and compu es he sum
56 Chap e 3. Op ional Checking
o i s elemen s. This unc ion has wo e sions: one ha w aps he loop in an
uncheckedA ay block (Figu e 3.16) and ano he wi hou he uncheckedA ay
block.
1 unc ion accessS o age() public e u ns (uin ) {
2uin sum = 0;
3uncheckedA ay(a ay) {
4 o (uin 256 i = 0; i < a ay.leng h; i++)
5sum += a ay[i];
6}
7 e u n sum;
8}
Figu e 3.16: Tes ed unc ion
The benchma k has been execu ed se e al imes wi h di e en a ay leng hs,
showing he ollowing esul s:
I e a ions O iginal Gas Unchecked Gas Di Di pe I e a ion
1 26380 26279 101 101.00
10 51220 50012 1208 120.80
100 299620 287342 12278 122.78
1000 2783620 2660642 122978 122.98
Table 3.1: Gas sa ings on s o age accesses
In Table 3.1, we can see he esul s o execu ing he code shown in Figu e 3.16
wi h and wi hou he uncheckedA ay block o e a ays o 1, 10, 100, and 1000
elemen s. Resul s show ha as we inc ease he a ay size and, consequen ly, he
i e a ions o access he a ay, he sa ed gas pe i e a ion ends o be 123 gas uni s.
This sa ing is one uni highe han expec ed, and mos p obably, i is because
bypassing he bounds check means we a e a oiding an ex a JUMP ins uc ion (cos
o 1 uni o gas) o exi om he block con aining such a check.
Howe e , when execu ed on an a ay wi h only one a ay, he imp o emen is
smalle han expec ed. I we only pe o m one i e a ion, we sa e 21 uni s less han
expec ed (22 i we ake 123 uni s as he new e e ence). This di e ence is because, as
explained, emo ing he bounds checks, and he e o e, some blocks o he code, may
gene a e a edis ibu ion o he by ecode. This edis ibu ion can ha e side e ec s
on he execu ion cos o he es o he con ac , inc easing o dec easing he gas
consumed. Looking a hese esul s, we can in e p e ha in his speci ic case, we
educe he gas consump ion by 123 uni s pe i e a ion, bu he es o he unc ion
inc eases i s consump ion by 21 uni s. The e o e, i he unc ion only pe o ms
one i e a ion, he gas sa ing will be 101 uni s, bu as we inc ease he numbe o
3.4. Resul s and expe imen s 57
i e a ions, his ex a cos is dis ibu ed be ween all he i e a ions, ge ing close o
he 123 uni s o gas sa ed pe i e a ion.
Again, his is alid o his pa icula case. On o he unc ions, he e ec on he
cos execu ion un ela ed o he a ay index accesses can be di e en , e en causing a
educ ion. None heless, his side e ec on he con ac gas cos is minimal compa ed
o he po en ial sa ings o he uncheckedA ay block, especially when pe o ming
mul iple accesses.
3.4.2. Memo y gas sa ing
In he case o a ays in memo y, we expec he uncheckedA ay block o ha e a
lowe impac on he gas cos . In Figu e 3.17, we can obse e he main pa o he
bounds check in he EVM assembly code:
1DUP2
2MLOAD // Load leng h
3DUP2
4LT // Compa e
5PUSH2
60x75
7JUMPI // Jump o panic unc ion
Figu e 3.17: Example o EVM assembly code o bounds checks on memo y a ays
F om he obse ed code, acco ding o EIP-2929 [8], we can conclude ha by
bypassing ha check, we will sa e gas by no execu ing he ollowing ins uc ions:
Two DUP2 ins uc ions, wi h a cos o 3 gas uni s each.
A load om memo y (MLOAD), wi h a cos o 3 uni s.
A compa ison (LT), wi h a cos o 3 gas uni s.
APUSH2 ins uc ion, wi h a cos o 3 gas uni s.
AJUMPI ins uc ion, wi h a cos o 10 gas uni s.
This esul s in a heo e ical gas sa e o 25 uni s. Howe e , as in he case o s o age
accesses, his numbe may a y sligh ly depending on he compiled con ac .
64 Chap e 4. Compile Op imiza ions
o gas pe i e a ion. Since accessing alues om s o age has a high cos , when he
a ay size emains cons an inside he loop, i is highly con enien o s o e he leng h
o he a ay in a local a iable (s ack) ou side he loop. This a iable can hen be
used inside he loop condi ion, sa ing a s o age load pe i e a ion. As shown in
Figu e 4.2, i is a simple change on he code ha can make us sa e a ound 100 gas
uni s pe i e a ion (cos o load om s o age). None heless, de elope s some imes
do no pe o m his op imiza ion due o o e sigh o igno ance.
1 unc ion sea ch(uin x) iew public e u ns (uin ,bool) {
2uin len = a .leng h;
3 o (uin i = 0; i < len; i++) {
4i (a [i] == x)
5 e u n (i, ue);
6}
7 e u n (0, alse);
8}
Figu e 4.2: Example o op imized sequen ial sea ch in Solidi y
The e is ano he possible op imiza ion o his loop, simila o he p e ious one,
bu which is only possible o pe o m in he sou ce code using an inline assembly
block. As we know om p e ious chap e s, when accessing he elemen s in s o age
o memo y a ays, he a ay leng h mus be loaded o pe o m he bounds checking.
This op imiza ion aims o s o e such leng h on a local a iable ou side he loop and
use i o check bounds on each a ay index access pe o med inside he loop.
4.1. Cu en Loop Op imiza ions
Once he wo op imiza ion goals o implemen in his phase o he p ojec a e
se , we mus s udy how he cu en op imize modules o he compile ea a ay
leng h and index accesses inside loops.
In he case o he opcode op imize (see Sec ion 2.2.1.1), since i wo ks a a
e y low le el, i can only op imize a ay accesses in e y speci ic cases. Using he
Cons an Op imize , he module can eplace he a ay leng h loads o s a ic-sized
a ays wi h he compu ed leng h a compile ime. This has a gas-sa ing e ec on
index and leng h accesses o e a ays wi h a p ede ined ixed size. Howe e , his
module pe o ms no op imiza ion on dynamic-sized a ays.
On i s side, he Yul op imiza ion module (see Sec ion 2.2.1.2), in e y speci ic
si ua ions, is able o pe o m he op imiza ions men ioned in he in oduc ion o
his chap e on dynamic-sized a ays. By using he LoopIn a ian CodeMo ion s ep
4.1. Cu en Loop Op imiza ions 65
oge he wi h unc ion inlining, he Yul module is able o iden i y some si ua ions
whe e he a ay leng h load can be pe o med ou side he loop, as we see in he nex
sec ion.
4.1.1. Loop In a ian Code Mo ion
The Loop In a ian Code Mo ion is an op imiza ion s ep o he Yul op imize
module, in oduced in Sec ion 2.2.1.2 o Chap e 2. This s ep analyzes he body o
he loop and mo es a iable decla a ions ou side he loop i such a iables emain
cons an du ing he loop and ha e only ead side e ec s (e.g., a load om s o age o
memo y) o no side e ec s. This op imiza ion is e y powe ul because i can p e en
he p og am om compu ing exp essions wi h cons an esul s on each i e a ion.
Howe e , since his module wo ks a a ela i ely low le el, i p esen s wo signi -
ican limi a ions ha es ic he si ua ions whe e he op imiza ion can be applied.
Fo emos , i wo ks only a he op le el in he loop body and pos block, i.e., a iable
decla a ions inside condi ional b anches will no be conside ed o mo ing. And sec-
ond, i canno eason abou ine-g ained s o age o memo y loca ions. Consequen ly,
i he code w i es o any loca ion in he same memo y egion (s o age o memo y)
inside he loop body, he compile is no able o de e mine whe he he loca ion
w i en co esponds o he leng h o he a ay being cached o o any o he loca ion
in he s o age o memo y, and, consequen ly, he op imiza ion is no applied.
4.1.2. Real case analysis
In o de o comple ely analyze how his op imiza ion wo ks on bo h index and
leng h a ay accesses inside he loop, we le us ake he unc ion shown in Figu e 4.3
as an example. This unc ion is one o he pa icula si ua ions whe e he Yul
op imize is able o op imize he a ay leng h access and he a ay index access by
ex ac ing he a ay leng h loads om he loop.
In he ollowing explana ion o how his loop is op imized, we will only ocus on
he s eps ha di ec ly a ec he a ay leng h and index access. Since he IR code
has high complexi y and he comple e op imiza ion p ocess makes he esul e y
di icul o in e p e , he code shown o suppo he explana ion is jus a ep esen-
a ion o how he eal IR code would be modi ied i we only apply he men ioned
op imiza ion s eps. The e o e, many op imiza ion s eps ha e been le aside, some
exp essions ha e been simpli ied, and ce ain a iables ha e been con enien ly e-
named o dele ed.
66 Chap e 4. Compile Op imiza ions
1 unc ion sum() iew public e u ns (uin ) {
2uin s = 0;
3 o (uin i = 0; i < a .leng h; i++)
4s += a [i];
5 e u n s;
6}
Figu e 4.3: Func ion o add he elemen s o an a ay
The Yul code shown in Figu e 4.4 co esponds o he IR gene a ed by he com-
pile o he unc ion o Figu e 4.3. Obse e ha he loop condi ion has been mo ed
o he loop body (Lines 10-13). This code eo de ing is pe o med by he op imiza-
ion s ep Fo LoopCondi ionIn oBody, which mo es he condi ion exp ession o he
loop in o he body. This op imiza ion s ep is applied by de aul when gene a ing
he IR code o loops, e en i he op imiza ions a e disabled. I is impo an o no e
ha he gene a ed code uses Yul unc ions o pe o ming basic ope a ions on he
a ay a Lines 12, 17, and 18. We will ocus on he calls highligh ed a Lines 12 and
17, which code is shown in Figu e 4.5.
Once he compile has gene a ed he IR code, i will s a wi h he op imiza ion
p ocess. The i s ele an s eps o he loop op imiza ion pe o med by he compile
a e ela ed o unc ion inlining. Du ing his p ocess, he op imize module will y o
eplace unc ion calls in he code wi h he body o he called unc ion. This p ocess
is pe o med in wo di e en s eps, he Exp essionInline and he FullInline ,
which a ge di e en kinds o unc ion calls:
Exp ession Inline . The exp ession inline s ep inlines unc ions o eplace
calls inside unc ional exp essions. This op imiza ion s ep is applied when he
ollowing condi ions hold:
•The exp ession e u ns a single alue.
•I is on he le side o a a iable assignmen .
•The exp ession has only mo able1a gumen s.
•The exp ession has a gumen s ha a e small cons an s o ha a e e e -
enced less han wice in he unc ion body.
The e o e, in he case o a ay access op imiza ions, he exp ession inline will
exclusi ely a ec he call o he auxilia y leng h loading unc ion a Line 12
as i complies wi h all he condi ions. In con as , he auxilia y unc ion in
1Acco ding o he compile documen a ion, an exp ession is conside ed mo able "i i is side-
e ec ee and i s e alua ion only depends on he alues o a iables and he call-cons an s a e o
he en i onmen ".
4.1. Cu en Loop Op imiza ions 67
1 unc ion un_sum_34() -> a __7 {
2 a __7 := ze o_ alue_ o _spli _ _uin 256()
3le a _s_10 := con e _ _ a ional_0_by_1_ o_ _uin 256(0x00)
4
5 o {
6le a _i := con e _ _ a ional_0_by_1_ o_ _uin 256(0x00)
7} 1 {
8 a _i := inc emen _ _uin 256( a _i)
9} {
10 // Loop condi ion: i < a .leng h
11 le _slo := 0x00
12 le exp _19 := a ay_leng h_ _a ay$_ _uin 256_$dyn_s o age(
_slo )
13 i isze o( l ( a _i, exp _19) ) { b eak }
14
15 // Load a [i]
16 le _1_slo := 0x00
17 le _8, _9 :=
s o age_a ay_index_access_ _a ay$_ _uin 256_$dyn_s o age(
_1_slo , a _i)
18 le _10 := ead_ om_s o age_spli _dynamic_ _uin 256(_8, _9)
19
20 // sum += a [i]
21 a _s_10 := checked_add_ _uin 256( a _s_10, _10)
22 }
23
24 a __7 := a _s_10
25 lea e
26 }
Figu e 4.4: IR code om Figu e 4.3
cha ge o he a ay access a Line 17 does no comply wi h he i s condi ion,
as i e u ns wo a iables.
Full Inline . The ull inline s ep pe o ms unc ion inlining i he ans o -
ma ion does no lead o a la ge code. The e o e, i inlines unc ions only i
he called unc ion is e y small o i i is called only a ew imes in he en i e
code.
Consequen ly, he a ay leng h ge e would also be inlined by his op imiza-
ion s ep because i s body comp ises a single ins uc ion. Ne e heless, since
he auxilia y unc ion o pe o m he a ay index access is conside ed a la ge
unc ion, i will only be inlined in o la ge unc ions i used only a ew imes
in he code. Ou expe imen s de ec ed ha he op imize does no inline he
68 Chap e 4. Compile Op imiza ions
unc ion call wi h mo e han h ee index accesses exp essions on he code.
Addi ionally, i se e al unc ions con ain a ay accesses, he inlining does no
occu . We canno es ablish an exac heu is ic since his beha io a ies de-
pending on he code size, how many accesses a e p oduced, and whe e hey a e
p oduced. Howe e , we can es ablish ha his is a majo limi a ion because
in mos o he cases ied, wi h expe imen al and eal con ac s, his inlining
is no p oduced, and, wi hou his inlining, he ollowing op imiza ion s eps
o e he a ay access a e no possible.
1 unc ion s o age_a ay_index_access_ _a ay$_ _uin 256_$dyn_s o age(
a ay, index) -> slo , o se {
2//Bounds check
3le a ayLeng h := a ay_leng h_ _a ay$_ _uin 256_$dyn_s o age(
a ay)
4i isze o(l (index, a ayLeng h)) {
5panic_e o _0x32()
6}
7// Compu e he s o age slo o he elemen in he a ay
8le da aA ea := a ay_da aslo _ _a ay$_ _uin 256_$dyn_s o age(
a ay)
9slo := add(da aA ea, mul(index, 1))
10 o se := 0
11 }
12
13 unc ion a ay_leng h_ _a ay$_ _uin 256_$dyn_s o age( alue) ->
leng h {
14 leng h := sload( alue)
15 }
Figu e 4.5: IR auxilia unc ions used in Figu e 4.4
Since ou code con ains a single a ay access, he inlining p ocess will success ully
eplace he unc ion calls o he a ay leng h ge e and he a ay index access
auxilia y unc ions, shown in Figu e 4.5. In Figu e 4.6, we can obse e he code
esul ing om his op imiza ion p ocess.
Finally, he loop in a ian code mo ion s ep will y o mo e ou side he loop
he decla a ion o a iables ha emain cons an inside he loop. Since he e is no
side-e ec on loading he a ay leng h and he leng h emains cons an ( he e is no
w i ing o s o age), he op imize will be able o mo e bo h a ay leng h loads, he
one o he loop condi ion and he one o he loop access. He e is whe e ha ing he
a ay index access inlined is c i ical. Because i is inlined, he a ay leng h access o
he bounds checks (Line 11 in Figu e 4.6) can be iden i ied as a cons an exp ession
by he loop in a ian code mo ion. I i we e no inlined, he leng h load would
be pe o med inside he a ay index access auxilia y unc ion ha is called inside
4.1. Cu en Loop Op imiza ions 69
he loop wi h a iable a gumen s ( he index being accessed) and, consequen ly, a
non-cons an exp ession.
1 unc ion un_sum_34() -> a __7 {
2 a __7 := ze o_ alue_ o _spli _ _uin 256()
3le a _s_10 := con e _ _ a ional_0_by_1_ o_ _uin 256(0x00)
4
5 o {
6le a _i := con e _ _ a ional_0_by_1_ o_ _uin 256(0x00)
7} 1 {
8 a _i := inc emen _ _uin 256( a _i)
9} {
10 // Loop condi ion: i < a .leng h
11 le exp _19 := sload(0x00)
12 i isze o( l ( a _i, exp _19) ) { b eak }
13
14 // Load a [i]
15 le _1_slo := 0x00
16
17 //Load a ay leng h
18 le a ayLeng h := sload(_1_slo )
19
20 //Bounds check
21 i isze o(l ( a _i, a ayLeng h)) { panic_e o _0x32() }
22
23 // Compu e he s o age slo o he elemen in he a ay
24 le da aA ea := a ay_da aslo _ _a ay$_ _uin 256_$dyn_s o age(
_1_slo )
25 slo := add(da aA ea, mul( a _i, 1))
26 o se := 0
27
28 // Load alue om s o age
29 le _10 := ex ac _ om_s o age_ alue_dynamic _uin 256(sload(
_1_slo ), o se )
30
31 // sum += a [i]
32 a _s_10 := checked_add_ _uin 256( a _s_10, _10)
33 }
34
35 a __7 := a _s_10
36 lea e
37 }
Figu e 4.6: Op imized IR code a e applying Exp essionInline and FullInline
s eps o he code in Figu e 4.4
70 Chap e 4. Compile Op imiza ions
In his pa icula case, he op imize will e en de ec ha he loop condi ion
exp ession (Line 12 in Figu e 4.6) and he condi ion exp ession o he bounds check
on he a ay access (Line 21 in Figu e 4.6) a e he same. Since he i s condi ion
leads o an exi o he loop when eached, he second condi ion always e alua es o
ue, so he op imize will emo e he bounds check on he a ay access. Figu e 4.7
shows he IR code a e op imizing he a ay leng h and access loads. In his Figu e,
we can see ha he code eading he leng h o he a ay has been mo ed ou o
he loop o Line 4. I he condi ions we e no equal, he bounds check would ha e
emained on he code, bu since bo h load exp essions (Line 11 and 18 in Figu e 4.6)
a e equi alen , he op imize will emo e one o hem and use he same a iable o
bo h condi ional exp essions.
1 unc ion un_sum_34() -> a __7 {
2 a __7 := ze o_ alue_ o _spli _ _uin 256()
3le a _s_10 := con e _ _ a ional_0_by_1_ o_ _uin 256(0x00)
4le a ayLeng h := sload(0x00)
5
6 o {
7le a _i := con e _ _ a ional_0_by_1_ o_ _uin 256(0x00)
8} 1 {
9 a _i := inc emen _ _uin 256( a _i)
10 } {
11 // Loop condi ion: i < a .leng h
12 i isze o( l ( a _i, a ayLeng h) ) { b eak }
13
14 // Load a [i]
15 // Compu e he s o age slo o he elemen in he a ay
16 ms o e(0, p )
17 le da aA ea := keccak256(0, 0x20)
18
19 slo := add(da aA ea, mul( a _i, 1))
20 le _10 := ex ac _ om_s o age_ alue_dynamic _uin 256(sload(
slo ), 0)
21
22 // sum += a [i]
23 a _s_10 := checked_add_ _uin 256( a _s_10, _10)
24 }
25
26 a __7 := a _s_10
27 lea e
28 }
Figu e 4.7: Op imized IR code a e applying LoopIn a ian CodeMo ion s ep o
he code in Figu e 4.6
4.2. A new op imiza ion phase 71
To summa ize, a e all hese op imiza ion s eps a e applied, some unnecessa y
a iables a e emo ed, and he gene a ed code will p oduce wo ewe loads om
s o age pe i e a ion han he o iginal one, esul ing in a g ea imp o emen in
con ac e iciency. I he a ay we e s o ed in memo y, he op imiza ion p ocess
would be he same, bu he amoun o gas sa ed would be much lowe because he
cos o loading alues om memo y is only h ee gas uni s in mos cases. In he case
o an a ay in callda a, he op imiza ion would no ha e any e ec since he leng h
o he a ay would al eady be s o ed in he s ack.
Howe e , his is an ideal case. As we ha e seen du ing he p ocess, he op imiza-
ion module has se e al impo an limi a ions:
Rega ding a ay leng h accesses inside he loop, he ollowing condi ions mus
hold:
•The e is no w i e o s o age inside he loop.
•The a ay leng h access mus be a he loop body op le el and no inside
any o he s uc u e, such as i - hen exp essions o nes ed loops.
Rega ding a ay index accesses, an addi ional e y s ong limi a ion is e-
qui ed:
•The code can only ha e a ew a ay index accesses in he en i e con ac ,
usually less han ou 2.
This las cons ain makes i almos impossible o ake ad an age o his op i-
miza ion module on a ay accesses on sma con ac s.
In his analysis o he cu en op imiza ions on a ays inside loops, we ha e seen
ha e en hough hey exis and hey a e qui e powe ul, hey can be used in e y
limi ed si ua ions, especially in he case o a ay index accesses. Consequen ly, i
would be in e es ing o c ea e a new a ay access op imiza ion, based on he same
p inciples, ha o e comes mos o he cu en limi a ions and, he e o e, co e s a
much wide ange o si ua ions.
4.2. A new op imiza ion phase
Knowing he limi a ions o he cu en op imize modules when dealing wi h
loops and a ay accesses, we decided o implemen a new op imiza ion phase a a
highe le el o abs ac ion. This new op imiza ion phase o e comes mos o he
2This numbe may a y sligh ly depending on he size o he con ac and unc ion whe e he
accesses a e pe o med.
72 Chap e 4. Compile Op imiza ions
limi a ions aced by he Yul op imize . We p opose o di ec ly gene a e op imized
a ay access in IR code, using all he in o ma ion we can ex ac om he AST o
he Solidi y code. This ex a in o ma ion gi es he op imize a signi ican ad an age
compa ed o he cu en modules, allowing us o op imize a ay accesses, bo h o
hei leng h and by index, in a b oade ange o si ua ions. Addi ionally, his new
op imiza ion phase opens a new window o u he complex op imiza ions ha could
no be implemen ed on he exis ing modules.
Fo example, his op imiza ion allows s o age modi ica ions ha do no a ec
he a ay leng h inside he loop. A he Yul le el, he op imize can only see a
SSTORE ins uc ion o a dynamically compu ed s o age slo , and i can no know
i ha slo is he one con aining he leng h o he a ay. Bu now, a he Solidi y
le el, he op imize can dis inguish be ween a s o age modi ica ion ha a ec s he
a ay leng h, such as a push o pop ope a ion, and a modi ica ion o he alue o an
a ay index ha does no ha e any side e ec on i s leng h.
4.2.1. Applicabili y cons ain s
The i s cons ain o his new op imiza ion is ha i is only pe o med o e
s o age a ays. The eason is ha while he gas cos o loading a alue om s o age
is high (100 gas uni s acco ding o EIP-2929 [8]), he load om memo y is cheap (3
gas uni s). The e o e, when op imizing memo y a ays, he ma gin is so low ha
only he new ins uc ions needed a EVM by ecode le el o keep he a ay leng hs
on he s ack du ing he whole loop may be mo e expensi e han loading i when
equi ed. We lea e as a u u e wo k he s udy o an op imiza ion ha can also
ob ain gains wi h memo y a ays. In he case o callda a a ays, his op imiza ion
has no sense as hey do no need hei leng h o be loaded when being accessed.
A undamen al pa o his op imiza ion is o se he condi ions ha gua an ee
ha he gene a ed code is equi alen o he o iginal. Since we a e mo ing he a ay
leng h load ou side he loop, we need o gua an ee ha he leng h emains cons an
du ing he execu ion o he loop. In o de o do ha , we ha e i s o iden i y all he
ways he a ay leng h o a s o age a ay can be modi ied in Solidi y code and hen
o es ablish he cons ain s ha gua an ee a sa e applica ion o he op imiza ion:
Doing a push ope a ion on he a ay.
Doing a pop ope a ion on he a ay.
Assigning a new a ay o he a ay s o age a iable.
Using an inline assembly block.
Calling a unc ion ha pe o ms any p e iously men ioned ope a ion.
4.2. A new op imiza ion phase 73
Push and Pop. Push and pop ope a ions inc ease o dec ease by one uni he
leng h o he a ay hey a e applied o. This ope a ion can be pe o med o e he
dynamic s o age a ays using he con ac s a e a iable as well as a memo y poin e
ha poin s o he a ay, which makes i e y di icul o keep ack o which s o age
a ay is being modi ied. The e o e, we ha e es ablished as a cons ain ha he
op imiza ion only is pe o med i he e is no push no pop ope a ion o e any a ay
inside he loop.
A ay copy. In Solidi y, assignmen s be ween s o age and memo y and be ween
s a e a iables c ea e an independen copy. The e o e, any assignmen o an a ay
(in s o age, memo y, o callda a) o a s a e a iable esul s in he a ay being copied
o he s a e a iable and, consequen ly, changing i s leng h. In o de o sol e his
si ua ion, he op imize does no op imize a ay accesses whe e i s a ay base is
assigned wi h ano he alue inside he loop.
Inline Assembly. Inline assembly blocks pe o m low-le el ope a ions using he
Yul language, such as di ec accesses o s o age using SLOAD o SSTORE by ecode
ins uc ions. The e o e, when analyzing inline assembly blocks, we ace he same
limi a ions as he Yul op imize : we canno iden i y i a SSTORE ins uc ion is modi y-
ing he leng h o an a ay being used inside he loop. Consequen ly, he op imiza ion
is no pe o med i he e is an inline assembly block inside he loop.
Func ion calls. Finally, he leng h o an a ay can be modi ied by calling a unc-
ion ha pe o ms any o he p e ious ope a ions. The e o e, we mus gua an ee
ha no modi ica ion o an a ay leng h is done in he called unc ion o any unc ion
called om i . This would equi e elabo a ing and analyzing he unc ion call g aph,
as well as complex easoning and soundness p oo . Howe e , his is ou o he scope
o his p ojec phase. In o de o simpli y he check o his condi ion, we ha e es-
ablished a mo e es ic i e cons ain ha gua an ees he p e ious one: he called
unc ion does no modi y he s a e o he con ac in any way ( he e a e no w i es
o s o age). We can easily iden i y i a unc ion modi ies he con ac s a e using
he s a e modi ie s (see mu abili y checking in Sec ion 2.1.2 o Chap e 2). These
modi ie s gua an ee ha all unc ions ansi i ely eachable mus ha e decla ed he
same o a mo e es ic i e modi ie , and hus we do no need o pe o m any a e -
sal o he unc ion call g aph. Using hem, we can es ablish ha he op imiza ion
will no ake place i he e is a call o a unc ion ha is no iew o pu e.
Ano he impo an cons ain o his new op imize is ha i only ope a es on
accesses whe e he base exp ession is a a iable iden i ie . The e o e, we can only
op imize accesses o one-dimensional a ays o o he i s dimension o mul idi-
mensional a ays. I we wan ed o op imize accesses o he second and ollowing
dimensions o he a ay, we would need o s o e ou side he loop he leng h o each
a ay accessed in each dimension. Tha solu ion would no be p ac ical o wo main
80 Chap e 4. Compile Op imiza ions
he new –op imize-a ays lag.
1Op imize Op ions:
2--op imize Enable by ecode op imize .
3--op imize- uns n (=200)
4The numbe o uns speci ies oughly how o en each
5opcode o he deployed code will be execu ed ac oss he
6li e ime o he con ac . Lowe alues will op imize
7mo e o ini ial deploymen cos , highe alues will
8op imize mo e o high- equency usage.
9--op imize-yul Legacy op ion, igno ed. Use he gene al --op imize o
10 enable Yul op imize .
11 --no-op imize-yul Disable Yul op imize in Solidi y.
12 --op imize-a ays Enable a ay access op imize in Solidi y. Same
e ec as --op imize and -- ia-i .
13 --yul-op imiza ions s eps
14 Fo ces yul op imize o use he speci ied sequence o
15 op imiza ion s eps ins ead o he buil -in one.
Figu e 4.14: Op imiza ion op ions o he compile
4.3. Resul s and expe imen s
As explained a he beginning o his chap e , his new op imiza ion s o es he
leng h o s o age a ays being accessed (bo h o access i s leng h o index) inside a
loop on a local a iable (s o ed in he s ack). Then his a iable is used o eplace
leng h loads on leng h accesses (e.g., condi ion o he loop) and bounds checks on
index accesses. Wi h his sligh change in he code, we sa e he cos o loading
a alue om s o age on each a ay access on each i e a ion o he loop. We only
main ain he cos o he i s leng h load, which is now pe o med p e ious o he
s a o he loop. The e o e, we a e sa ing 100 gas uni s pe access on each i e a ion
4in each i e a ion excep he i s one.
Howe e , since we a e adding he a ay leng hs o he s ack, he gene a ed by e-
code may in oduce new ins uc ions o keep hese alues on he op o he s ack
du ing he loop execu ion. Consequen ly, he inal sa ed amoun may be sligh ly
lowe . Ne e heless, he di e ence be ween he cos o ope a ions on he s ack (e.g.,
PUSH,POP,DUP), which usually a ies be ween 1 and 3 gas uni s, is much lowe han
a load om s o age (100 gas uni s) so only on emo e cases he op imiza ion may
no educe he gas consump ion because o hose ex a ins uc ions.
4Acco ding o EIP-2929 [8], he cos o he i s access o a s o age slo is 2100 gas uni s.
Howe e , since we main ain his access, his does no a ec he sa ing compu a ion.
4.3. Resul s and expe imen s 81
Addi ionally, he e is a speci ic case whe e he op imiza ion inc eases he gas
consump ion: i he loop is no accessed. Since wi h he op imiza ion, he a ay
leng hs a e loaded be o e en e ing he loop, i he loop is no accessed, we will
p oduce ex a loads om s o age. This issue can be easily sol ed in u u e wo k by
w apping he a ay loads on a condi ional s a emen wi h he same condi ion as he
a ay loop.
4.3.1. Simple expe imen
In o de o p o e he heo e ical gas sa ing pe access, we used a simple unc ion
simila o he one used in he p e ious chap e o es he uncheckedA ay block.
Figu e 4.15 shows he es ed unc ion, which sa es he sum o wo a ays in one
a ay, all in s o age.
1 unc ion sumA ays() public {
2 o (uin 256 i = 0; i < size; i++)
3a[i] = b[i] + c[i];
4}
Figu e 4.15: Tes ed unc ion
The execu ion o his simple benchma k on a ays o di e en leng hs (1, 10, and
100 elemen s) p oduced he esul s shown in Table 4.1.
I e a ions O iginal New Op imiza ion Di Di pe I e a ion
1 36305 36376 -71 -71.00
10 278387 275965 2422 242.20
100 2699207 2671855 27352 273.52
Table 4.1: Gas cos di e ence be ween using he o iginal op imiza ion and he new
op imiza ion
We obse e ha ou new op imiza ion inc eases gas consump ion when execu ing
he code o e an a ay wi h a single elemen . This consump ion inc ease is because,
as explained, he op imiza ion akes he leng h loads ou o he loop, bu hey
a e s ill pe o med once. Consequen ly, since he op imiza ion canno educe he
numbe o loads bu s ill in oduces an ex a cos by c ea ing new local a iables,
he inal gas cos is sligh ly inc eased (less han an 0.2%).
Howe e , as we inc ease he leng h o he a ay and consequen ly he numbe
o i e a ions, he op imiza ion becomes mo e e ec i e, inc easing he gas sa es pe
82 Chap e 4. Compile Op imiza ions
i e a ion o an amoun close o he expec ed 300 gas uni s (3 leng h loads om
s o age) o his case.
4.3.2. Real li e expe imen s
The main goal du ing his phase is o imp o e he cu en a ay access op imiza-
ions p o iding a new op imiza ion ha co e s a much mo e comp ehensi e ange
o scena ios and ha can be used on eal code wi hou any needed modi ica ion, as
equi ed wi h he uncheckedA ay block. The e o e, we wan o measu e he e i-
ciency o his new op imiza ion on he code o con ac s cu en ly being used in he
E he eum blockchain. In o de o do ha , we ha e selec ed public sma con ac s
and lib a ies ha de elope s equen ly use o manage a ays and ma ices.
Using such lib a ies and con ac s, we ha e de eloped a benchma k 5 o measu e
he gas sa ing when applying ou new op imiza ion. This benchma k is composed o
h ee di e en es sui es ha use h ee eal lib a ies o pe o m di e en ope a ions
o e s o age a ays and ma ixes.
We ha e sligh ly modi ied he code o some o he o iginal lib a ies o adap hem
o he cu en compile e sion and only use s o age a ays.
In o de o e alua e he gas sa ings p oduced wi h his new op imiza ion, we ha e
used he same op imiza ion se up o bo h he cu en compile and he compile
wi h ou new op imiza ion. We ha e se up he –op imize and – ia-i lags, which
gene a e he mos op imized code he cu en op imiza ions can gene a e.
A ay Lib a y. The A ay es sui e uses an a ay managemen lib a y om
he Solidi y S anda d Lib a y [4]. This lib a y eposi o y p o ides wo lib a ies,
Uin A ay and In A ay, o manage a ays o unsigned and signed in ege s. Bo h
lib a ies a e implemen ed as con ac s ha s o e he in ege a ay in a s a e a iable
(in s o age), allowing he calling con ac o pe o m di e en ope a ions o e he
a ay.
In o de o de elop ou es sui e, we ha e selec ed h ee me hods o he Uin A ay
lib a y (maximum alue ge e , he minimum alue ge e , and he sum o he el-
emen s o he a ay), and we ha e c ea ed h ee di e en es s whe e we c ea e an
a ay, call he co esponding me hod and e i y he co ec ness o he e u ned alue.
Mo eo e , since he lib a y was de eloped wi h a a ge o he 0.4.0 e sion o he
compile , we had o modi y some unc ion decla a ions in o de o adap hemsel es
o he cu en compile e sion es ic ions, such as he cons uc o de ini ion o he
memo y space decla a ion on unc ion e e ence pa ame e s.
5The used benchma ks can be consul ed a h ps://gi hub.com/ja ie Sande/
solidi y-benchma ks.gi .
4.3. Resul s and expe imen s 83
We ha e compu ed he gas sa ings by execu ing each es h ee imes o e a ays
o 100 elemen s so ed in ascending o de , descending o de , and andomly gene -
a ed. Table 4.2 and Figu e 4.16 show he a e age gas consump ion o each es wi h
and wi hou ou op imiza ion.
Me hod O iginal Gas Op imized Gas Di Pe cen age
Max 299687 280597 19090 6.37%
Min 296619 278543 18076 6.09%
Sum 300269 282369 17900 5.96%
Table 4.2: Gas sa ings on A ay Lib a y es s
0
50000
100000
150000
200000
250000
300000
350000
es Max es Min es Sum
Gas uni s consumed
Gas Consump ion Compa ison
O iginal A ay Access Op imized
Figu e 4.16: Compa ison o he gas cos be ween o iginal code and op imized code
The esul s show a gas educ ion o a ound 6% on each es . We can obse e
ha he sum es has a sligh ly lowe sa ing han he o he wo es s because, on
his es , he a ay is accessed only once pe i e a ion, while on he o he es s, i
is accessed wice whene e local minimums o maximums a e ound. Addi ionally,
we can obse e s a sligh di e ence in gas consump ion and sa ing be ween he
maximum and minimum ge e es s, which a e echnically iden ical in e ms o
pe o mance, which is explained because o he andomness o he a ay. P obably,
he a ay so ed andomly p oduces mo e accesses when looking o he maximum
(mo e local maximums), which explains he highe a e age gas cos and he highe
gas sa ing on he max es o e he min es .
F om hese esul s, we conclude ha he op imiza ion p oduces a signi ican gas
sa ing e en in unc ions whe e a ays a e accessed only a ew imes pe i e a ion,
whe e he po en ial gas educ ion is lowe .
84 Chap e 4. Compile Op imiza ions
Ma ix Lib a y. The Ma ix es sui e has been de eloped using he SolMATe
lib a ies [20] o loa ing-poin compu a ion, a ay manipula ion, and linea algeb a.
F om i , we ook he Vec o U ils and Ma ixU ils lib a ies o de elop se e al es s
on a ay manipula ion. Wi h hese es sui es, we wan o measu e he e iciency
o ou op imiza ion when manipula ing ma ices, e en when i can only op imize
accesses o he i s dimension o a ma ix.
We ha e de eloped six es s o add, mul iply, and anspose ma ices, add o
mul iply a ma ix by a numbe , and compu e he diagonal o a ma ix. Since bo h
lib a ies only suppo ed memo y a ays, hey ha e been modi ied o be able o
ope a e o e s o age a ays. Addi ionally, some unused unc ions we e emo ed.
Each es calls a lib a y unc ion ha ecei es s o age ma ices as pa ame e s and
e u ns a new ma ix o ec o (diagonal) s o ed in memo y. The e o e, ou new
op imiza ion will only educe gas om he a ay ead accesses, limi ing i s po en ial
e en mo e.
Me hod O iginal Gas Op imized Gas Di Pe cen age
Add Ma ix 833995 751526 82469 9.89%
Add Numbe 511443 441897 69546 13.60%
Diagonal 100008 97978 2030 2.03%
Do 1868660 1751896 116764 6.25%
Mul iply Numbe 515487 445941 69546 13.49%
T anspose 462439 417172 45267 9.79%
Table 4.3: Gas sa ings on Ma ix Lib a y es s
0
200,000
400,000
600,000
800,000
1,000,000
1,200,000
1,400,000
1,600,000
1,800,000
2,000,000
es AddMa ix es AddNum es Diagonal es Do es MulNum es T anspose
Gas uni s consumed
Gas Consump ion Compa ison
O iginal A ay Access Op imized
Figu e 4.17: Compa ison o he gas cos be ween o iginal code and op imized code
4.3. Resul s and expe imen s 85
Tes s ha e been execu ed o e a s o age 10 x 10 ma ix wi h andom in ege
alues, using bo h he cu en compile and he modi ied compile con aining ou
new op imiza ion.
Despi e he limi a ions, wi h ou op imiza ion, we educe he gas consump ion
be ween 9% and 14% in mos es s. Table 4.3 and Figu e 4.17 show a g ea educ ion
in es s wi h many a ay accesses pe i e a ion, such as addi ions and mul iplica ions,
whe e all he a ay elemen s a e accessed.
None heless, we also obse e a e y low gas educ ion on he diagonal es , which
pe o ms much ewe a ay accesses han o he es s. As shown in Figu e 4.18 in
a 10 x 10 ma ix, he unc ion only pe o ms en i e a ions wi h wo a ay index
accesses (1 o he ows and 1 o he columns) pe i e a ion, whe e we only op imize
he ow access ( i s dimension). The es pe o ms an iden ical ope a ion o check
ha he diagonal alues a e co ec , so we ha e o double he numbe o i e a ions.
F om hose 20 i e a ions, we a e ge ing a sa ing o 2030 gas uni s, which means we
a e sa ing a ound 100 uni s pe i e a ion. Knowing ha he loop complies wi h he
cu en compile cons ain s o op imize he a ay leng h access on he condi ion,
we can conclude ha ou op imize is sa ing his ex a gas om each a ay index
access in he loop. The e o e, ou op imiza ion is using i s maximum po en ial, and
he only eason he sa ing pe cen age is low is ha mos o he gas consump ion on
he unc ion is p oduced by o he ope a ions, such as c ea ing he memo y ec o 6.
1 unc ion diag(in 256[][] s o age a) in e nal iew e u ns (in 256[]
memo y) {
2in 256[] memo y diagonal_ ec o = new in 256[](a.leng h);
3 o (uin i=0; i<a.leng h; i++) {
4diagonal_ ec o [i] = a[i][i];
5}
6 e u n diagonal_ ec o ;
7}
Figu e 4.18: Diagonal unc ion o he Ma ixU ils lib a y
The case o he do es is simila . Al hough he do ope a ion equi es accessing
e e y alue in he a ay since i is a complex unc ion wi h h ee nes ed loops, i
has a high gas cos de i ed om o he ope a ions, and consequen ly, he pe cen age
o he sa ed gas may be lowe bu s ill signi ican (mo e han 100,000 gas uni s).
Those esul s p o e ha ou new op imiza ion, despi e i s limi a ions on mul idi-
mensional a ays, pe o ms well when op imizing ma ix accesses. I is also p obable
ha as we inc ease he numbe o dimensions o an a ay, his pe o mance dec eases,
6The c ea ion o ec o in memo y has ela i ely high cos due o memo y expansion (EIP-
2929 [8]).
86 Chap e 4. Compile Op imiza ions
bu he use o s o age a ays o 3 o mo e dimensions is no equen in Solidi y sma
con ac s since he cos o manipula ing hem is ex emely high.
So ing Lib a y. The So ing es s sui e is a collec ion o he mos common
so ing me hods in p og amming adap ed o Solidi y, con ained in he So Lib
lib a y. So ing me hods a e one o he mos access in ense manipula ions o a ays,
pe o ming se e al a ay index accesses pe i e a ion in o de o ead, compa e
and eo de alues. Consequen ly, hey a e a g ea benchma k o measu e he eal
po en ial o ou op imiza ion on a complex a ay manipula ion.
On he So Lib lib a y, we ha e included se e al in ege so ing me hods wi h
di e en complexi ies: he selec ion, inse ion, and bubble (s anda d and op imized)
so me hods, which ha e a n2 ime complexi y, and he heap so me hod wi h a
nlogn ime complexi y. Using he men ioned lib a y, we ha e de eloped se e al es s
o call he co esponding so ing me hod and check he esul . Each es has been
execu ed h ee imes wi h an a ay wi h 100 in ege s so ed in ascending (bes -case
scena io), descending (wo s -case scena io), and andom o de o gua an ee eliable
a e age gas consump ion esul s.
0
1000000
2000000
3000000
4000000
5000000
6000000
7000000
8000000
9000000
10000000
es BubbleSo es BubbleSo Op imized es HeapSo es Inse ionSo es Selec ionSo
Gas uni s consumed
Gas Consump ion Compa ison
O iginal A ay Access Op imized
Figu e 4.19: Compa ison o he gas cos be ween o iginal code and op imized code
Table 4.4 and Figu e 4.19 show he a e age gas consump ion on each es o
he code compiled wi h and wi hou ou new op imiza ion. These esul s indica e
ha ou op imiza ion p oduces a ema kable educ ion o gas consump ion, be ween
10% and 17% o he o al gas cos , independen ly o he o de o complexi y o he
so ing me hod.
4.4. Conclusions 87
Me hod O iginal Gas Op imized Gas Di Pe cen age
Bubble So 7928770 6828488 1100282 13.88%
Bubble So Op im. 8948553 7441954 1506599 16.84%
Heap So 2184631 1876938 307693 14.08%
Inse ion So 6314264 5356155 958109 15.17%
Selec ion So 4069664 3623238 446426 10.97%
Table 4.4: Gas sa ings on So Lib a y es s
4.4. Conclusions
In his chap e , we ha e p esen ed a new op imiza ion o a ay accesses pe -
o med inside loops. As explained, his is an op imiza ion al eady being pe o med
by he Yul op imize module o he o icial compile . Howe e , since his op imiza-
ion is being pe o med a Yul le el, he compile lacks much impo an in o ma ion
abou he code beha io . Consequen ly, he amoun o op imized Yul code is limi ed
and can only a ge pa icula cases. As a solu ion o he signi ican limi a ions o
he Yul op imize , we ha e p oposed a new op imiza ion phase a a highe le el.
This new phase wo ks wi h in o ma ion om he sou ce code and i s AST, ha -
ing much mo e in o ma ion on he e ec s o he code on he p og am s a e and,
he e o e, o e coming mos o he limi a ions he Yul op imize aces.
Then, we implemen ed a new a ay op imiza ion in his new phase using he same
idea as he o iginal op imiza ion. This op imiza ion iden i ies accesses o s o age
a ays inside loops, analyzes i hei leng h emains cons an on each i e a ion, and
mo es he load o hei leng hs ou side he loop when possible, a oiding loading he
leng h on each i e a ion.
In o de o p o e he e ec i eness o his new op imiza ion, we ha e compa ed
he gas consump ion o di e en sma con ac s when only applying he cu en
op imiza ions and when adding ou op imiza ion. Fi s ly, we ha e compa ed he
consump ion o a simple con ac o iden i y he o igin o he gas sa ings easily. Re-
sul s show us ha he gas sa ings a e as expec ed and ha , e en in simple con ac s,
he p oposed op imiza ion goes u he han he cu en op imize . Finally, we ha e
compa ed he gas consump ion o e eal lib a ies used by de elope s o manage
a ays in hei sma con ac s. The esul s ha e shown a mo e han conside able
educ ion in gas consump ion, exceeding he 10% in mos cases.
This new compile op imiza ion has p o ed o be almos as e icien as he
uncheckedA ay block when educing he gas cos o accessing s o age a ays. Ad-
di ionally, i has wo ad an ages o e he men ioned block: i p ese es sa e y, and
we do no need o modi y code o ge op imized accesses. On he downside, i only
op imizes a ay accesses inside loops and in speci ic si ua ions whe e he compile
can gua an ee ha he a ay leng h emains cons an .
Conclusions and Fu u e Wo k
We s a ed his p ojec wi h he aim o op imizing a ay accesses in Solidi y
sma con ac s. In o de o do so, we ocused on educing he o e head p oduced
by bounds checks.
The ini ial s udy o he Solidi y language, i s compile , and he op imiza ion
s a egies used o educe gas consump ion on sma con ac s allowed us o p esen
and implemen wo op imiza ion p oposals o accomplish ou ini ial goal.
The i s p oposed solu ion was o allow p og amme s o disable bounds checks
on index accesses. In o de o do so, we based ou sel es on a solu ion cu en ly used
in he Solidi y language ha disables unde low and o e low checks on a i hme ic
ope a ions, he unchecked block. F om his idea, we came up wi h a new language
cons uc , he unchecke A ay block, ha disables bounds checks on any a ay
access enclosed in he block, and which has p o en i s e ec i eness on expe imen-
al esul s, educing gas consump ion in memo y, callda a, and, mos signi ican ly,
s o age a ays.
Howe e , his solu ion is no pe ec . I pu s sa e y in he hands o p og amme s,
equi es o modi y he code, and is no able o educe gas consump ion o accesses
whe e he bounds checks a e needed. All hese d awbacks o he i s solu ion
mo i a ed a comple ely di e en one: an op imiza ion a compile ime.
In his second solu ion, we wan ed o c ea e a new compile op imiza ion on a ay
accesses. F om he s udy o he cu en compile , we disco e ha he op imiza ions
being pe o med a e limi ed by he low-le el in o ma ion abou he code hey ha e.
Acco dingly, we implemen ed a new op imiza ion phase ha akes place du ing he
IR gene a ion, using he in o ma ion om he Solidi y sou ce code and i s AST.
Using his new phase, we implemen ed a new op imiza ion ha a ge s s o age
a ay accesses inside loops, educing i s gas cos de i ed om he leng h load on
bounds checks.
This new op imiza ion has p o en a ema kable e icacy, showing subs an ial gas
89