more risc-v instructions andcs61c/sp18/lec/06/lec06.pdf · • risc-v is example risc instruction...

53
CS 61C: Great Ideas in Computer Architecture More RISC-V Instructions and How to Implement Functions Instructors: Nick Weaver & John Wawrzynek http://inst.eecs.Berkeley.edu/~cs61c/fa17 Spring 2018 - Lecture #6 1

Upload: others

Post on 18-Feb-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

CS61C:GreatIdeasinComputerArchitecture

MoreRISC-VInstructionsand HowtoImplementFunctions

Instructors:NickWeaver&JohnWawrzynek

http://inst.eecs.Berkeley.edu/~cs61c/fa17

Spring2018-Lecture#6 1

Page 2: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Outline• RISC-VISAandC-to-RISC-VReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…

2

Page 3: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Outline• RISC-VISAandC-to-RISC-VReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…

3

Page 4: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

LevelsofRepresentation/Interpretation

lw $t0,0($2)lw $t1,4($2)sw $t1,0($2)sw $t0,4($2)

HighLevelLanguageProgram(e.g.,C)

AssemblyLanguageProgram(e.g.,RISC-V)

MachineLanguageProgram(RISC-V)

HardwareArchitectureDescription(e.g.,blockdiagrams)

Compiler

Assembler

MachineInterpretation

temp=v[k];v[k]=v[k+1];v[k+1]=temp;

0000 1001 1100 0110 1010 1111 0101 1000 1010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111

ArchitectureImplementation

Anythingcanberepresented asanumber,

i.e.,dataorinstructions

LogicCircuitDescription(CircuitSchematicDiagrams) 4

Page 5: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

ReviewFromLastLecture…• Computer’snativeoperationscalledinstructions.Theinstructionset

definesallthevalidinstructions.• RISC-VisexampleRISCinstructionset-usedinCS61C

– Lecture/problemsuse32-bitRV32ISA,bookuses64-bitRV64ISA• Rigidformat:oneoperation,twosourceoperands,onedestination

– add,sub– lw,sw,lb,sbtomovedatato/fromregistersfrom/tomemory

• Simplemappingsfromarithmeticexpressions,arrayaccess,inCtoRISC-Vinstructions

5

Page 6: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Processor

Control

Datapath

Recap:RegistersliveinsidetheProcessor

6

PC

RegistersArithmetic&LogicUnit

(ALU)

Memory Input

Output

Bytes

Enable?Read/Write

Address

WriteData

ReadData

Processor-MemoryInterface I/O-MemoryInterfaces

Program

Data

Page 7: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

RISC-VLogicalInstructions

Logical operationsC

operatorsJava

operatorsRISC-V

instructionsBit-by-bit AND & & andBit-by-bit OR | | orBit-by-bit XOR ^ ^ xorShift left logical << << sllShift right logical >> >> srl

•Usefultooperateonfieldsofbitswithinaword−e.g.,characterswithinaword(8bits)

•Operationstopack/unpackbitsintowords•Calledlogicaloperations

7

Page 8: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Logical Shifting•ShiftLeftLogical:slli x11,x12,2#x11=x12<<2

– Storeinx11thevaluefromx12shifted2bitstotheleft(theyfalloffend),inserting0’sonright;<<inC

Before:00000002hex 00000000000000000000000000000010two

After: 00000008hex 00000000000000000000000000001000twoWhatarithmeticeffectdoesshiftlefthave?

•ShiftRightLogical:srliisoppositeshift;>>–Zerobitsinsertedatleftofword,rightbitsshiftedoffend

8

Page 9: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

ArithmeticShifting• Shiftrightarithmetic(srai)movesnbitstotheright(inserthigh-ordersignbitintoemptybits)

• Forexample,ifregisterx10contained11111111111111111111111111100111two=-25ten

• Ifexecutesrax10,x10,4,resultis: 11111111111111111111111111111110two=-2ten• Unfortunately,thisisNOTsameasdividingby2n

