assembler 2003
TRANSCRIPT
3803
1
1
Linguaggio Assembler
Andrea CoccoliACoccoliguestcnucecnrit
2
In dice
bull L inguaggio ad alto livello linguaggio assembler elinguaggio macchina
bull I l linguaggio assembler MI PS istruzioni ar itmetiche ditrasfer imento dati e di salto
bull Conversione linguaggio assembler in linguaggio macchina
bull Gestione delle procedure Uso della pila
bull Modi di indir izzamento
bull Sintassi di un programma in assembler M IPS
bull SPIM
bull Confr onto con altre architetture PowerPC e Intel 80x86
3803
2
3
In tr oduzione
bull le CPU lavorano con linguaggio macchinandash sequenza di cifre binarie
bull I l linguaggio assembler ersquo la rappresentazionesimbolica (mnemonica) della codifica binar ia usata dal
calcolatore (linguaggio macchina)ndash simboli al posto di bit
ndash codici delle istruzioni (opcodes)
ndash registri
ndash uso di etichette
ndash macro
bull L a codifica binaria delle istr uzioni si trov a in memor ia
4
L inguaggio macchina
bull Si intende lrsquoin sieme delle operazioni direttamenteeseguibili dallrsquohard ware
bull Ogni oper azione ersquo richiesta da unrsquoistruzione
bull Un insieme di istruzioni costituisce un programma
bull ogni istruzione deve specificare che tipo di operazione
ersquo r ichiesta e quali sono i suoi operandi
3803
3
5
L inguaggio assembler
bull Piugrave primi tivo dei linguaggi di alto livello
eg manca un controllo di flusso sofisticato
bull Molto restritti vo
eg Istruzioni Aritmetiche del MI PS
bull Noi lavoreremo con lrsquoarchitettura d el set di istruzioni MI PS
ndash simile ad altre architetture sviluppate a partire dagl i anni lsquo80
ndash usata da NEC Nintendo Silicon Graphics Sony
bull Obiettivi di Progetto massimizzare la perfor mance eminimizzare il costo ridurre il tempo di progettazione
6
001001111011110111111111111000001010111110111111000000000001010010101111101001000000000000100000101011111010010100000000001001001010111110100000000000000001100010101111101000000000000000011100100011111010111000000000000111001000111110111000000000000001100000000001110011100000000000011001001001011100100000000000000000010010100100000001000000000110010110101111101010000000000000011100000000000000000001111000000100100000001100001111110010000010000100010100001000001111111111110111101011111011100100000000000110000011110000000100000100000000000010001111101001010000000000011000000011000001000000000000111011000010010010000100000001000011000010001111101111110000000000010100001001111011110100000000001000000000001111100000000000000000100000000000000000000001000000100001
text
align 2
globl mainmain
subu $sp $sp 32sw $ra 20($sp )sd $a0 32($ sp)sw $0 24($sp)sw $0 28($sp)
looplw $t6 28($sp)mul $t7 $t6 $t6lw $t8 24($sp)addu $t9 $t8 $t7w $t9 24($ sp)addu $t0 $t6 1sw $t0 28($sp)ble$t0 100 loopla $a0 strlw $a1 24($sp)jal printfmove$v0 $0lw $ra 20($sp)ddu $sp $sp 32jr $radataalign 0
strasciiz The sum from 0 100 is d n
Programma che ca lcola e stampa la somma dei q uad rati dei pri mi 100 interi
inclu de ltstdiohgtint main (int argc char argv[])int iint sum = 0for (i = 0 i lt= 100 i = i + 1) sum = sum + i i printf (The sum from 0 100 is dn sum)
3803
4
7
Gerarchia di tr asformazioneProgramma in C
Programma in linguaggio assembler
Assemblatore
M odulo oggetto Linguaggio macchina M odulo oggetto Librerie
Linker
Eseguibi le
Loader
M emoria
Compilatore
8
Gerarchia di tr asformazione
Un programma scri tto in linguaggio ad alto livello viene
bull compilato in linguaggio assembler
bull assemblato per ottener e un modulo oggetto in linguaggiomacchina
bull il linker combina uno o piugrave moduli oggetto con le
procedure contenute nelle libreri e per esplicitare tutti iriferimenti incrociati
bull il loader colloca il codice macchina in opportunelocazioni di memoria in modo che possa esser e eseguitodal processore
3803
5
9
Vantaggi e svantaggi del li nguaggio assembler
bull Vantaggindash velocitagrave drsquoesecuzione (es calcolatori embedded)
ndash occupazione di memoria
ndash collegabile a programmi ad alto livello
ndash possibilitagrave di usare istruzioni specializzate
bull Svantaggindash minore portabilitagrave
ndash fattore di espansione elevato =gt minore produttivitagrave
ndash minore leggibilitagrave
ndash no programmazione strutturata
bull Nota la perfor mance deve esser e valutata sulleistruzioni reali
10
Gli assemblator i
bull I l processo di traduzione ersquo costitui to da due partindash traduzione in indirizzi delle locazioni di memoria etichettate
ndash traduzione istruzioni assembler (codice operativo identif icatori diregistri etichette) in istruzione macchina
bull File oggettondash etichetta esterna (o globale)
ndash etichetta locale (funzione static in C)
bull Rifer imenti in avanti =gt tabella dei simboli
3803
6
11
Il for mato del f ile oggetto
bull Ersquo composto da 6 partindash Intestazione del f ile oggetto
ndash Segmento di testo
ndash Segmento di dato
ndash Informazioni di rilocazione
ndash Tabella dei simboli
ndash Informazioni per il debugger
bull Funzionalitagrave aggiuntiv endash direttive per la codifica dei dati
ndash macro
12
L inker - Loader - Uso del la memor iabull Compilazione separata =gt diversi moduli
bull I l linker unisce i fi lesndash cerca le procedure usate nelle librerie
ndash riloca i f ile oggetto
ndash risolve i riferimenti tra files
bull I l loader (in unix)ndash lettura dellrsquointestazione del file eseguibile per determinare la sua
dimensione
ndash creazione di uno spazio di indirizzamento sufficiente
ndash copia delle istruzioni e dei dati dal file eseguibile alla memoria
ndash copia nello stack degli eventuali parametri passati al programmaprincipale
ndash inizializzazione dei registri dellrsquo elaboratore (es stack pointerhellip)
ndash salto ad una procedura di inizializzazione (start-up routine) chechiama la procedura principale del programma (main)
3803
7
13
Ar itm eti ca MIPS
bull Tutte le istruzioni hanno 3 oper andi
bull Una linea puograve contenere una sola istruzione
bull L rsquoord ine degli operandi ersquo fissato (destinazione per pr ima)
bull Formaoperatore operando1 operando2 operando3
bull Significatooperando1 = operando2 operatore operando3
bull Esempio codice MIPS add $s0 $s1 $s2
codice C a = b + c
14
Ar itm eti ca MIPSbull Principio di progetto1 semplificare per fav or ire la
regolaritagrave
bull Svantaggi della regolar itagrave
C code a = b + c + d
e = f - a
MI PS code add $t 0 $s1 $s2
add $s0 $t 0 $s3
sub $s4 $s5 $s0
bull Gli operandi devono essere r egistrindash solo 32 registri da 4Bytes (= 1 Word)
bull Principio di progetto2 dimensioni minori =gt maggiorevelocitagrave
3803
8
15
Convenzioni sullrsquo uso dei r egistr i
Nome Numero Uso$zero 0 il valore costante 0$v0-$v1 2-3 valori per risultati di espressioni$a0-$a3 4-7 argomenti$t 0-$t 7 8-15 temporanei
$s0-$s7 16-23 salvati$t 8-$t 9 24-25 altri temporanei$gp 28 global pointer
$sp 29 stack pointer$f p 30 frame pointer$r a 31 return address$at 1 riservato
$k0 26 riservato$k1 27 riservato
Registro l ocazione di memoria elementare all rsquointerno del processore
16
Moltip l icazione e divisione
bull Cop pia di regis t ri 32 bit ( HiLo ) che contengono il p ro dotto
di una moltiplic azione (mult $s2$s3) ed il resto ed il
quoziente ris p ett ivamente di una div isione ( div $s2$s3)
bull Istr uzioni mf l o mf hi per accedere ai r egistri Hi e Lo
bull Esempiondash mult $s2$s3ndash mflo $s1 $s1 = Lo (copia di L o in $s1)
bull Compito del programmator e evitare lrsquo overflow e cont rollare chenon ci siano divisioni impr opr ie (per zero)
Istruzione Esempio Signifi cato Commenti
move from Hi mfhi $s1 $s1 = Hi Copia Hi in $s1
move from Lo mflo $s1 $s1 = Lo Copia Lo in $s1
move to Hi mthi $s1 Hi = $s1 Copia $s1 in Hi
move to Lo mtlo $s1 Lo = $s1 Copia $s1 in Lo
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
2
3
In tr oduzione
bull le CPU lavorano con linguaggio macchinandash sequenza di cifre binarie
bull I l linguaggio assembler ersquo la rappresentazionesimbolica (mnemonica) della codifica binar ia usata dal
calcolatore (linguaggio macchina)ndash simboli al posto di bit
ndash codici delle istruzioni (opcodes)
ndash registri
ndash uso di etichette
ndash macro
bull L a codifica binaria delle istr uzioni si trov a in memor ia
4
L inguaggio macchina
bull Si intende lrsquoin sieme delle operazioni direttamenteeseguibili dallrsquohard ware
bull Ogni oper azione ersquo richiesta da unrsquoistruzione
bull Un insieme di istruzioni costituisce un programma
bull ogni istruzione deve specificare che tipo di operazione
ersquo r ichiesta e quali sono i suoi operandi
3803
3
5
L inguaggio assembler
bull Piugrave primi tivo dei linguaggi di alto livello
eg manca un controllo di flusso sofisticato
bull Molto restritti vo
eg Istruzioni Aritmetiche del MI PS
bull Noi lavoreremo con lrsquoarchitettura d el set di istruzioni MI PS
ndash simile ad altre architetture sviluppate a partire dagl i anni lsquo80
ndash usata da NEC Nintendo Silicon Graphics Sony
bull Obiettivi di Progetto massimizzare la perfor mance eminimizzare il costo ridurre il tempo di progettazione
6
001001111011110111111111111000001010111110111111000000000001010010101111101001000000000000100000101011111010010100000000001001001010111110100000000000000001100010101111101000000000000000011100100011111010111000000000000111001000111110111000000000000001100000000001110011100000000000011001001001011100100000000000000000010010100100000001000000000110010110101111101010000000000000011100000000000000000001111000000100100000001100001111110010000010000100010100001000001111111111110111101011111011100100000000000110000011110000000100000100000000000010001111101001010000000000011000000011000001000000000000111011000010010010000100000001000011000010001111101111110000000000010100001001111011110100000000001000000000001111100000000000000000100000000000000000000001000000100001
text
align 2
globl mainmain
subu $sp $sp 32sw $ra 20($sp )sd $a0 32($ sp)sw $0 24($sp)sw $0 28($sp)
looplw $t6 28($sp)mul $t7 $t6 $t6lw $t8 24($sp)addu $t9 $t8 $t7w $t9 24($ sp)addu $t0 $t6 1sw $t0 28($sp)ble$t0 100 loopla $a0 strlw $a1 24($sp)jal printfmove$v0 $0lw $ra 20($sp)ddu $sp $sp 32jr $radataalign 0
strasciiz The sum from 0 100 is d n
Programma che ca lcola e stampa la somma dei q uad rati dei pri mi 100 interi
inclu de ltstdiohgtint main (int argc char argv[])int iint sum = 0for (i = 0 i lt= 100 i = i + 1) sum = sum + i i printf (The sum from 0 100 is dn sum)
3803
4
7
Gerarchia di tr asformazioneProgramma in C
Programma in linguaggio assembler
Assemblatore
M odulo oggetto Linguaggio macchina M odulo oggetto Librerie
Linker
Eseguibi le
Loader
M emoria
Compilatore
8
Gerarchia di tr asformazione
Un programma scri tto in linguaggio ad alto livello viene
bull compilato in linguaggio assembler
bull assemblato per ottener e un modulo oggetto in linguaggiomacchina
bull il linker combina uno o piugrave moduli oggetto con le
procedure contenute nelle libreri e per esplicitare tutti iriferimenti incrociati
bull il loader colloca il codice macchina in opportunelocazioni di memoria in modo che possa esser e eseguitodal processore
3803
5
9
Vantaggi e svantaggi del li nguaggio assembler
bull Vantaggindash velocitagrave drsquoesecuzione (es calcolatori embedded)
ndash occupazione di memoria
ndash collegabile a programmi ad alto livello
ndash possibilitagrave di usare istruzioni specializzate
bull Svantaggindash minore portabilitagrave
ndash fattore di espansione elevato =gt minore produttivitagrave
ndash minore leggibilitagrave
ndash no programmazione strutturata
bull Nota la perfor mance deve esser e valutata sulleistruzioni reali
10
Gli assemblator i
bull I l processo di traduzione ersquo costitui to da due partindash traduzione in indirizzi delle locazioni di memoria etichettate
ndash traduzione istruzioni assembler (codice operativo identif icatori diregistri etichette) in istruzione macchina
bull File oggettondash etichetta esterna (o globale)
ndash etichetta locale (funzione static in C)
bull Rifer imenti in avanti =gt tabella dei simboli
3803
6
11
Il for mato del f ile oggetto
bull Ersquo composto da 6 partindash Intestazione del f ile oggetto
ndash Segmento di testo
ndash Segmento di dato
ndash Informazioni di rilocazione
ndash Tabella dei simboli
ndash Informazioni per il debugger
bull Funzionalitagrave aggiuntiv endash direttive per la codifica dei dati
ndash macro
12
L inker - Loader - Uso del la memor iabull Compilazione separata =gt diversi moduli
bull I l linker unisce i fi lesndash cerca le procedure usate nelle librerie
ndash riloca i f ile oggetto
ndash risolve i riferimenti tra files
bull I l loader (in unix)ndash lettura dellrsquointestazione del file eseguibile per determinare la sua
dimensione
ndash creazione di uno spazio di indirizzamento sufficiente
ndash copia delle istruzioni e dei dati dal file eseguibile alla memoria
ndash copia nello stack degli eventuali parametri passati al programmaprincipale
ndash inizializzazione dei registri dellrsquo elaboratore (es stack pointerhellip)
ndash salto ad una procedura di inizializzazione (start-up routine) chechiama la procedura principale del programma (main)
3803
7
13
Ar itm eti ca MIPS
bull Tutte le istruzioni hanno 3 oper andi
bull Una linea puograve contenere una sola istruzione
bull L rsquoord ine degli operandi ersquo fissato (destinazione per pr ima)
bull Formaoperatore operando1 operando2 operando3
bull Significatooperando1 = operando2 operatore operando3
bull Esempio codice MIPS add $s0 $s1 $s2
codice C a = b + c
14
Ar itm eti ca MIPSbull Principio di progetto1 semplificare per fav or ire la
regolaritagrave
bull Svantaggi della regolar itagrave
C code a = b + c + d
e = f - a
MI PS code add $t 0 $s1 $s2
add $s0 $t 0 $s3
sub $s4 $s5 $s0
bull Gli operandi devono essere r egistrindash solo 32 registri da 4Bytes (= 1 Word)
bull Principio di progetto2 dimensioni minori =gt maggiorevelocitagrave
3803
8
15
Convenzioni sullrsquo uso dei r egistr i
Nome Numero Uso$zero 0 il valore costante 0$v0-$v1 2-3 valori per risultati di espressioni$a0-$a3 4-7 argomenti$t 0-$t 7 8-15 temporanei
$s0-$s7 16-23 salvati$t 8-$t 9 24-25 altri temporanei$gp 28 global pointer
$sp 29 stack pointer$f p 30 frame pointer$r a 31 return address$at 1 riservato
$k0 26 riservato$k1 27 riservato
Registro l ocazione di memoria elementare all rsquointerno del processore
16
Moltip l icazione e divisione
bull Cop pia di regis t ri 32 bit ( HiLo ) che contengono il p ro dotto
di una moltiplic azione (mult $s2$s3) ed il resto ed il
quoziente ris p ett ivamente di una div isione ( div $s2$s3)
bull Istr uzioni mf l o mf hi per accedere ai r egistri Hi e Lo
bull Esempiondash mult $s2$s3ndash mflo $s1 $s1 = Lo (copia di L o in $s1)
bull Compito del programmator e evitare lrsquo overflow e cont rollare chenon ci siano divisioni impr opr ie (per zero)
Istruzione Esempio Signifi cato Commenti
move from Hi mfhi $s1 $s1 = Hi Copia Hi in $s1
move from Lo mflo $s1 $s1 = Lo Copia Lo in $s1
move to Hi mthi $s1 Hi = $s1 Copia $s1 in Hi
move to Lo mtlo $s1 Lo = $s1 Copia $s1 in Lo
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
3
5
L inguaggio assembler
bull Piugrave primi tivo dei linguaggi di alto livello
eg manca un controllo di flusso sofisticato
bull Molto restritti vo
eg Istruzioni Aritmetiche del MI PS
bull Noi lavoreremo con lrsquoarchitettura d el set di istruzioni MI PS
ndash simile ad altre architetture sviluppate a partire dagl i anni lsquo80
ndash usata da NEC Nintendo Silicon Graphics Sony
bull Obiettivi di Progetto massimizzare la perfor mance eminimizzare il costo ridurre il tempo di progettazione
6
001001111011110111111111111000001010111110111111000000000001010010101111101001000000000000100000101011111010010100000000001001001010111110100000000000000001100010101111101000000000000000011100100011111010111000000000000111001000111110111000000000000001100000000001110011100000000000011001001001011100100000000000000000010010100100000001000000000110010110101111101010000000000000011100000000000000000001111000000100100000001100001111110010000010000100010100001000001111111111110111101011111011100100000000000110000011110000000100000100000000000010001111101001010000000000011000000011000001000000000000111011000010010010000100000001000011000010001111101111110000000000010100001001111011110100000000001000000000001111100000000000000000100000000000000000000001000000100001
text
align 2
globl mainmain
subu $sp $sp 32sw $ra 20($sp )sd $a0 32($ sp)sw $0 24($sp)sw $0 28($sp)
looplw $t6 28($sp)mul $t7 $t6 $t6lw $t8 24($sp)addu $t9 $t8 $t7w $t9 24($ sp)addu $t0 $t6 1sw $t0 28($sp)ble$t0 100 loopla $a0 strlw $a1 24($sp)jal printfmove$v0 $0lw $ra 20($sp)ddu $sp $sp 32jr $radataalign 0
strasciiz The sum from 0 100 is d n
Programma che ca lcola e stampa la somma dei q uad rati dei pri mi 100 interi
inclu de ltstdiohgtint main (int argc char argv[])int iint sum = 0for (i = 0 i lt= 100 i = i + 1) sum = sum + i i printf (The sum from 0 100 is dn sum)
3803
4
7
Gerarchia di tr asformazioneProgramma in C
Programma in linguaggio assembler
Assemblatore
M odulo oggetto Linguaggio macchina M odulo oggetto Librerie
Linker
Eseguibi le
Loader
M emoria
Compilatore
8
Gerarchia di tr asformazione
Un programma scri tto in linguaggio ad alto livello viene
bull compilato in linguaggio assembler
bull assemblato per ottener e un modulo oggetto in linguaggiomacchina
bull il linker combina uno o piugrave moduli oggetto con le
procedure contenute nelle libreri e per esplicitare tutti iriferimenti incrociati
bull il loader colloca il codice macchina in opportunelocazioni di memoria in modo che possa esser e eseguitodal processore
3803
5
9
Vantaggi e svantaggi del li nguaggio assembler
bull Vantaggindash velocitagrave drsquoesecuzione (es calcolatori embedded)
ndash occupazione di memoria
ndash collegabile a programmi ad alto livello
ndash possibilitagrave di usare istruzioni specializzate
bull Svantaggindash minore portabilitagrave
ndash fattore di espansione elevato =gt minore produttivitagrave
ndash minore leggibilitagrave
ndash no programmazione strutturata
bull Nota la perfor mance deve esser e valutata sulleistruzioni reali
10
Gli assemblator i
bull I l processo di traduzione ersquo costitui to da due partindash traduzione in indirizzi delle locazioni di memoria etichettate
ndash traduzione istruzioni assembler (codice operativo identif icatori diregistri etichette) in istruzione macchina
bull File oggettondash etichetta esterna (o globale)
ndash etichetta locale (funzione static in C)
bull Rifer imenti in avanti =gt tabella dei simboli
3803
6
11
Il for mato del f ile oggetto
bull Ersquo composto da 6 partindash Intestazione del f ile oggetto
ndash Segmento di testo
ndash Segmento di dato
ndash Informazioni di rilocazione
ndash Tabella dei simboli
ndash Informazioni per il debugger
bull Funzionalitagrave aggiuntiv endash direttive per la codifica dei dati
ndash macro
12
L inker - Loader - Uso del la memor iabull Compilazione separata =gt diversi moduli
bull I l linker unisce i fi lesndash cerca le procedure usate nelle librerie
ndash riloca i f ile oggetto
ndash risolve i riferimenti tra files
bull I l loader (in unix)ndash lettura dellrsquointestazione del file eseguibile per determinare la sua
dimensione
ndash creazione di uno spazio di indirizzamento sufficiente
ndash copia delle istruzioni e dei dati dal file eseguibile alla memoria
ndash copia nello stack degli eventuali parametri passati al programmaprincipale
ndash inizializzazione dei registri dellrsquo elaboratore (es stack pointerhellip)
ndash salto ad una procedura di inizializzazione (start-up routine) chechiama la procedura principale del programma (main)
3803
7
13
Ar itm eti ca MIPS
bull Tutte le istruzioni hanno 3 oper andi
bull Una linea puograve contenere una sola istruzione
bull L rsquoord ine degli operandi ersquo fissato (destinazione per pr ima)
bull Formaoperatore operando1 operando2 operando3
bull Significatooperando1 = operando2 operatore operando3
bull Esempio codice MIPS add $s0 $s1 $s2
codice C a = b + c
14
Ar itm eti ca MIPSbull Principio di progetto1 semplificare per fav or ire la
regolaritagrave
bull Svantaggi della regolar itagrave
C code a = b + c + d
e = f - a
MI PS code add $t 0 $s1 $s2
add $s0 $t 0 $s3
sub $s4 $s5 $s0
bull Gli operandi devono essere r egistrindash solo 32 registri da 4Bytes (= 1 Word)
bull Principio di progetto2 dimensioni minori =gt maggiorevelocitagrave
3803
8
15
Convenzioni sullrsquo uso dei r egistr i
Nome Numero Uso$zero 0 il valore costante 0$v0-$v1 2-3 valori per risultati di espressioni$a0-$a3 4-7 argomenti$t 0-$t 7 8-15 temporanei
$s0-$s7 16-23 salvati$t 8-$t 9 24-25 altri temporanei$gp 28 global pointer
$sp 29 stack pointer$f p 30 frame pointer$r a 31 return address$at 1 riservato
$k0 26 riservato$k1 27 riservato
Registro l ocazione di memoria elementare all rsquointerno del processore
16
Moltip l icazione e divisione
bull Cop pia di regis t ri 32 bit ( HiLo ) che contengono il p ro dotto
di una moltiplic azione (mult $s2$s3) ed il resto ed il
quoziente ris p ett ivamente di una div isione ( div $s2$s3)
bull Istr uzioni mf l o mf hi per accedere ai r egistri Hi e Lo
bull Esempiondash mult $s2$s3ndash mflo $s1 $s1 = Lo (copia di L o in $s1)
bull Compito del programmator e evitare lrsquo overflow e cont rollare chenon ci siano divisioni impr opr ie (per zero)
Istruzione Esempio Signifi cato Commenti
move from Hi mfhi $s1 $s1 = Hi Copia Hi in $s1
move from Lo mflo $s1 $s1 = Lo Copia Lo in $s1
move to Hi mthi $s1 Hi = $s1 Copia $s1 in Hi
move to Lo mtlo $s1 Lo = $s1 Copia $s1 in Lo
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
4
7
Gerarchia di tr asformazioneProgramma in C
Programma in linguaggio assembler
Assemblatore
M odulo oggetto Linguaggio macchina M odulo oggetto Librerie
Linker
Eseguibi le
Loader
M emoria
Compilatore
8
Gerarchia di tr asformazione
Un programma scri tto in linguaggio ad alto livello viene
bull compilato in linguaggio assembler
bull assemblato per ottener e un modulo oggetto in linguaggiomacchina
bull il linker combina uno o piugrave moduli oggetto con le
procedure contenute nelle libreri e per esplicitare tutti iriferimenti incrociati
bull il loader colloca il codice macchina in opportunelocazioni di memoria in modo che possa esser e eseguitodal processore
3803
5
9
Vantaggi e svantaggi del li nguaggio assembler
bull Vantaggindash velocitagrave drsquoesecuzione (es calcolatori embedded)
ndash occupazione di memoria
ndash collegabile a programmi ad alto livello
ndash possibilitagrave di usare istruzioni specializzate
bull Svantaggindash minore portabilitagrave
ndash fattore di espansione elevato =gt minore produttivitagrave
ndash minore leggibilitagrave
ndash no programmazione strutturata
bull Nota la perfor mance deve esser e valutata sulleistruzioni reali
10
Gli assemblator i
bull I l processo di traduzione ersquo costitui to da due partindash traduzione in indirizzi delle locazioni di memoria etichettate
ndash traduzione istruzioni assembler (codice operativo identif icatori diregistri etichette) in istruzione macchina
bull File oggettondash etichetta esterna (o globale)
ndash etichetta locale (funzione static in C)
bull Rifer imenti in avanti =gt tabella dei simboli
3803
6
11
Il for mato del f ile oggetto
bull Ersquo composto da 6 partindash Intestazione del f ile oggetto
ndash Segmento di testo
ndash Segmento di dato
ndash Informazioni di rilocazione
ndash Tabella dei simboli
ndash Informazioni per il debugger
bull Funzionalitagrave aggiuntiv endash direttive per la codifica dei dati
ndash macro
12
L inker - Loader - Uso del la memor iabull Compilazione separata =gt diversi moduli
bull I l linker unisce i fi lesndash cerca le procedure usate nelle librerie
ndash riloca i f ile oggetto
ndash risolve i riferimenti tra files
bull I l loader (in unix)ndash lettura dellrsquointestazione del file eseguibile per determinare la sua
dimensione
ndash creazione di uno spazio di indirizzamento sufficiente
ndash copia delle istruzioni e dei dati dal file eseguibile alla memoria
ndash copia nello stack degli eventuali parametri passati al programmaprincipale
ndash inizializzazione dei registri dellrsquo elaboratore (es stack pointerhellip)
ndash salto ad una procedura di inizializzazione (start-up routine) chechiama la procedura principale del programma (main)
3803
7
13
Ar itm eti ca MIPS
bull Tutte le istruzioni hanno 3 oper andi
bull Una linea puograve contenere una sola istruzione
bull L rsquoord ine degli operandi ersquo fissato (destinazione per pr ima)
bull Formaoperatore operando1 operando2 operando3
bull Significatooperando1 = operando2 operatore operando3
bull Esempio codice MIPS add $s0 $s1 $s2
codice C a = b + c
14
Ar itm eti ca MIPSbull Principio di progetto1 semplificare per fav or ire la
regolaritagrave
bull Svantaggi della regolar itagrave
C code a = b + c + d
e = f - a
MI PS code add $t 0 $s1 $s2
add $s0 $t 0 $s3
sub $s4 $s5 $s0
bull Gli operandi devono essere r egistrindash solo 32 registri da 4Bytes (= 1 Word)
bull Principio di progetto2 dimensioni minori =gt maggiorevelocitagrave
3803
8
15
Convenzioni sullrsquo uso dei r egistr i
Nome Numero Uso$zero 0 il valore costante 0$v0-$v1 2-3 valori per risultati di espressioni$a0-$a3 4-7 argomenti$t 0-$t 7 8-15 temporanei
$s0-$s7 16-23 salvati$t 8-$t 9 24-25 altri temporanei$gp 28 global pointer
$sp 29 stack pointer$f p 30 frame pointer$r a 31 return address$at 1 riservato
$k0 26 riservato$k1 27 riservato
Registro l ocazione di memoria elementare all rsquointerno del processore
16
Moltip l icazione e divisione
bull Cop pia di regis t ri 32 bit ( HiLo ) che contengono il p ro dotto
di una moltiplic azione (mult $s2$s3) ed il resto ed il
quoziente ris p ett ivamente di una div isione ( div $s2$s3)
bull Istr uzioni mf l o mf hi per accedere ai r egistri Hi e Lo
bull Esempiondash mult $s2$s3ndash mflo $s1 $s1 = Lo (copia di L o in $s1)
bull Compito del programmator e evitare lrsquo overflow e cont rollare chenon ci siano divisioni impr opr ie (per zero)
Istruzione Esempio Signifi cato Commenti
move from Hi mfhi $s1 $s1 = Hi Copia Hi in $s1
move from Lo mflo $s1 $s1 = Lo Copia Lo in $s1
move to Hi mthi $s1 Hi = $s1 Copia $s1 in Hi
move to Lo mtlo $s1 Lo = $s1 Copia $s1 in Lo
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
5
9
Vantaggi e svantaggi del li nguaggio assembler
bull Vantaggindash velocitagrave drsquoesecuzione (es calcolatori embedded)
ndash occupazione di memoria
ndash collegabile a programmi ad alto livello
ndash possibilitagrave di usare istruzioni specializzate
bull Svantaggindash minore portabilitagrave
ndash fattore di espansione elevato =gt minore produttivitagrave
ndash minore leggibilitagrave
ndash no programmazione strutturata
bull Nota la perfor mance deve esser e valutata sulleistruzioni reali
10
Gli assemblator i
bull I l processo di traduzione ersquo costitui to da due partindash traduzione in indirizzi delle locazioni di memoria etichettate
ndash traduzione istruzioni assembler (codice operativo identif icatori diregistri etichette) in istruzione macchina
bull File oggettondash etichetta esterna (o globale)
ndash etichetta locale (funzione static in C)
bull Rifer imenti in avanti =gt tabella dei simboli
3803
6
11
Il for mato del f ile oggetto
bull Ersquo composto da 6 partindash Intestazione del f ile oggetto
ndash Segmento di testo
ndash Segmento di dato
ndash Informazioni di rilocazione
ndash Tabella dei simboli
ndash Informazioni per il debugger
bull Funzionalitagrave aggiuntiv endash direttive per la codifica dei dati
ndash macro
12
L inker - Loader - Uso del la memor iabull Compilazione separata =gt diversi moduli
bull I l linker unisce i fi lesndash cerca le procedure usate nelle librerie
ndash riloca i f ile oggetto
ndash risolve i riferimenti tra files
bull I l loader (in unix)ndash lettura dellrsquointestazione del file eseguibile per determinare la sua
dimensione
ndash creazione di uno spazio di indirizzamento sufficiente
ndash copia delle istruzioni e dei dati dal file eseguibile alla memoria
ndash copia nello stack degli eventuali parametri passati al programmaprincipale
ndash inizializzazione dei registri dellrsquo elaboratore (es stack pointerhellip)
ndash salto ad una procedura di inizializzazione (start-up routine) chechiama la procedura principale del programma (main)
3803
7
13
Ar itm eti ca MIPS
bull Tutte le istruzioni hanno 3 oper andi
bull Una linea puograve contenere una sola istruzione
bull L rsquoord ine degli operandi ersquo fissato (destinazione per pr ima)
bull Formaoperatore operando1 operando2 operando3
bull Significatooperando1 = operando2 operatore operando3
bull Esempio codice MIPS add $s0 $s1 $s2
codice C a = b + c
14
Ar itm eti ca MIPSbull Principio di progetto1 semplificare per fav or ire la
regolaritagrave
bull Svantaggi della regolar itagrave
C code a = b + c + d
e = f - a
MI PS code add $t 0 $s1 $s2
add $s0 $t 0 $s3
sub $s4 $s5 $s0
bull Gli operandi devono essere r egistrindash solo 32 registri da 4Bytes (= 1 Word)
bull Principio di progetto2 dimensioni minori =gt maggiorevelocitagrave
3803
8
15
Convenzioni sullrsquo uso dei r egistr i
Nome Numero Uso$zero 0 il valore costante 0$v0-$v1 2-3 valori per risultati di espressioni$a0-$a3 4-7 argomenti$t 0-$t 7 8-15 temporanei
$s0-$s7 16-23 salvati$t 8-$t 9 24-25 altri temporanei$gp 28 global pointer
$sp 29 stack pointer$f p 30 frame pointer$r a 31 return address$at 1 riservato
$k0 26 riservato$k1 27 riservato
Registro l ocazione di memoria elementare all rsquointerno del processore
16
Moltip l icazione e divisione
bull Cop pia di regis t ri 32 bit ( HiLo ) che contengono il p ro dotto
di una moltiplic azione (mult $s2$s3) ed il resto ed il
quoziente ris p ett ivamente di una div isione ( div $s2$s3)
bull Istr uzioni mf l o mf hi per accedere ai r egistri Hi e Lo
bull Esempiondash mult $s2$s3ndash mflo $s1 $s1 = Lo (copia di L o in $s1)
bull Compito del programmator e evitare lrsquo overflow e cont rollare chenon ci siano divisioni impr opr ie (per zero)
Istruzione Esempio Signifi cato Commenti
move from Hi mfhi $s1 $s1 = Hi Copia Hi in $s1
move from Lo mflo $s1 $s1 = Lo Copia Lo in $s1
move to Hi mthi $s1 Hi = $s1 Copia $s1 in Hi
move to Lo mtlo $s1 Lo = $s1 Copia $s1 in Lo
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
6
11
Il for mato del f ile oggetto
bull Ersquo composto da 6 partindash Intestazione del f ile oggetto
ndash Segmento di testo
ndash Segmento di dato
ndash Informazioni di rilocazione
ndash Tabella dei simboli
ndash Informazioni per il debugger
bull Funzionalitagrave aggiuntiv endash direttive per la codifica dei dati
ndash macro
12
L inker - Loader - Uso del la memor iabull Compilazione separata =gt diversi moduli
bull I l linker unisce i fi lesndash cerca le procedure usate nelle librerie
ndash riloca i f ile oggetto
ndash risolve i riferimenti tra files
bull I l loader (in unix)ndash lettura dellrsquointestazione del file eseguibile per determinare la sua
dimensione
ndash creazione di uno spazio di indirizzamento sufficiente
ndash copia delle istruzioni e dei dati dal file eseguibile alla memoria
ndash copia nello stack degli eventuali parametri passati al programmaprincipale
ndash inizializzazione dei registri dellrsquo elaboratore (es stack pointerhellip)
ndash salto ad una procedura di inizializzazione (start-up routine) chechiama la procedura principale del programma (main)
3803
7
13
Ar itm eti ca MIPS
bull Tutte le istruzioni hanno 3 oper andi
bull Una linea puograve contenere una sola istruzione
bull L rsquoord ine degli operandi ersquo fissato (destinazione per pr ima)
bull Formaoperatore operando1 operando2 operando3
bull Significatooperando1 = operando2 operatore operando3
bull Esempio codice MIPS add $s0 $s1 $s2
codice C a = b + c
14
Ar itm eti ca MIPSbull Principio di progetto1 semplificare per fav or ire la
regolaritagrave
bull Svantaggi della regolar itagrave
C code a = b + c + d
e = f - a
MI PS code add $t 0 $s1 $s2
add $s0 $t 0 $s3
sub $s4 $s5 $s0
bull Gli operandi devono essere r egistrindash solo 32 registri da 4Bytes (= 1 Word)
bull Principio di progetto2 dimensioni minori =gt maggiorevelocitagrave
3803
8
15
Convenzioni sullrsquo uso dei r egistr i
Nome Numero Uso$zero 0 il valore costante 0$v0-$v1 2-3 valori per risultati di espressioni$a0-$a3 4-7 argomenti$t 0-$t 7 8-15 temporanei
$s0-$s7 16-23 salvati$t 8-$t 9 24-25 altri temporanei$gp 28 global pointer
$sp 29 stack pointer$f p 30 frame pointer$r a 31 return address$at 1 riservato
$k0 26 riservato$k1 27 riservato
Registro l ocazione di memoria elementare all rsquointerno del processore
16
Moltip l icazione e divisione
bull Cop pia di regis t ri 32 bit ( HiLo ) che contengono il p ro dotto
di una moltiplic azione (mult $s2$s3) ed il resto ed il
quoziente ris p ett ivamente di una div isione ( div $s2$s3)
bull Istr uzioni mf l o mf hi per accedere ai r egistri Hi e Lo
bull Esempiondash mult $s2$s3ndash mflo $s1 $s1 = Lo (copia di L o in $s1)
bull Compito del programmator e evitare lrsquo overflow e cont rollare chenon ci siano divisioni impr opr ie (per zero)
Istruzione Esempio Signifi cato Commenti
move from Hi mfhi $s1 $s1 = Hi Copia Hi in $s1
move from Lo mflo $s1 $s1 = Lo Copia Lo in $s1
move to Hi mthi $s1 Hi = $s1 Copia $s1 in Hi
move to Lo mtlo $s1 Lo = $s1 Copia $s1 in Lo
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
7
13
Ar itm eti ca MIPS
bull Tutte le istruzioni hanno 3 oper andi
bull Una linea puograve contenere una sola istruzione
bull L rsquoord ine degli operandi ersquo fissato (destinazione per pr ima)
bull Formaoperatore operando1 operando2 operando3
bull Significatooperando1 = operando2 operatore operando3
bull Esempio codice MIPS add $s0 $s1 $s2
codice C a = b + c
14
Ar itm eti ca MIPSbull Principio di progetto1 semplificare per fav or ire la
regolaritagrave
bull Svantaggi della regolar itagrave
C code a = b + c + d
e = f - a
MI PS code add $t 0 $s1 $s2
add $s0 $t 0 $s3
sub $s4 $s5 $s0
bull Gli operandi devono essere r egistrindash solo 32 registri da 4Bytes (= 1 Word)
bull Principio di progetto2 dimensioni minori =gt maggiorevelocitagrave
3803
8
15
Convenzioni sullrsquo uso dei r egistr i
Nome Numero Uso$zero 0 il valore costante 0$v0-$v1 2-3 valori per risultati di espressioni$a0-$a3 4-7 argomenti$t 0-$t 7 8-15 temporanei
$s0-$s7 16-23 salvati$t 8-$t 9 24-25 altri temporanei$gp 28 global pointer
$sp 29 stack pointer$f p 30 frame pointer$r a 31 return address$at 1 riservato
$k0 26 riservato$k1 27 riservato
Registro l ocazione di memoria elementare all rsquointerno del processore
16
Moltip l icazione e divisione
bull Cop pia di regis t ri 32 bit ( HiLo ) che contengono il p ro dotto
di una moltiplic azione (mult $s2$s3) ed il resto ed il
quoziente ris p ett ivamente di una div isione ( div $s2$s3)
bull Istr uzioni mf l o mf hi per accedere ai r egistri Hi e Lo
bull Esempiondash mult $s2$s3ndash mflo $s1 $s1 = Lo (copia di L o in $s1)
bull Compito del programmator e evitare lrsquo overflow e cont rollare chenon ci siano divisioni impr opr ie (per zero)
Istruzione Esempio Signifi cato Commenti
move from Hi mfhi $s1 $s1 = Hi Copia Hi in $s1
move from Lo mflo $s1 $s1 = Lo Copia Lo in $s1
move to Hi mthi $s1 Hi = $s1 Copia $s1 in Hi
move to Lo mtlo $s1 Lo = $s1 Copia $s1 in Lo
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
8
15
Convenzioni sullrsquo uso dei r egistr i
Nome Numero Uso$zero 0 il valore costante 0$v0-$v1 2-3 valori per risultati di espressioni$a0-$a3 4-7 argomenti$t 0-$t 7 8-15 temporanei
$s0-$s7 16-23 salvati$t 8-$t 9 24-25 altri temporanei$gp 28 global pointer
$sp 29 stack pointer$f p 30 frame pointer$r a 31 return address$at 1 riservato
$k0 26 riservato$k1 27 riservato
Registro l ocazione di memoria elementare all rsquointerno del processore
16
Moltip l icazione e divisione
bull Cop pia di regis t ri 32 bit ( HiLo ) che contengono il p ro dotto
di una moltiplic azione (mult $s2$s3) ed il resto ed il
quoziente ris p ett ivamente di una div isione ( div $s2$s3)
bull Istr uzioni mf l o mf hi per accedere ai r egistri Hi e Lo
bull Esempiondash mult $s2$s3ndash mflo $s1 $s1 = Lo (copia di L o in $s1)
bull Compito del programmator e evitare lrsquo overflow e cont rollare chenon ci siano divisioni impr opr ie (per zero)
Istruzione Esempio Signifi cato Commenti
move from Hi mfhi $s1 $s1 = Hi Copia Hi in $s1
move from Lo mflo $s1 $s1 = Lo Copia Lo in $s1
move to Hi mthi $s1 Hi = $s1 Copia $s1 in Hi
move to Lo mtlo $s1 Lo = $s1 Copia $s1 in Lo
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
9
17
Overflow
bull I l risultato dellrsquooperazione non ersquo rappresentabiledallrsquohw disponibile
bull I numer i rappresentabili sonondash da 0 a (232 -1) (unsigned)
ndash da -231 a (231-1) (signed)
bull Condizioni di over flow (numer i signed)ndash Agt0 Bgt0 e si ottiene A+Blt0
ndash Alt0 Blt0 e si ottiene A+Bge0
ndash A ge0 Blt0 e si ottiene A-Blt0
ndash Alt0B ge0 e si ottiene A-B ge0
bull L e oper azioni addusu bumu lt mult u div e divu
non fanno alcun controllo sullrsquoov erflow
18
Istr uzioni Ar i tmeticheIstruzi one Esempio Significato Commenti
add add $s1$s2$s3 $s1 = $s2 + $s3 3 operandi eccezione possibile
add immediate addi $s1$s2100 $s1 = $s2 + 100 + cost eccezione possibile
add unsigned addu $s1$s2$s3 $s1 = $s2 + $s3 3 operandi nessuna eccezione
add imm unsign addiu $s1$s2100 $s1 = $s2 + 100 + costante nessuna eccezione
subtract sub $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi eccezione possibile
subtract unsigned subu $s1$s2$s3 $s1 = $s2 ndash $s3 3 operandi nessuna eccezione
multiply mult $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto con segno
multiply unsigned multu $s2$s3 Hi Lo = $s2 x $s3 64-bit prodotto senza segno
divide div $s2$s3 Lo = $s2 divide $s3 Lo = quoziente Hi =
resto
Hi = $s2 mod $s3
divide unsigned divu $s2$s3 Lo = $s2 divide $s3 Quoziente amp resto senza segno
Hi = $s2 mod $s3
shift right arit sra $s1$s210 $s1 = $s2 gtgt 10 Shift a destra (segno esteso)
shift right aritvar srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift aritm a destra di bit var
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
10
19
Qualche esempio (NB non assembler pur o)
bull Esempio1a = b + c + d + e
add a b c a = b + c
add a a d a = a + d
add a a e a = a + e
bull Esempio2f = ( g + h) - ( i + j )
add $t 0 g h $t 0 = g + h
add $t 1 i j $t 1 = i + j
sub f $t 0 $t 1 f = $t 0 - $t 1
20
Registr i e Memor ia
bull L e istr uzioni aritmeticheoperano su r egistrindash solo 32 registri
ndash ogni registro 1W (4B)
bull il compilatore associa
variabil i con r egistri
bull Cosa succede conprogrammi con tanti dati
(variabil i array)ndash usiamo la memoria che
contiene anche i programmi
ndash Memoria MIPS indir izzata al Byte
Control
Datapath
Input
OutputMemory
Processor IO
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
0
1
2
3
4
5
6
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
11
21
In dir izzamento al byte
bull Ersquo l rsquoin dir izzamento usato dalla maggior parte dellearchitetture
bull MI PSndash le parole iniziano sempre ad indiriz zi multipl i di 4 (vincolo di
allineamento)
ndash Indirizz o = indir izzo base + offset x 4
bull Or dinamento dei byte in memoriandash big endian (MIPS Sparc Motorola 68k)
lrsquoin dirizzo di una parola corrisponde allrsquoindirizzo del byte piugravesignificativo
ndash little endian (Intel 80x86 DEC Alpha)lrsquoin dirizzo di una parola corrisponde indirizzo del byte menosignificativo
22
Or dinamento dei byte in memor ia
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
12
23
Or ganizzazione della memor ia
bull L rsquoi ndirizzamento al byte ersquo comodo ma i dati sonomemor izzati in ldquo wordsrdquo (32 bits o 4 bytes)
bull I registr i contengono 32 bits di dati
bull Or ganizzazione della memoriandash 232 bytes con indirizzi da 0 a 232-1
ndash 230 words con indirizzi 0 4 8 232-4
bull L e words sono allineatendash quali sono i due bits meno significativi
dellrsquoindirizzo di una parola
0
4
8
12
32 bits of data
32 bits of data
32 bits of data
32 bits of data
24
Istr uzioni di tr asfer imento datibull sw (Store Word) reg =gt word in memoria
bull lw (Load Word) word in memoria =gt regbull Forma
operatore r egistro offset(indirizz o_base)
offset ersquo opzionale
bull sw ha la destinazione come ultimo oper ando
bull EsempioC code A[ 9] = h + A[ 8]
MI PS code hlt=gt$s2 A[ 0] lt=gt$s3
l w $t 0 32( $s3)
add $t 0 $s2 $t 0
sw $t 0 36( $s3)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
13
25
Un esempio
swap( i nt v[ ] i nt k) i nt t emp
t emp = v[ k]v[ k] = v[ k+1] v[ k+1] = t emp
swap
add $t 1 $a1 $a1add $t 1 $t 1 $t 1add $t 1 $a0 $t 1l w $t 0 0( $t 1)l w $t 2 4( $t 1)sw $t 2 0( $t 1)sw $t 0 4( $t 1)
j r $r a
vlt=gt$a0 klt=gt$a1 t emplt=gt$t 0
26
Esempio con indice variabile
bull g = h + A[i]
g $s1
h $s2
A $s3 ( i ndi r i zzo base)
i $s4 ( of f set )
MIPS code add $t 1 $s4 $s4
add $t 1 $t 1 $t 1
add $t 1 $t 1 $s3
l w $t 0 0( $t 1)
add $s1 $s2 $t 0
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
14
27
Spil ling
bull I n memoria si mettono le variabil i meno usate
bull Ricorda gli operandi aritmetici sono registri non celledi memor iandash tempo accesso ai registri ersquo minore
ndash throughput migliore
bull 1 ciclo di clock
ndash lettura due registri
ndash esecuzione operazione
ndash scrittura risultato
28
Istr uzioni di tr asfer imento dati
ISTRUZIONE ESEMPIO SIGNIFICA TO
caricamento di li $s1 10 $s1 = 10una costantecaricamento costante la $s1 ind $s1 = inddi tipo indirizzo (32bit)caricamento del byte lb $s1 ind $s1 = (ind)memorizz all rsquoindi rizzo indcaricamento della lw $s1 ind $s1 = (ind)word memorizzallrsquoi ndiri zzo indmemorizz del byte sb $s1 ind ind = ($s1)contenuto nel registro$s1 all rsquoindi rizzo indmemorizz della word sw $s1 ind ind = ($s1)contenuto nel registro$s allrsquoi ndiri zzo ind
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
15
29
Riassumendo
bull MI PSndash loadstore word con indirizzamento al byte
ndash aritmetica solo su registri
bull I str uzioni Significatoadd $t 1 $t 2 $t 3 $t 1 = $t 2 + $t 3
sub $t 1 $t 2 $t 3 $t 1 = $t 2 - $t 3
l w $t 0 100( $t 1) $t 0 = Memor y[ $t 1+100]
sw $t 0 100( $t 1) Memor y[ $t 1+100] = $t 0
30
bull Istruzioni r egistri e words di dati sono di 32 bitsndash sono rappresentati allrsquointerno del calcolatore come serie di
segnali elettrici
ndash ovvero numeri in base 2
bull Esempio add $t 0 $s 1 $s 2
ndash I registri sono numerati $t0=8 $s1= 17 $ s2=18
bull Formato istruzione R-type000000 10001 10010 01000 00000 100000
op r s r t r d shamt f unct
L inguaggio macchina
6 bit 5 bit 5 bit 6 bit5 bit 5 bit
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
16
31
L inguaggio macchina
bull op codice operativo (opcode) dellrsquoi struzione
bull rs primo oper ando (registro)
bull rt secondo operando (registr o)
bull rd registro destinazione che contiene il risultatodellrsquooperazione
bull shamt valore dellrsquooffset (scalamento shift amount)
bull funct seleziona una variante dellrsquooper azione basespecificata dallrsquoopcode (codice funzione function code)
32
Rappr esentazione delle ist r uzioni
bull Formato istruzione (R-type) 3 registri
bull le istruzioni lw e swndash 2 registri e una costante
ndash 5 bit non sono sufficienti
ndash occorre nuovo formato
bull Formato istruzione (I-type) 6bit 5bit 5bit 16bit
op rs rt address
opcode base Dest ( l w)
bull Spazio di indir izzamento plusmn215 =plusmn213 parole
bull Principio di progetto 3
ndash un buon progetto richiede buoni compromessi
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
17
33
Rappr esentazione delle ist r uzioni
bull esempiol w $t 0 32( $s3)
l w $8 32( $19)
35 19 8 32
op r s r t addr ess opcode base Dest
bull Compromesso di progettondash anche lwsw sono lunghe 1w con displacement costante (operando
immediato di 16 bit) inserito direttamente nellrsquoistruzione
34
bull L e istr uzioni sono stringhe di bits
bull I programmi sono memorizzati in memoriandash semplificazione hwsw dei calcolatori
bull Ciclo Fetch amp Executendash lrsquoistruzione corrente viene letta e messa in uno speciale registro internondash i bit nel registro ldquocontrollanordquo le azioni seguentindash viene letta la nuova istruzione e cosirsquo via
memoria per dati programmi compilatori editor etc
Concetto di pr ogramma memor izzato
Processore M emoria
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
18
35
Ciclo fetchamp execute
Instruction Fetch
Instruction Decod e
Operand Fetch
Execute
Result Store
Next Instruction
36
Pr ogramma memor izzato
memory
OS
Program 1
Program 2
CPU
code
dataunused
unused
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
19
37
Or ganizzazione della memor ia
0x7fffffff
0x400000
0x10000000
Riservata
Segmento di co dice
Segmento di dato
Segmento stack
Dati dinamici
Dati statici
text
stack
38
bull I str uzioni per prender e le decisionindash alterano il controllo del flusso (sequenziale)
ndash cambiano quindi la prossima istruzione da eseguire
bull I str uzioni MI PS di salto condizionato
bne $t 0 $t 1 Label br anch i f not equal
beq $t 0 $t 1 Label br anch i f equal
bull Esempio if (i==j) h = i + j
bne $s0 $s1 Label
add $s3 $s0 $s1
Label
Istr uzioni di contr ollo
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
20
39
bull Salto non condizionato
j lab el
bull Esempio (costrutto ifthenelse) i f ( i = j ) h=i +j beq $s4 $s5 Lab1
el se h=i - j add $s3 $s4 $s5
j Lab2
Lab1 sub $s3 $s4 $s5
Lab2
Istr uzioni di contr ollo
40
bull Esempio costrutto while
whi l e ( vet t [ i ] == k) i =i +j ndash i j e k sono contenuti nei registri $s 3 $s 4 e $s 5 e lrsquoindirizzo base
di vet t in $s6
ci c l o add $t 1 $s3 $s3 t 1 =2 i
add $t 1 $t 1 $t 1 t 1 =4 i
add $t 1 $t 1 $s6 t 1 = i ndi r i zzo di vet t [ i ]
l w $t 0 0( $t 1) t 0 = vet t [ i ]
bne $t 0 $s5 esci vai a esci se vet t [ i ] = k
add $s3 $s3 $s4 i =i +j
j c i c l o vai a ci c l o
Esci
Istr uzioni di contr ollo
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
21
41
bull I str uzione set on less than
i f $s1 lt $s2 t hen
sl t $t 0 $s1 $s2 $t 0 = 1
el se $t 0 = 0
bull Questa istr uzione puorsquo essere utilizzata per cr eare ldquo bl t rdquo che non
ersquo predefinita nel linguaggio MIPS Per fare questo ersquo necessario
lrsquouso del r egistro $zer o
bull Formato J-Type
Istr uzioni di contr ollo
op 26 bi t addr essJ
6 bit 26 bit
42
Comando FOR
bull C codef or ( i =0 i = n i = i+ k)
a = a+b
bull MI PSadd $t 0 $zer o $zero i= $t 0=0
Loop
beq $t 0 $s0 Exi t if ( i== n) goto Exi t
add $s1 $s1 $s2 a = a+b
add $t 0 $t 0 $t 1 i = i+k
j Loop goto Loop
Exi t
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
22
43
Comando CaseSwitch
bull Comando Caseswitchndash puorsquo essere tradotto in una catena di if-then-else
ndash caso peggiore tempo di esecuzione proporzionale al numero di casi
ndash puorsquo essere reso piugrave veloce con una jump address tableind in cui si trovano le sequenze di istruzioni = vettore con indirizzi delleetichette
bull Nuova istr uzionesalto tramite registro jr $ t0 ( jump register )
bull swit ch (k )
cas e 0 f = i+ j br eak
cas e 1 f = g+ h br eak
cas e 2 f = g- h br eak
cas e 3 f = i- j br eak
44
Comando CaseSwitch
1 test se 0 lt= k lt= 32 calcola indirizzo3 trova indirizzo di salto e salta
4 esegue il codice
Assembler code s lt $ t3 $s 5 $z ero
bne $ t3 $z er o Exi t
s lt $ t3 $s 5 $t 2
beq $ t3 $z er o Exi t
add $ t1 $s 5 $s 5
add $ t1 $t 1 $t 1
add $ t1 $t 1 $t 4
l w $ t0 0( $t 1)
j r $ t0
L0 add $s0 $s 3 $s 4
j Exit
L1 add $s0 $s 1 $s 2
j Exit
L2 s ub $s0 $s 1 $s 2
j Exit
L3 s ub $s0 $s 3 $s 4
Exit
address L0address L1
address L2address L3
Data jump table
$t4
$t4+4
$t4+8
$t4+12
$t 4 lt-gt base$t 2 lt-gt 4$s 5 lt-gt k
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
23
45
Istr uzioni di confr onto
Istruzione Esempio Signifi cato Commenti
set less than slt $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri
else $s1=0 (con segno)
set less than imm slti $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (con segno)
set less than uns sltu $s1$s2$s3 if ($s2lt$s3) $s1=1 Confronto tra registri (senza
else $s1=0 segno)
set l t imm uns sltiu $s1$s2100 if ($s2lt100) $s1=1 Confronto registro-costante
else $s1=0 (senza segno)
46
Branch e BranchampL inkIstruzione Esempio Signifi cato Commenti
branch on equal beq $s1$s2L if ($s1 == $s2) go to L Test di uguaglianza PC-rel
branch on not eq bne $s1$s2L if ($s1= $s2) go to L Test di disuguaglianza PC-rel
branch gr eq zero bgez $s1 L if ($s1gt= $0) go to L Test di non negativo PC-rel
branch gr th zero bgtz $s1 L if ($s1gt $0) go to L Test di positivo PC-rel
branch less eq zero blez $s1 L if ($s1lt= $0) go to L Test di non positivo PC-rel
branch less th zero bltz $s1 L if ($s1lt $0) go to L Test di negativo PC-rel
branch gr eq zero bgezal $s1 P if ($s1gt= $0) Test di non negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
branch less th zero bltzal $s1 P if ($s1lt $0) Test di negativo PC-rel
and link $ra = PC + 4 Per le chiamate a procedura
go to P
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
24
47
Jump
Istruzione Es Signifi cato Commenti
jump j Lab go to Lab Salta allrsquoistruzione di eti chetta Lab
jump register jr $ra go to $ra Per i ritor ni da procedura
jump and link jal Proc $ra = PC + 4 Per le chiamate di procedura
go to Proc
jump and link jalr $s1 $ra = PC + 4 Per le chiamate di procedura
reg go to $s1
48
Pr ocedur eFunzioni
bull Molto util i in linguaggi di alto livellondash astrazione - riusabilitarsquo - strutturazionemodularitagrave
bull Chi si ldquooccupardquo della chiamatandash il compilatore nei linguaggi ad alto livello
ndash il programmatore in assembler
bull Passi necessarindash passare i parametri al chiamato
ndash salvare lrsquoindirizzo di ritorno e passare il controllo alla procedura
ndash allocare spazio per variabili locali
ndash eseguire il corpo della procedura
ndash passare i risultati al chiamante
ndash riportare il controllo al punto di partenza
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
25
49
In dir izzo di r itor no
bull Ersquo necessario salvare lrsquoindirizzo di ri torno
Istruzione jump and link
ja l i ndiri zzoesegue lrsquo istruzione memorizzata ad indirizzo e pone in $ra lrsquoindirizzodellrsquoistruzione successiva a jal indirizzo
bull Istruzione di ri torno
j r $r a
esegue lrsquoistruzione il cui indirizzo ersquo contenuto in $ra
bull Lrsquoi ndirizzo dellrsquoistruzione corrente ersquo contenuto nel registro
riservato PC (Program Counter)ndash j al mette in $ra il valore (PC)+4
ndash j r $ra mette in PC $r a
50
Chiamata di una pr ocedur a
E se il chiamato chiama unrsquoaltra procedura
jr $ra
jal label
chiamante
chiamato
label
$ra
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
26
51
Chiamate annidate
jal loc
chiamante
jal loc2
chiamatochiamante
loc
$ra
jr $ra
chiamato
$ra
jr $ra
loc2
52
Passaggio dei parametri
bull Il programma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametr i al
chiamatondash Si usano i registri $a0 $a3 (4 registri in tutto)
bull Se ho piugrave di 4 parametri da passare o piugrave chiamate
innestate
Occorre una struttura dati per memorizzare le variabili
locali del chiamato e gestire le chiamate annidate
PILA (Stack)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
27
53
Uso della pila (stack)
bull Lrsquoin dirizz o dellrsquoistruzione corrente ersquo contenuto nel r egistro
riservato PC (Program Counter)
bull Lrsquoistruzione j al mette in $r a il valore (PC)+4
bull j r mette in PC ( $r a)
bull Il progr amma chiamante puorsquo passare dei parametri allaprocedura chiamata
bull La convenzione usata per il passaggio dei parametri
ndash uso dei registr i $a0 $a3 (4 registr i in tutto)
ndash se ho piugrave di 4 parametri da passare o piugrave chiamate innestate si usala PILA
54
Uso della pila (stack)bull Stack Pointer $sp
ndash punta sempre alla cima dello stack(allrsquo ultima parola)
bull Strutt ur a dati LIFO
ndash push sub $sp $sp 4
sw $t 0 ( $sp)
ndash pop l w $t 0 ( $sp)
add $sp $sp 4
bull Fr ame Pointer $f p
ndash indirizza la prima parola dello stack frame di una procedura
bull Stack f rame
ndash segmento dello stack che contiene i registri salvati da una
procedura e le variabili locali
new
oldhigh
addresses
lowaddresses
$sp
$fp
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
28
55
Stack fr ame
Argomento 5Argomento 6
Registrisalvati
Variabililocal i
$fp
$sp
Stackframe
Lo stack cresce verso il basso
Scopobull memorizzare i dati di una
procedura in una struttura si ngola
bull si puorsquo accedere ai dati con $fp
bull usare $sp puorsquo essere difficile
perchersquo la pila puorsquo variare
bull Ersquo necessario
ndash si per le chiamate ricorsivendash si per chiamate di procedure
complessendash no per programmi semplici
ndash I compilatori lo usano
bull Contenuti
ndash argomenti non passati con a0-a3ndash valori di registri salvat i
ndash vari abil i locali del la procedura
56
Stack Fr ame
bull
SFproce dura A
stack
SFproce dura B
SFproce dura C
argomento 5
argomento 6
Registrisalvati
variabililocali
cresce versoil basso
$sp
$fp
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
29
57
Convenzioni nel la chiamata di pr ocedur e -1bull Programma chiamante e chiamato devono stabilire una
ben definita sequenza di passibull I l chiamante
ndash passa gli argomenti se ce ne sono Fino a 4 si usano i registri $a0-$a3 I successivi in pila
ndash salva i registri $a0- $a3 e $t 0- $t 9 se intende usarli dopo lachiamata
ndash esegue j al (salta alla prima istruzione del chiamato e salva in$r a lrsquo indirizzo di ritorno)
bull I l chiamato (prima di eseguire le proprie istruzioni)ndash alloca memoria per lo stack frame Se lo stack frame ersquo di 32 byte
$sp = $sp - 32
ndash salva i registri $s0- $7 $f p $r a prima di alterarli
ndash inizializza il f rame pointer $f p = $sp + 32 - 4
ndash se non ci sono dati locali nella pila $f p non serve
58
Convenzioni nel la chiamata di pr ocedur e -2
bull I l chiamato (dopo avere eseguito le proprie istr uzioni)ndash mette il valore risultato in $v0 (se esiste)
ndash ripristina tutti i registri che aveva salvato prima dellrsquoesecuzionedella procedura
ndash libera lo stack f rame $sp = $sp + 32
ndash Ritorna al programma chiamante j r $32
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
30
59
Convenzioni sullrsquo uso dei r egistr i
No me Numer o Uso
Pr eser vato in u na chiamata a p ro ced ur a
$zero 0 il valor e costante 0 na
$v0-$v1 2-3 valor i per r isultati di espressioni no$a0-$a3 4-7 ar gomenti si
$t0-$t7 8-15 tempor anei no $s0-$s7 16-23 salvati si
$t8-$t9 24-25 altr i temporanei no$gp 28 global pointer si$sp 29 stack pointer si$fp 30 fr ame pointer si
$r a 31 r etur n address si
60
Ottimizzazione del le chiamate
bull Tipi di chiamate di procedurandash non-foglia
bull procedure che chiamano altre procedure
bull procedure ricorsive
ndash foglia
bull procedure che non effettuano chiamatendash che richiedono lrsquouso della pila per variabili locali
ndash che non richiedono uso della pila
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
31
61
Compilare una pr ocedur a ldquofogl iardquo
voi d swap (int v[] int k) swap add $t0$ a1$a 1 add $t0$ t0$t 0 int tm p add $t0$ a0$a 0 tmp = v[k] lw $t10 ($t0) v[k] = v[k+ 1] lw $t24 ($t0) v[k+1] = tm p sw $t20 ($t0) sw $t14 ($t0)
jr $ra
Calleradd $a0$ s1$z eroadd $a1$ s2$z erojal swap
62
Compilare una pr ocedur a ldquonon fogliardquoin t squ are (i nt a) sq uare
r etu rn a a mul $v 0 $a0 $a 0 pseudoist r
jr $r a
in t pol y(i nt x) po ly addi $s p $sp -8
r etu rn sq uar e(x )+ x+1 sw $r a 4($ sp)
sw $a0 0($ sp)
ja l sq uare
lw $a0 0($ sp)
add $v 0 $v0 $a 0
addi $v 0 $v0 1
lw $r a 4($ sp)
addi $s p $sp 8
jr $r a
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
32
63
Funzione r icorsiva
Funzione C per il calcolo del fattori ale
int fact (int n)
if (nlt1) return (1)
else return (nfact(n-1))
Fattor iale n = n (n-1)
0 = 1
64
Funzione r icorsiva
i nstr uct i on
addre ss
1000 f act addi $sp$ sp -8
1004 sw $r a4 ( $sp)1008 sw $a00 ( $sp)
1012 sl t i $t 0$ a0 1 te st i f nlt1
1016 beq $t 0$ zer o L1 if ngt=1 got o L1
1020 addi $v0$ zer o 1 re t ur n 1
1024 addi $sp$ sp 8
1032 jr $r a
1036 L1 addi $a0$ a0 -1
1040 ja l fa ct cal l f act wit h ( n- 1)
1044 lw $a00 ( $sp)
1048 lw $r a4 ( $sp)
1052 addi $sp$ sp 8
1056 mul $v0$ a0 $v0 re t ur n nf act ( n- 1)
1060 jr $r a
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
33
65
Funzione r icorsiva
$sp
low address
high address
fille
d100 addi $a0$zero3
104 jal fact
108 $ra = 1044$a0 = 2
$ra = 1044$a0 = 1
$ra = 1044$a0 = 0
$ra =108$a0 = 3
$v0 = 1
$v0 = 1
$v0 = 2
$v0 = 6
66
Istr uzioni Logiche
Istruzione Esempio Signifi cato Commento
and and $s1$s2$s3 $s1 = $s2 amp $s3 3 reg operands L ogical AND
or or $s1$s2$s3 $s1 = $s2 | $s3 3 reg operands L ogical OR
xor xor $s1$s2$s3 $s1 = $s2 ^ $s3 3 reg operands L ogical XOR
nor nor $s1$s2$s3 $s1 = ~($s2 |$s3) 3 reg operands L ogical NOR
and immediato andi $s1$s210 $s1 = $s2 amp 10 Logical AND reg constant
or immediato ori $s1$s210 $s1 = $s2 | 10 Logical OR reg constant
xor immediato xori $s1 $s210 $s1 = ~$s2 amp~10 Logical XOR reg constant
shift left l ogical sll $s1$s210 $s1 = $s2 ltlt 10 Shift left by constant
shift right logi cal srl $s1$s210 $s1 = $s2 gtgt 10 Shift r ight by constant
shift right arithm sra $s1$s210 $s1 = $s2 gtgt 10 Shift r ight (sign extend)
shift left l ogical sllv $s1$s2$s3 $s1 = $s2 ltlt $s3 Shift left by variabl e
shift right logi cal srlv $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight by vari able
shift right arithm srav $s1$s2 $s3 $s1 = $s2 gtgt $s3 Shift r ight arith b y vari able
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
34
67
bull L e costanti sono util izzati fr equentemente (50 deglioperandi) Esempio A = B + 5
bull Possibile soluzionendash mettere le costanti in memoria e caricarle nei registri
bull I str uzioni MI PS per manipolare costantindash particolari versioni delle istruzioni aritmetiche (sempre I-type)
ndash operando immediat o di 16 bits
addi $29 $29 4
sl t i $8 $18 10
andi $29 $29 6
or i $29 $29 4
Costanti
68
bull Si pr ocede in due passi
bull Esempio caricare 0xaabbccddndash Si caricano i 16 bit piugrave signifi cativi
l ui $t 0 1010 1010 1011 1011
bull Bit meno significativi posti a zero
ndash Si caricano i 16 bit meno significativi (or i add i )
or i $t 0 $t 0 1100 1100 1101 1101
bull Nota dif fer enza tra or i e addi ( est segno)
bull Principio di pr ogetto 4ndash rendere veloce lrsquoevento piugrave f requente (costanti come parte
dellrsquoistruzione rende la loro esecuzione piugrave veloce)
Come caricare costanti l unghe 32 bits
0xa abb 0x0 000
0x0 000 0xc cdd
0xa abb 0xc cdd
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
35
69
Car icamento di costanti
bull Load 0x12345678 in R8 (LI $8 0x12345678)
lui $8 0x123 4
ori $8 0 x5678
bull Load 0x1234 in R8 (LI $8 0x1234)
addi $8 $zer o 0x 1234
bull Load -1 in R8 (LI $8 -1)
addi $8 $zero -1
1234 0000
1234 5678
Zero Fill
0000 1234
Sign Extended
FFFF FFFF
Sign Extended
70
bull I str uzionibne $t 4 $t 5 Label Salta a Label se $t 4 =$t 5
beq $t 4 $t 5 Label Salta a Label se $t 4==$t 5
j Label Salta Label
bull Formato gli indir izzi non sono di 32 bits op rs rt 16 bi t addre ss
op 26 bi t addr ess
I
J
In dir izzamento nei salti
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
36
71
bull Lrsquoistruzione d i salto condizionato (branch) hasolo 16 bits per lrsquoind iriz zo di salto
bull Indirizzamento PC-relativePC = registr o + indiri zzo di salto
ndash il programma puorsquo raggiungere la dimensione di 232 (4Gb)
ndash si puorsquo saltare fino ad una distanza plusmn215 word (plusmn128Kb)(principio di localitagrave)
Importantebull lrsquooff set ersquo relativo allrsquoin dirizz o dellrsquoistruzione successiva (PC+4)
bull lrsquooff set usa un indiriz zamento r elativo alle parole (deve esseremoltipl icato per 4 pr ima di essere sommato a PC+4)
In dir izzamento nei salti
72
Modi di indir izzamento
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
37
73
I ntervallo plusmn 32 Kb dalla base
In dir izzamento Base + Offset
74
In dir izzamento PC-r elative (branch)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
38
75
In dir izzamento PC-r elative (jump)
76
Pseudoistruzioni
bull Sono istr uzioni accettate dallrsquoassemblatore MI PS chenon hanno corrispettiv o nel linguaggio macchina peruno dei seguenti motivindash usano unrsquooperazione non implementata dallo hardware
ndash usano un modo di indirizzamento esteso non implementato dallohardware
bull L rsquoassemblatore le espande in sequenze di pocheistruzioni binar ie usando il registr o $1 ($at) riser vato
a questo scopo
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
39
77
Pseudo Ist r uzioni
bull aritmetichendash abs neg negu mul mlo mlou div divu rem remu
bull logichendash not
ndash rol ror
bull di trasfer imento datindash la ld ulh ulhu ulw li
ndash sd ush usw
ndash move
bull di confrontondash seq sge sgeu sgt sgtu sle sleu sne
78
Pseudo Ist r uzioni
bull di controllondash b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez
bull dei coprocessorindash mfc1d
bull floating-pointndash lis(d) ls(d)ss(d)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
40
79
Pseudoistruzioni esempi
bull la $4 l abel
l ui $1 Upper Par t Label Addr ess
or i $4 $1 Lower Par t Label Addr ess
bull bge $8$ 9addr ess
sl t at $8 $9
beq at $zer o addr ess
bull move $8 $10
addu $8 $0 $10
80
Pseudoistruzioni esempi
bull abs $9$ 8 addu $ 9$0 $8
bge z $8 $L
sub $9$ 0$8
$L
bull abs $8$ 8 bgez $ 8$L
sub $8$ 0$8
$L
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
41
81
Pseudo-Indir izzamento
bull Si ha quando il modo di indiri zzamento usato non egravedirettamente forni to dal processore
bull Anche in questo caso una singola (pseudo)istruzioneviene tradotta in una sequenza di piugrave istr uzioni di
macchina
bull Esempio
J Labe l
82
bull Tutte le istruzioni sono lunghe 32 bits (1 word)
bull Solo tre i formati delle istruzioni
op r s r t r d shamt f unct
op r s r t 16 bi t addr ess
op 26 bi t addr ess
R
I
J
Riassumendo
MIPS operands
Name Example Comments$s0-$s7 $t0-$t9 $zero Fast locations for data In MIPS data must be in registers to perform
32 registers $a0-$a3 $v0-$v1 $gp arithmetic MIPS register $zero always equals 0 Register $at is
$fp $sp $ra $at reserved for the assembler to handle large constants
Memory[0] Accessed only by data transfer instructions MIPS uses byte addresses so230 memory Memory[4] sequential words differ by 4 Memory holds data structures such as arrayswords Memory[4294967292] and spilled registers such as those saved on procedure calls
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
42
83
RiassumendoMIPS assembly language
Category Instruction Example Meaning Commentsadd add $s1 $s2 $s3 $s1 = $s2 + $s3 Three operands data in registers
Arithmetic subtract sub $s1 $s2 $s3 $s1 = $s2 - $s3 Three operands data in registers
add immediate addi $s1 $s2 100 $s1 = $s2 + 100 Used to add constantsload word lw $s1 100($s2) $s1 = Memory[ $s2 + 100] Word from memory to register
store word sw $s1 100($s2) Memory[$s2 + 100] = $s1 Word from register to memory
Data transfer load byte lb $s1 100($s2) $s1 = Memory[ $s2 + 100] Byte from memory to registerstore byte sb $s1 100($s2) Memory[$s2 + 100] = $s1 Byte from register to memoryload upper immediate
lui $s1 100 $s1 = 100 2 16 Loads constant in upper 16 bits
branch on equal beq $s1 $s2 25 if ($s1 == $s2 ) go to PC + 4 + 100
Equal test PC-relative branch
Conditional
branch on not equal bne $s1 $s2 25 if ($s1 = $s2 ) go to PC + 4 + 100
Not equal test PC-relative
branch set on less than slt $s1 $s2 $s3 if ($s2 lt $s3 ) $s1 = 1 else $s1 = 0
Compare less than for beq bne
set less than immediate
slti $s1 $s2 100 if ($s2 lt 100 ) $s1 = 1 else $s1 = 0
Compare less than constant
jump j 2500 go to 10000 Jump to target address
Uncondi- jump register jr $ra go to $ra For switch procedure returntional jump jump and link jal 2500 $ra = PC + 4 go to 10000 For procedure call
84
Riassumendo
bull Tutte le istruzioni modificano tutti i 32 bits del registro destinazione (incluso
lui lb lh) e tutte leggono i 32 bits della sorgente (add sub and or hellip)
bull Le istruzioni Imm ediate aritmetiche e logiche sono estese nel seguente modo
ndash gli operandi logici immediati sono ldquozero extendedrdquo a 32 bitsndash gli operandi aritmeti ci i mmediati sono ldquosign extendedrdquo a 32 bits (incl uso addu)
bull I dati caricati da lb e lh sono estesi nel seguente modondash lbu l hu ldquozero extendedrdquo
ndash lb l h ldquosign extendedrdquo
bull Overflow puorsquo verificarsi conndash add sub addi
bull non puorsquo verificarsi conndash addu subu addiu and or xor nor shifts mult multu div divu
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
43
85
Summar y
bull I nstruction complexity is only one var iablendash lower instruction count vs higher CPI lower clock rate
bull Design Principlesndash simplicity favors regularity
ndash smaller is faster
ndash good design demands compromise
ndash make the common case fast
86
Il sim ulator e SPIM
bull Ersquo un simulatore dellrsquoarchi tettur a MIPS R2000R3000inclusi il coprocessore 1 parte del coprocessore 0 e unter minale memory-mapped
bull Esiste in una versione per W indows (PCSpim) chendash accetta un programma scritto in linguaggio assembly completo di
direttive e di pseudoistruzioni
ndash dispone di un debugger che consente di inserire breakpoint e dieseguire a singoli step
bull Ersquo fedele anche sendash usa quale ordinamento dei byte quello (little-endian o big-endian)
proprio dello hardware su cui gira (Win-SPIM egrave little-endian)
ndash non rispetta i tempi di esecuzione inclusi i ritardi delle istruzionidi moltiplicazione e divisione di quelle floating-point e ognilatenza di memoria
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
44
87
Assembler di Spim
bull I l programma egrave organizzato in linee
bull Ogni linea puograve contenere un commento che parte dalcarattere e si estende fino alla fine della linea
bull Ogni linea che non sia bianca o contenga solo uncommento puograve essere una istruzione (o pseudo-
istruzione) o una direttiva
bull Spazi tab e vir gole () fungono da separatori
bull Gli identi ficatori sono sequenze di caratterialfanumerici (letter e cifr e $) under score(_) e punto ()che non incominciano per cifr a
88
Assembler di SPIM
bull L ettere minuscole e maiuscole non sono equivalenti
bull L e etichette (label) si defin iscono scrivendole allrsquoi niziodella linea seguite da due punti ()
bull I mnemonici di istr uzioni pseudoistruzioni direttiv e eregistri ($0-$31 $zero $at ) sono riser vati
bull I numer i si indicano in decimale (default) o sepreceduti da 0x in esadecimale
bull L e stringhe si r acchiudono tr a ldquo conndash newline n
ndash tab t
ndash quote rdquo
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
45
89
Strut tu r a di un pr ogramma assembler
da ta se gment o dati
ele mento wo rd 10
te xt se gment o codi ce
gl obal main main
mai n
bull Global vs Externalndash global etichetta rende etichetta visibile agli altr i files
ndash extern etichetta etichetta ersquo dichiarato come global in un altro file
90
Dir ettive
bull L e principali dir etti ve allrsquoassemblatore sonondash data kdata
ndash text ktext
ndash space
ndash ascii asciiz byte double float half word
ndash align
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
46
91
data kdata
bull da ta introduce dati da caricare nel segmento dati
bull kda ta introduce dati da caricare nel segmento dati
del ker nel
bull I dati sono caricati nel segmento dati a parti r edallrsquoin dir izzo 0x10010000 in modo da poter esser eagevolmente indirizzati trami te $gp
bull I dati sono caricati nel segmento dati del ker nel aparti r e dallrsquoin dir izzo 0x90000000
92
Global Pointer
bull Disponendo di un offset a 16 bit le istruzioni diloadstore non possono accedere dir ettamente ai datistatici
lui $16 0x100 0
lw $2 0 x8000( $16)
bull Conviene dedicare un r egistro (per convenzione $28)come puntatore globale caricandovi lrsquoin dir izzo0x10008000 (egrave automatico in SPIM ) in modo darender e direttamente accessibil i i primi 64KB dei dati
statici
lw $2 0 ($28)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
47
93
text ktext
bull te xt introduce istr uzioni e word da caricare nel
segmento testo
bull kt ext introduce istr uzioni e word da caricare nelsegmento testo del ker nel
bull I str uzioni e word sono caricate a parti r e dallrsquoin dir izzo
0x00400000 nel segmento testo e 0x80000000 nelsegmento testo del ker nel
94
space
bull sp ace n alloca n byte non inizializzati nel segmento
corrente
bull usato per dichiarare arr ay ed altre str utture datindash buffer space 100
bull usato nel segmento testo del kernel per porre il tr aphandler (start-up program) a partire dallrsquoi ndirizzo0x8000080ndash ktext
ndash space 0x80
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
48
95
ascii asciiz
bull as cii s tringa Carica str inga in memor ia senza
ter minarla con nul
bull as ciiz string a Carica stringa in memoriater minandola con nul
bull as ciiz ldquoI nput datanrdquo
96
byte half word float double
bull Consentono di caricare piugrave numeri nei formati bytehalfword word float e double in posizioni consecutive dimemor iandash byte b1 bn
ndash half h1 hn
ndash word w1 wn
ndash float f1 fn
ndash double d1 dn
bull Gli inter i sono esprimi bili in decimale o esadecimale
bull I float e double vanno espressi in decimale con
obbligatorio dopo parte intera ed esponente (e) opzionale
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
49
97
__star t
bull Ersquo l rsquoetichetta che per default specifica la primaistruzione eseguibile del programma
bull Ersquo d i solito defin ita nel trap fi le dove egrave associata alcodice
__st ar t
j al mai n
l i $v0 10 syscal l 10 ( exi t )
syscal l
bull I n questo caso egrave sufficiente che il pr ogramma contengala funzione main secondo la convenzione C
98
Caratter ist iche essenziali di PCSpim
http wwwcswiscedu~larusspimhtml
bull clear pulisce registr i e memor ia
bull load carica il programma
bull run esegue il pr ogramma
bull step esecuzione single-step
bull breakpoint setdelete breakpoints
bull Notandash Codice di Startup ersquo pre-caricato
ndash Pseudo-istruzioni sono espanse in istruzioni reali
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
50
99
Chiamate di sistema (system call)
bull I nterfaccia attraverso la quale il pr ogrammainter agisce col sistema operativ o
bull Modalitarsquo drsquousondash mettere il parametro in un registro ( $a0 $a1)
ndash specificare il tipo di system call (mettendo un parametro nelregistro $v0)
ndash syscal l
bull Esempiomove $a0 $t 2
l i $v0 1
syscal l
100
System call
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
51
101
bull Design alter nativendash provide more powerful operations
ndash goal is to reduce number of instructions executed
ndash danger is a slower cycle time andor a higher CPI
bull Sometimes r efer red to as ldquoRISC vs CISCrdquondash virtually all new instruction sets since 1982 have been RISC
ndash VA X minimize code size make assembly language easy
ndash instructions from 1 to 54 bytes long
bull Wersquoll look at Power PC and 80x86
Ar chitectur e alter native
102
Power PC
bull I ndexed addressingndash example lw $t1$a0+$s3
$t1=Memory[$a0+$s3]
ndash What do we have to do in MIPS
bull Update addressingndash update a register as part of load (for marching through arrays)
ndash example lwu $t04($s3)$t0=Memory[$s3+4]$s3=$s3+4
ndash What do we have to do in MIPS
bull Other sndash load multiplestore multiple
ndash a special counter register ldquo bc Loop rdquo
ndash decrement counter if not 0 goto loop
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
52
103
80x86
bull 1978 The Intel 8086 is announced (16 bit architecture)
bull 1980 The 8087 floating point coprocessor is added
bull 1982 The 80286 increases addr ess space to 24 bits +instructions
bull 1985 The 80386 extends to 32 bits new addr essing modes
bull 1989-1995 The 80486 Pentium Pentium Pro add a few
instructions (most ly designed for higher perform ance)
bull 1997 M MX is addedndash ldquoThis history illustrates the impact of the ldquogolden handcuffsrdquo of
compatibili ty
ldquoadding new features as someone might add clothing to a packed bagrdquo
ldquoan architecture that is diffi cult to explain and impossible to loverdquo
104
A dominant ar chi tectur e 80x86
bull See your textbook for a more detailed description
bull Complexityndash Instructions from 1 to 17 bytes long
ndash one operand must act as both a source and destination
ndash one operand can come from memory
ndash complex addressing modes
ndash eg ldquo base or scaled index with 8 or 32 bit displacementrdquo
bull Saving gracendash the most frequently used instructions are not too diffic ult to build
ndash compilers avoid the portions of the architecture that are slow
bull ldquo what the 80x86 lacks in style is made up in quantitymaking it beautiful from the right perspectiverdquo
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
53
105
Registr i 80386
106
Istr uzioni 80x86
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
54
107
Formati istr uzioni 80x86
108
esempio
T his i s the data segme nt
da ta
string 0 as ciiz This is a text string n
item0 wo rd 99
array0 wo rd 11 22 33 44 5 5 66 77 88 99
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
55
109
esempio
EXAMPLE I Pr int a st rin g on the c ons ole
The meth od is to l oad th e add res s of the s tri ng in to
$a0 a nd th en use a sy sca ll to pr in t t he st rin g
la $a0 st ri ng0 Load the base addr ess
of st rin g0 in to $a0
li $v0 4 Set $ v0 to 4 th is
te lls sy sc all to
pr int th e tex t s tr ing
sp eci fie d by $a0
sy sc all Now p rin t the te xt
st rin g t o the co ns ole
110
esempio
EXAMPLE II L oad an i nte ger f rom t he dat a seg ment
and p rin t it
lw $a0 it em0 Load the v alu e o f ite m0
in to $a0
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
56
111
esempio
EXAMPLE III Read an integer from the console
li $v0 5 Set $v0 to 5 this tells
syscall to read an
integer from the console
syscall Now read the integer
The integer is now in $v0
112
esempio
EXAMPLE IV P rin t an ele ment fro m an int eger arr ay
in t he dat a seg ment
li $ t0 3 Set t 0 t o 3 the i nde x o f
th e e lem ent w e a re fe tch in g
li $ t1 4 Set t 1 t o 4 thi s is the
si ze in by tes of a n e lem ent
mul $t2 $ t1 $ t0 t2 = t1 t0 so t 2 i s t he
BYTE off se t o f t he el ement
lw $a0 ar ra y0( $t2 ) L oad t he ele ment of th e
ar ray n ot e t hat t he fir st
el ement in th e a rr ay has
an of fse t of zer o
li $v0 1 Set $ v0 to 1 th is te lls
sy sca ll to pr int t he
in teg er sp eci fie d by $a0
sy sc all Now p rin t the in te ger
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)
3803
57
113
esempio
EXAMPLE V Halt the program
li $v0 10 set $v0 to 10 this tells
syscall to end execution
syscall
114
esempio
C MIPS
=== ======
global var data
x = y lw $t0 y
sw $t0 x
x = y + z lw $t0 y
lw $t1 z
add $t0 $t0 $t1
sw $t0 x
char s[] = hello n s asciiz hello n
x = s[2] li $t0 2
lb $t1 s($t0)
x = s[y] lw $s0 y
lb $s1 s($s0)