Download Compiler Design

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Ada (programming language) wikipedia , lookup

Abstraction (computer science) wikipedia , lookup

Scala (programming language) wikipedia , lookup

Library (computing) wikipedia , lookup

Java (programming language) wikipedia , lookup

Join-pattern wikipedia , lookup

ALGOL 68 wikipedia , lookup

Structured programming wikipedia , lookup

Falcon (programming language) wikipedia , lookup

C syntax wikipedia , lookup

Object-oriented programming wikipedia , lookup

Go (programming language) wikipedia , lookup

PL/I wikipedia , lookup

Java performance wikipedia , lookup

C++ wikipedia , lookup

Assembly language wikipedia , lookup

Parsing wikipedia , lookup

C Sharp syntax wikipedia , lookup

Program optimization wikipedia , lookup

Interpreter (computing) wikipedia , lookup

Name mangling wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Compiler wikipedia , lookup

Cross compiler wikipedia , lookup

Transcript
CompilerDesign
Spring2017
1.1Simplecompilermodel
Dr.Zoltán Majó
CompilerGroup– JavaHotSpot VirtualMachine
OracleCorporation
1
1.1Simpleandrealisticcompilermodel
§ Simple:Canbehandledinonesemester,8credits
§ Twopersonstoworkonthesameproject(moreaboutteamslater)
§ Realistic:Experienceproblemsencounteredbyrealcompilers
§ Mirrorsstructureofmanycompilers
2
Compilermodel
Sourceprogram
Compiler
ASMfile
Assembler
Objectfile
4
Compilermodel
§ Compilationpriortoexecution
§ AOT“Aheadof(Execution)Time”compilation
§ Commonlyusedforlanguageswithoutlanguage-specificexecution
environments(e.g.,C,C++)
§ AvailableinJavaaswell(IBMJ9,OracleHotSpot)
§ Othermodel:Continuouscompilation
§ JIT“JustinTime”compilation
§ Usually:optimizationofmethodsthatarefrequentlyinvoked(hot)
§ Commonlyusedwithlanguagevirtualmachines(e.g.,JavaVM)
§ E.g.,HotSpot JVMhastwoJITcompilers(C1andC2)
5
8
9
IR– Intermediaterepresentation
§ Compiler-internalrepresentation
§ E.g.,compilermustdistinguishbetweennamesindifferentscopes
§ E.g.,manyprogramsworkwithvariables,computersworkwithlocations
§ Mustexpressalllanguageconstructs/concepts
§ CodegeneratormapsIRtoassemblycode
§ Machinecodeanotheroption
§ No“best”IR– allarecompromises
10
13
15
Notagoodidea!
16
Checkinginput(PL1)
§ Compilermustcheckthatprogramcanbetranslatedcorrectly
§ Theprogrammaystillbeflawed
§ Executionbehavesasexpected(orspecified)
§ Issuesoraspectsthatacompilershouldcheck
Talktoyourneighborandcollectalistofchecksthatacompiler
shoulddo(todeterminethatprogramcanbetranslatedcorrectly)
17
19
20
Issues/Properties
§ Allvariables/methods/symbolsdefined
§ Allvariablesinitializedbeforeuse
§ Programhasnosyntaxerrors
§ Definedprogramstart(mainmethodifappropriate)
§ Exceptionsarecaught
§ Nonull-pointeraccesses
§ Noout-of-boundaccessesforarrays,records/instances
§ Programtypechecks
§ Nounusedvariables/fields
§ Returnstatementisreachable
§ Executionreachesendofprogram
21
Issues/Properties(Continued)
§ Allfunctionsreturnvalue
§ Rulesofthemodulesystemfollowed
§
Noaccesstoprivate/protectedmembersunlesslegal
§ Nocycleininheritancegraph
§ Interfaces/abstractfunctionsimplemented
§ Loopsterminate
§ Programexecuteswithinagiventime
§ Programstayswithinpowerbudget
§ Allvaluescomputedcanberepresented
22
24
CompilerDesign
Spring2017
1.2Adminissues
2.0Translationofassignmentstatements
Dr.Zoltán Majó
CompilerGroup– JavaHotSpot VirtualMachine
OracleCorporation
25
2.0Translationofassignmentstatements
§ Assignmentstatements(stmts)
§ Foundinmanyprogramminglanguages
§ Welookatsimpleassignmentstmts
§ Forexample:A = B + 1
§ Issues
§ TypesofA andB:32-bitinteger(asinC,C++,Java,Pascal)
§ Onlyscalarentities
§ Only32-bitintegerconstants
26
Translateasingleassignmentstmt
§ Examples
int A, B, C;
A = B + C;
int A, B, C, D;
A = B + C + D;
int A, B, C;
A = B + C + 2 + 4;
§ Simple.
§ Yourtask
§ Givenasingleassignmentstatement,generatecodeforthatstatement.
§ WegiveyoutheIRforthestmt
27
Astart
§ Useassignmentstmt toexplore(partof)theIR
§ Canyougenerate“optimal”code?
§ Whatis“optimal”?
§ Isthereanefficientalgorithm?
§ (Easy)extension:onestmt à listofstmts
§ Knownasablock
§ Solutiontothisassignmentreusedlater(Homework4)
28
2.1Intermediaterepresentation
§ ThereexistmanydifferentIRs
§ NosingleIRisthebest– allarecompromises
§ SomecompilersuseseveralIRs
§ High-levelIR:representinputprogram
§ Analyze,addannotations
§ Low-levelIR:exposemoredetails(e.g.,machine-leveldetails)
§ IRforthiscourse:tree-based
§ Easytounderstand
§ Easytoextend:treeà forest
§ ClosetoIRusedinrealcompilers
§ MoresophisticatedIRs:discussedlater
§ Alsoin“AdvancedCompilerDesign”
29
Tree-basedIR
§ Oneassignmentstmt à onebinary tree
int A, B, C, D;
=
A = B + C * D;
L
§ Thetreehasaroot
§ Topnode:Assignment
§ Rightandleftsubtrees
defines
operation(’+’)
R
A
+
delivers
targetaddress
ofassignment
delivers
a value
defines
operation(‘*’)
B
*
C
delivers
a value
D
delivers
a value
30
Approach
§ Treedescribescomputationtobedone
§ Determines“evaluationorder”
§ FirstC * D
§ ThenaddproducttoB
§ Compileonetreeatatime
§ Codegenerator(CG)“visits”anode
§ Alsoknownas:CG“evaluates”anode
§ Steps
§
§
§
§
§
Bookkeeping
(maybe)Generatecode
Visitchildren
Bookkeeping
(maybe)Generatecode
31
33
Options
§ Example
int A, B, C, D;
A = B + C + D;
+
+
B
+
C
C
D
+
+
B
D
+
D
C
B
§ Whyshouldwecare?
34
Evaluationorder
§ Treedeterminesevaluationorder
§ Comparetwoversions(ontheassemblylevel)
§ Version1
add B, C
add B, D
// B = B + C
// B = B + D
§ Version2
add B, D // B = B + D
add B, C // B = B + C
§ Resultsmaydiffer
§ Floatingpointarithmeticisnotassociative
35
Non-associativearithmetic
§ (X+fp Y)+fp ZispossiblydifferentfromX+fp (Y+fp Z)
§ +fp floatingpointarithmetic
36
Howtoproceed?
§ Whoshoulddecidewhichtreetobuild?
Discusswithyourneighboriftheanswerisobvious.
37
Howtoproceed?
§ Whoshoulddecidewhichtreetobuild?
§ Programminglanguagespecificationshouldaddressthisissue
§ Maybeallowuseroptions
§ E.g.,ICC(IntelCCompiler)supports
§ –fp-model precise
§ –fp-model source
38
CompilerDesign
Spring2017
1.2Adminissues
Dr.Zoltán Majó
CompilerGroup– JavaHotSpot VirtualMachine
OracleCorporation
39
Topicsforthisclass
1. Compilerdesign:Structureofasimplecompiler
2. Softwareengineering
§ Howtodesignanon-trivialsystem
§ Softwarereuse
3. Programming
§ Homework:Designandimplementationofacompiler
§ Corepartofthecourse
40
What(someof)youexpectfromthisclass
§ Somefeedback
§ ”Understandhowcompilerswork”
§ “Howtobuildacompiler”
§ “Betterunderstandingofhowmycodegetstotheactualexecution
§ Also:
§ “Agoodgrade”
§ “8creditpoints”
41
43
Homework
§ Buildacompiler
§ 5(or6)well-definedandeasysteps
§ Teamsoftwopersons
§ Stillalotofwork
§ Usecompilerframework(providedbyTAs)
44
TargetlanguageL2
§ Observation:Resourceissuescriticalincompilation
§ Userealmachine
§ Realmachineshaverealflaws
§ Onlypaperdesignsareperfect
§ TargetlanguageL2:32-bitx86assembler
§ Objective
§ Understandissues
§ Notbecomeexpertinx86assemblyprogramming
§ Knowledgefrom“ComputerArchitectureandSystemsProgramming”
sufficient
45
46
Sourcelanguage L1
§ ShouldweimplementaCcompiler?
+ Ciswidelyused
+ Cisfairlycomplicated
- Cisapain(tograde)
- Cisnotobject-oriented
§ ShouldweimplementaJavacompiler?
+ Alltheabove
- (Alittle)toomuch
47
SourcelanguageL1
§ Object-oriented
§ Polymorphism
§ Class-based
§ Singleinheritance
§ ….subsetofJava:JavaLi
§ Nofinalizers
§ Nostaticfields/methods
§ Nomulti-threading
§ Nomodulesystem
§ …
48
JavaLi
§ ExampleJavaLi code
class Record {
int j;
int next() {
j = j + 1;
return j;
}
}
§ Seecoursewebsiteforspecification
49
Grading
§ Finalexam:TBD
§ 2hours
§ Duringexaminationperiod
§ Homeworkdoneinteams
§ Graded
§ 50%ofthefinalgradeisdeterminedbythegradesyougetforhomework
§ Ifyoucan’tdohomeworkbyduedate:
TalktotheTAsortheinstructorbeforethedeadline(wearereasonable)
50
Homework
§ Bothmembersofateammustcontribute
§ Bothofyouareresponsibleforthesolutionyouturnin
§ Wereservetherighttoaskquestionsaboutthedesign,
implementation,testingplan,etc.
§ Youmustturninyourownwork
§ “Finding”asolutioninasomeoneelse’sdirectoryischeating
§ ETHhasapolicyoncheating.
51
52
53
55
Homework
§ Wedonotwanttoplaypolice
§ Dothehomeworkyourself
§ Discussionsarefine(andencouraged)…
§ ...copyingcodeisnot
56
1st homework
§ Formateamof2persons
§ Chooseyourteam’snamewisely
§ Registerteam
§ Detailsonthewebpage
§ Writeasmall(assembly)program
§ Seewebpage
§ Submitit
§ Usingsubversion,moreaboutthatsoon
§ Noteampartner?
§ Cometofrontafterclass(preferablytoday)
§ Writeprogram(above)onyourown
57
Summary
§ L1:JavaLi
§ Classes/methods
§ Primitivetypeint
§ Inheritance(single)
§ NOmultipleinheritance,NOexceptions,NOthreads,NOfinalizer
§ L2:32-bitx86
§ LH (compilerlanguage):Java
§ Firsthomework
§ Formteam,writesmallassemblyprogram
60
Non-topics(forthisclass)
§ Efficiencyofgeneratedcode(inL2)
§ Efficiencyofcompiler
§ Can’tmakestupidmistakes
§ Easeofre-targeting(fromL2 toL3)
§ Easeofporting(fromLH toLH’)
61
Literature
1. Aho/Lam/Sethi/Ullman:Compilers:
Principles,Techniques,andTools,2nd edition
2. Muchnick:
AdvancedCompilerDesignandImplementation
3. Booksonpatterns,frameworks,softwaredesign
62