− Failsforoddnegativenumbers− Carithmeticsemanticsisthatdivisionshouldroundtowards0

9

Page 10: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

ComputerDecisionMaking• Basedoncomputation,dosomethingdifferent• NormaloperationonCPUistoexecuteinstructionsinsequence• Needspecialinstructionsforprogramminglanguages:if-statement

• RISC-V:if-statementinstructionis beq register1,register2,L1 means:gotoinstructionlabeledL1

if(valueinregister1)==(valueinregister2) ….otherwise,gotonextinstruction• beqstandsforbranchifequal • Otherinstruction:bneforbranchifnotequal

10

Page 11: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

TypesofBranches• Branch–changeofcontrolflow

• ConditionalBranch–changecontrolflowdependingonoutcomeofcomparison– branchifequal(beq)orbranchifnotequal(bne)– Alsobranchiflessthan(blt)andbranchifgreaterthanorequal(bge)

• UnconditionalBranch–alwaysbranch– aRISC-Vinstructionforthis:jump(j)

11

Page 12: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Outline• AssemblyLanguage• RISC-VArchitecture• Registersvs.Variables• RISC-VInstructions• C-to-RISC-VPatterns• AndinConclusion…

12

Page 13: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

ExampleifStatement• Assumingassignmentsbelow,compileifblock f→x10 g→x11 h→x12 i→x13 j→x14

if (i == j) bne x13,x14,skip f = g + h; add x10,x11,x12 . skip: .

. .

. .

13

Page 14: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Exampleif-elseStatement• Assumingassignmentsbelow,compile f→x10 g→x11 h→x12 i→x13 j→x14

if (i == j) bne x13,x14,else f = g + h; add x10,x11,x12 else j done f = g – h; else: sub x10,x11,x12 done:

14

Page 15: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Magnitude Compares in RISC-V• Untilnow,we’veonlytestedequalities(==and!=inC);

Generalprogramsneedtotest<and>aswell.• RISC-Vmagnitude-comparebranches: “BranchonLessThan” Syntax:blt reg1,reg2, label Meaning: if(reg1<reg2)//treatregistersassignedintegers gotolabel;• “BranchonLessThanUnsigned” Syntax:bltu reg1,reg2, label Meaning: if(reg1<reg2)//treatregistersasunsignedintegers gotolabel;

15

“BranchonGreaterThanorEqual”(andit’sunsignedversion)alsoexists.

Page 16: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

CLoopMappedtoRISC-VAssembly

int A[20];int sum = 0;for (int i=0; i<20; i++) sum += A[i];

# Assume x8 holds pointer to A# Assign x9=A, x10=sum, # x11=i, x13=20add x9, x8, x0 # x9=&A[0]add x10, x0, x0 # sum=0add x11, x0, x0 # i=0addi x13,x0,20 # x13=20Loop:lw x12, 0(x9) # x12=A[i]add x10,x10,x12 # sum+=addi x9,x9,4 # &A[i++]addi x11,x11,1 # i++blt x11,x13,Loop

16

Page 17: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

PeerInstructionWhichofthefollowingisTRUE?

A:add x10,x11,4(x12)isvalidinRV32B:canbyteaddress8GBofmemorywithanRV32wordC:immmustbemultipleof4forlw x10,imm(x10)tobevalidD:Noneoftheabove

17

Page 18: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

PeerInstructionWhichofthefollowingisTRUE?

A:add x10,x11,4(x12)isvalidinRV32B:canbyteaddress8GBofmemorywithanRV32wordC:immmustbemultipleof4forlw x10,imm(x10)tobevalidD:Noneoftheabove

18

Page 19: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Administrivia• TheProject1deadlineextendedtoThursday,11:59pm!• TherewillbeaguerrillasectionThursday7-9PM.• TwoweekstoMidterm#1!• Project2-1releaselaterthisweekorearlynext,due2/16.• Project2-2releaserightaftermidtermanddue2/23.

19

Page 20: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Outline• RISC-VISAandC-to-RISC-VReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…

20

Page 21: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

AssemblertoMachineCode(morelaterincourse)

