compiler design - eth ?· compiler design spring 2017 7.0 code generation dr. zoltánmajó...

Download Compiler Design - ETH ?· Compiler Design Spring 2017 7.0 Code generation Dr. ZoltánMajó Compiler…

Post on 04-Jun-2018

215 views

Category:

Documents

2 download

Embed Size (px)

TRANSCRIPT

  • CompilerDesignSpring2017

    7.0Codegeneration

    Dr.Zoltn Maj

    CompilerGroup JavaHotSpot VirtualMachineOracleCorporation

    46

  • Outline

    7.1Accesstooperands

    7.2Assignmentstatement

    7.3Conditionalstatement

    7.4Loops

    7.5Methodinvocation

    47

  • 48

    A B

    B

  • Extendingthecodegenerator

    NewIRnodes

    ARRAY (Index inframework) Specifiesarrayelement Requiresnameofarray ...andtreeforindexexpression

    FIELD

    Couldincludesubtree tocomputeaddress Asdiscussedearlier

    49

  • Otherrestrictions

    Didnothandlestatementsthatrequiredmoreregistersthanavailable Virtualregisterspostponedealingwiththisaspect

    CouldbreakatreethatrequiresmorethanRregistersintoseparatetrees Introducetemporaryvariablestoholdintermediateresults

    Recommendedoption:Handleregistershortageonthefly Needaregister?Freearegister Saveregistercontentsontostack Exampleonnextslide

    50

  • 51

  • Outline

    7.1Accesstooperands

    7.2Assignmentstatement

    7.3Conditionalstatement

    7.4Loops

    7.5Methodinvocation

    53

  • 7.3Conditionalstatement

    JavaLi allowstwokindsofconditionalstatements

    1. if-thenif (expression) { }

    2. if-then-elseif (expression) { }

    else { }

    54

  • 1. if-thenif (expression) { }InvokecodegeneratoronexpressionCodetodecideifthen-partisexecutedInvokecodegeneratoronthen-part

    2. if-then-elseif (expression) { }

    else { }InvokecodegeneratoronexpressionCodetodecideifthen-partisexecutedInvokecodegeneratoronthen-partCodetoskiparoundelse-partInvokecodegeneratoronelse-part

    55

  • Codeoutline

    57

    Eval expression

    Test

    Branch

    dThen-part

    continue

    Eval expression

    Test

    Branch

    Then-part

    continue

    Else-part

    d

    d

    Uncond.branch

  • 58

  • Outline

    7.1Accesstooperands

    7.2Assignmentstatement

    7.3Conditionalstatement

    7.4Loops

    7.5Methodinvocation

    59

  • 7.4Loops

    JavaLi hasonlyoneloopingconstructwhile (expression) {

    }

    Cantranslateallotherkindsofloopingconstructsintowhile-loops

    60

  • Translationsimilartoconditionalstatement Samerulesforexpression

    while-loopwhile (expression) { }

    InvokecodegeneratoronexpressionCodetodecideifloop-bodyisexecutedInvokecodegeneratoronloop-bodyCodetojumpbacktostartofloop

    61

  • Codeoutline

    62

    Eval expression

    Test

    Branch

    Body

    continue

    d

    Uncond.branch

  • 63

  • Expressionmustbeevaluatedforeveryiteration

    Simplescheme

    Straightforwardtoimplement Closetoconditionalstatement

    Oneunconditionalbranchforeachiteration

    64

  • Codeoutline2

    Idea:eliminateunconditionalbranchattheendofeachloopbody

    Moveloopcontinuationtesttotheendoftheloop

    65

  • Codeoutline2

    66

    Eval expression

    Test

    Branch

    Body

    continue

    d

    Uncond.branch

  • Possibleperformanceimprovement Reducednumberofunconditionalbranches Basedontheguessthattheloopbodyisexecuted Processorimplementationmayprefetch /pre-executeunconditional

    branches

    Otheroptionsexist

    67

  • 68

  • Otherloopconstructs

    Takeasheetofpaperandsketchhowyoucouldtranslateaforloop

    for (int i = low; i < high; i++) {

    }

    Showafigurethatoutlinesthecode(similartoslidesshownduringthelecture)

    69

  • Codeoutline

    70

    Eval expression

    Test

    Branch

    Body

    continue

    d

    Uncond.branch

    Init loopcounter

    Updateloopcounter

  • 71

  • Outline

    7.1Accesstooperands

    7.2Assignmentstatement

    7.3Conditionalstatement

    7.4Loops

    7.5Methodinvocation

    72

  • 7.5Methodinvocation

    Findingthecorrectbodyofcode Coveredearlier

    Storageformethod-localvariables

    Passingofparameters(arguments)

    Handlingthereturnvalue

    73

  • Terminology

    Considerasimpleclasswithonemethod:class B {

    int bar(int x1, int x2, ..., int xn) { }}// somewhere in some method fooB bref; int val = bref.bar(y1,y2, , yn);

    74

    callee

    target(instance)receiver(y0 firstactual)

    argumentsactualparametersactuals

    callsite

    caller

  • 75

  • Callingconvention

    controlflow

    infoo

    continue

    76

    controlflow

    inbar

    return

  • Callingconvention

    Thecallingconventiondecideswhichsteps/actionsofmethodinvocation/returnare Donebythecaller Donebythecallee

    andhowanydatatransferisimplemented Wherethedataarestored Dataincludesreturnaddressandreturnvalue Mayhavetoincludetypecasts

    Usuallydefinedforallcompilers/softwaredevelopersonagivenoperatingsystem Ensuresinteroperability

    77

  • Callingconvention

    Stackprincipaldatastructure Controlstack

    Setupbyrun-timesystem Supportedbyinstructionsand/orresources(registers)onsome

    systems

    Activationrecord keepsinformationonmethodinvocationsthatarecurrentlyactive(orlive) Alsoknownasframe

    78

  • Actions

    Considerthismethodinvocation.// in some method fooB bref; int val = bref.bar(y1,y2, , yn);

    Listallthestepsthatarenecessarytoimplementthecallanditsreturn(onasheetofpaper).

    79

  • 80

  • Actions (relatedtomethodinvocation)

    Identifytarget

    Identifystartingaddressofcallee

    Handleparameters Evaluateyi

    Castasnecessary Putintolocationwhereitcanbefound

    Pushontostack Placeintoregister Leavesomewhereelse

    Saveregisters

    Findspacefortemporaries

    81

  • Actions (relatedtomethodinvocation)

    Determineandstorereturnaddress

    Findspaceforreturnvalue

    Setupactivationrecordforcallee Linktoactivationrecordofcaller(controllink)

    Transfercontroltocallee

    82

  • Callling convention

    Someofthesesteps Mustbedonebycaller Mustbedonebycallee

    Methodthatwasinvoked Canbedonebyeitherone

    83

  • Actions (relatedtomethodreturn)

    Transfercontroltocaller/returnaddress

    Deliverreturnvalue

    Removeactivationrecordforcallee Reclaimanytemporarystorage Switchtoactivationrecordofcaller

    84

  • Simpleactivationrecord

    85

    Temp k

    ...

    Temp0

    Local m

    Local0

    oldSP

    oldFP

    Returnaddress

    target(parametery0)

    parametery1

    parameteryn

    Returnvalue

    framepointer

    stackpointer

  • 86

  • Comments

    SufficientforJavaLi Willnotworkforvarargs

    Methodswithavariablenumberofarguments(actuals)

    Parametersarefoundonthestack Actuals:positiveoffsetfromframepointer Offsetrecordedinsymboltable

    Localsarefoundonthestack Negativeoffsetfromframepointer Offsetrecordedinsymboltable

    Temporaryregioncangroww/olimit Temporariescanbeaccessedviaframepointer

    87

  • Symboltable

    Mustcompletesymboltablepriortocodegeneration

    88

    local0 - 4

    local1 - 8

    parameter1 +16

    parameter 2 +20

    return value +24

    this (implicitparameter) + 12

  • Parameterpassing

    (Recall)JavaLi passesallargumentsbyvalue

    Nottheaddressofavariableispassedbutitsvalue

    Thevalueofareferencecanbeusedtoread/writetheobjectthereferencerefersto Butthereferencecannotbechanged

    Atcallsite(ofbref.bar(y1,y2, , yn)) Evaluateyn,pushontostack

    Evaluateyn-1,yn-2,y1,y0 Couldbeanexpression,i.e.bref.bar(y1, a b, , yn) Mayrequirecast

    89

  • Actual-formalcorrespondence

    Otherlanguagesarebasedon(orinclude)differentmodels Languagespecshouldspecifymodel

    Herewelookatthecompilersside7.5.1Call-by-value7.5.2Call-by-reference7.5.3Call-by-result7.5.4Call-by-name

    90

  • 7.5.1Call-by-value

    TheonlyoptioninJava(andJavaLi)

    Easytounderstand Lookatmethodinisolation Withreferencesriskofaliasing

    Easytoimplement Callerknowshowtoevaluateactuals Callee usesaparameterlikealocal initializedbycaller

    Potentiallyinefficient Passanarray/anobjectbyvalue? Mayrequirecopy(timeconsuming) Languagerestrictscall-by-valuetoword-sizeentities(ints,references)

    91

  • 92

  • Adminissues

    Norecitationsessiontoday

    Easterbreakstartssoon Usefreetime(ifany)toworkonHomework3(dueonApril27) Andonoptionalparsing-relatedhomework(HWPRS)

    Outtoday

    Nextrecitation:April27at10:15inCABG61 DiscussionofHomework4(completecodegenerator)

    Willsendoutreminder

    93

  • Wherearewenow?

    Pastfirsthalfofthelecture Covered8weeksofmaterial

    Lexing Parsing Semanticanalysis Codegeneration SomeVM/runtime-relatedissues

    Intheremaining6weekswellcover Programanalysis Registerallocation OtherIRs/JITcompilation(iftimepermits)

    Nextlecture:May4at10:15inCABG61

    94