foo.S bar.S

Assembler Assembler

foo.o bar.o

Linker lib.o

a.out

Assemblersourcefiles(text)

Machinecodeobjectfiles

Pre-builtobjectfilelibraries

Machinecodeexecutablefile

Assemblerconvertshuman-readableassemblycodetoinstructionbitpatterns

21

Page 22: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

HowProgramisStoredMemory

Bytes

Program

Data

OneRISC-VInstruction=32bits22

Page 23: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Processor

Control

Datapath

ProgramExecution

PC

RegistersArithmetic&LogicUnit

(ALU)

Memory

Bytes

InstructionAddress

InstructionBits

Program

Data

• PC(programcounter)isspecialinternalregisterinsideprocessorholdingbyteaddressofnextinstructiontobeexecuted

• Instructionisfetchedfrommemory,thencontrolunitexecutesinstructionusingdatapathandmemorysystem,andupdatesprogramcounter(defaultisadd+4bytestoPC,tomovetonextsequentialinstruction)

23

Page 24: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

HelpfulRISC-VAssemblerFeatures

• Symbolicregisternames– E.g.,a0-a7forargumentregisters(x10-x17)– E.g.,zeroforx0

• Pseudo-instructions– Shorthandsyntaxforcommonassemblyidioms– E.g.,“mv rd, rs” = “addi rd, rs, 0”– E.g.,“li rd, 13” = “addi rd, x0, 13”

24

Page 25: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

RISC-VSymbolicRegisterNames

25

Numbershardwareunderstands

Human-friendlysymbolicnamesinassemblycode

Page 26: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Outline• RISC-VISAandC-to-RISC-VReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…

26

Page 27: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

SixFundamentalStepsinCallingaFunction1. Putparametersinaplacewherefunctioncanaccess

them2. Transfercontroltofunction3. Acquire(local)storageresourcesneededforfunction4. Performdesiredtaskofthefunction5. Putresultvalueinaplacewherecallingcodecanaccess

itandmayberestoreanyregistersyouused6. Returncontroltopointoforigin.(Note:afunctioncan

becalledfromseveralpointsinaprogram.)27

Page 28: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

RISC-VFunctionCallConventions• Registersfasterthanmemory,sousethem• a0–a7 (x10-x17):eightargumentregisterstopassparametersandtworeturnvalues(a0-a1)

• ra:onereturnaddressregisterforreturntothepointoforigin(x1)

28

Page 29: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

InstructionSupportforFunctions(1/4) ... sum(a,b);... /* a,b:s0,s1 */

} int sum(int x, int y) { return x+y; }

address (shown in decimal) 1000 1004 1008 1012 1016 … 2000 2004

CRISC-V InRISC-V,allinstructionsare4bytes,and

storedinmemoryjustlikedata.Sohereweshowtheaddressesofwheretheprogramsarestored.

29

Page 30: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

InstructionSupportforFunctions(2/4) ... sum(a,b);... /* a,b:s0,s1 */

} int sum(int x, int y) { return x+y; }

address (shown in decimal) 1000 mv a0,s0 # x = a 1004 mv a1,s1 # y = b 1008 addi ra,zero,1016 #ra=1016 1012 j sum #jump to sum 1016 … # next instruction … 2000 sum: add a0,a0,a1 2004 jr ra # new instr. “jump register”

30

CRISC-V

Page 31: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

InstructionSupportforFunctions(3/4) ... sum(a,b);... /* a,b:s0,s1 */

} int sum(int x, int y) { return x+y; }

2000 sum: add a0,a0,a1 2004 jr ra # new instr. “jump register”

• Question:Whyusejrhere?Whynotusej?

• Answer:summightbecalledbymanyplaces,sowecan’treturntoafixedplace.Thecallingproctosummustbeabletosay“returnhere”somehow.

31

CRISC-V

Page 32: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

InstructionSupportforFunctions(4/4)• Singleinstructiontojumpandsavereturnaddress:jumpandlink(jal)• Before:

1008 addi ra,zero,1016 #ra=1016 1012 j sum #goto sum

• After:1008 jal sum # ra=1012,goto sum

• Whyhaveajal?– Makethecommoncasefast:functioncallsverycommon– Reduceprogramsize– Don’thavetoknowwherecodeisinmemorywithjal!

32

• Returnfromfunction:jumpregisterinstruction(jr)– Unconditionaljumptoaddressspecifiedinregister:jr ra – Assemblershorthand:ret = jr ra

Page 33: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Outline• RISC-VISAandC-to-RISC-VReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…

33

Page 34: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Exampleint Leaf(int g, int h, int i, int j) { int f; f = (g + h) – (i + j); return f; } • Parametervariablesg,h,i,andjinargumentregistersa0,a1,a2,

anda3. • Assumewecomputefbyusings0 and s1

34

Page 35: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

WhereAreOldRegisterValuesSaved toRestoreThemAfterFunctionCall?

• Needaplacetosaveoldvaluesbeforecallfunction,restorethemwhenreturn

• Idealisstack:last-in-first-outqueue(e.g.,stackofplates)– Push:placingdataontostack– Pop:removingdatafromstack

• Stackinmemory,soneedregistertopointtoit• spisthestackpointerinRISC-V(x2)• spalwayspointstothelastusedplaceonthestack • Conventionisgrowstackdownfromhightolowaddresses

– Pushdecrementssp,Popincrementssp35

Page 36: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

RISC-VCodeforLeaf()Leaf: addi sp,sp,-8 # adjust stack for 2 items sw s1, 4(sp) # save s1 for use afterwards sw s0, 0(sp) # save s0 for use afterwards

add s0,a0,a1 # s0 = g + h add s1,a2,a3 # s1 = i + j sub a0,s0,s1 # return value (g + h) – (i + j)

lw s0, 0(sp) # restore register s0 for caller lw s1, 4(sp) # restore register s1 for caller addi sp,sp,8 # adjust stack to delete 2 items jr ra # jump back to calling routine

36

Page 37: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

StackBefore,During,AfterFunction• Needtosaveoldvaluesofs0ands1

37

sp

Beforecall

spSaved s1

Duringcall

Saved s0

sp

Aftercall

Saved s1Saved s0

Page 38: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Break!

38

Page 39: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

NewRISC-Vbook!• “TheRISC-VReader”,DavidPatterson,

AndrewWaterman

• AvailablefromAmazon • Printedition$19.99• Kindleeditiontofollowatsomepoint

• Recommended,notrequired

39

Page 40: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

WhatIfaFunctionCallsaFunction?RecursiveFunctionCalls?

• Wouldclobbervaluesina0-a7andra • Whatisthesolution?

40

Page 41: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

NestedProcedures(1/2)int sumSquare(int x, int y) { return mult(x,x)+ y; }

• SomethingcalledsumSquare,nowsumSquareiscallingmult

• Sothere’savalueinrathatsumSquarewantstojumpbackto,butthiswillbeoverwrittenbythecalltomult

NeedtosavesumSquare returnaddressbeforecalltomult

41

Page 42: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

NestedProcedures(2/2)• Ingeneral,mayneedtosavesomeotherinfoinadditiontora.

• WhenaCprogramisrun,therearethreeimportantmemoryareasallocated:– Static:Variablesdeclaredonceperprogram,ceasetoexistonlyafterexecutioncompletes-e.g.,Cglobals

– Heap:Variablesdeclareddynamicallyviamalloc – Stack:Spacetobeusedbyprocedureduringexecution;thisiswherewecansaveregistervalues

42

Page 43: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

OptimizedFunctionConventionToreduceexpensiveloadsandstoresfromspillingandrestoringregisters,RISC-Vfunction-callingconventiondividesregistersintotwocategories:

1. Preservedacrossfunctioncall– Callercanrelyonvaluesbeingunchanged– sp,gp,tp,“savedregisters”s0-s11(s0isalsofp)

2. Notpreservedacrossfunctioncall– Callercannotrelyonvaluesbeingunchanged– Argument/returnregistersa0-a7,ra,“temporaryregisters”

t0-t643

Page 44: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

PeerInstruction• WhichstatementisFALSE?• A:RISC-Vusesjaltoinvokeafunctionand jrtoreturnfromafunction

• B: jalsavesPC+1inra• C: Thecalleecanusetemporaryregisters(ti)without

savingandrestoringthem• D: Thecallercanrelyonsaveregisters(si)withoutfearof

calleechangingthem

44

Page 45: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

PeerInstruction• WhichstatementisFALSE?• A:RISC-Vusesjaltoinvokeafunctionand jrtoreturnfromafunction

• B: jalsavesPC+1inra• C: Thecalleecanusetemporaryregisters(ti)without

savingandrestoringthem• D: Thecallercanrelyonsaveregisters(si)withoutfearof

calleechangingthem

45

Page 46: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

AllocatingSpaceonStack• Chastwostorageclasses:automaticandstatic

– Automaticvariablesarelocaltofunctionanddiscardedwhenfunctionexits

– Staticvariablesexistacrossexitsfromandentriestoprocedures• Usestackforautomatic(local)variablesthataren’tinregisters

• Procedureframeoractivationrecord:segmentofstackwithsavedregistersandlocalvariables

46

Page 47: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

StackBefore,During,AfterFunction

47

sp

Beforecall

sp

Duringcall

Savedargumentregisters(ifany)

Savedreturnaddress(ifneeded)

Savedsavedregisters(ifany)Localvariables

(ifany)

sp

Aftercall

Page 48: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

UsingtheStack(1/2)• Sowehavearegisterspwhichalwayspointstothelastusedspaceinthestack

• Tousestack,wedecrementthispointerbytheamountofspaceweneedandthenfillitwithinfo

• So,howdowecompilethis? int sumSquare(int x, int y) {

return mult(x,x)+ y; }

48

Page 49: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

UsingtheStack(2/2)

49

sumSquare: addi sp,sp,-8 # reserve space on stack sw ra, 4(sp) # save ret addr sw a1, 0(sp) # save y mv a1,a0 # mult(x,x) jal mult # call mult lw a1, 0(sp) # restore y add a0,a0,a1 # mult()+y lw ra, 4(sp) # get ret addr addi sp,sp,8 # restore stack jr ra mult: ...

int sumSquare(int x, int y) { return mult(x,x)+ y; }

“push”

“pop”

Page 50: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

WhereistheStackinMemory?• RV32convention(RV64andRV128havedifferentmemorylayouts)• Stackstartsinhighmemoryandgrowsdown

– Hexadecimal(base16):bfff_fff0hex• RV32programs(textsegment)inlowend

– 0001_0000hex • staticdatasegment(constantsandotherstaticvariables)abovetext

forstaticvariables– RISC-Vconventionglobalpointer(gp)pointstostatic– RV32gp=1000_0000hex

• Heapabovestaticfordatastructuresthatgrowandshrink;growsuptohighaddresses

50

Page 51: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

RV32MemoryAllocation

51

Page 52: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

Outline• RISC-VISAandC-to-RISC-VReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…

52

Page 53: More RISC-V Instructions andcs61c/sp18/lec/06/lec06.pdf · • RISC-V is example RISC instruction set - used in CS61C – Lecture/problems use 32-bit RV32 ISA, book uses 64-bit RV64

AndinConclusion…• Functionscalledwithjal,returnwithjr ra.• Thestackisyourfriend:Useittosaveanythingyouneed.Justleaveitthe

wayyoufoundit!• Instructionsweknowsofar…

Arithmetic:add, addi, subMemory:lw, sw, lb, lbu, sbDecision:beq, bne, blt, bgeUnconditionalBranches(Jumps):j, jal, jr

• Registersweknowsofar– Allofthem!– a0-a7forfunctionarguments,a0-a1forreturnvalues– sp,stackpointer,rareturnaddress– s0-s11savedregisters– t0-t6temporaries– zero

53