Sistemi di Calcolo

Corso di Laurea in Ingegneria Informatica e Automatica - A.A. 2017-2018

HomePage | Avvisi | Diario lezioni | Programma | Materiale didattico | Esami | Forum | Login

Venerdì 20 e martedì 24 ottobre 2017 (Lezione 6 - 90 min) - Demetrescu/Coppa


Esercizio ripasso: array + passaggio parametri + registri callee-save + cast

sqr.c
int sqr(int x) {
    return x * x;
}


sommaQuadrati.c
int sqr(int x);

int sommaQuadrati(char * v, int n) {
    int s = 0;
    while (n > 0) {
        n--;
        s += sqr(v[n]);
    }
    return s;
}


sommaQuadrati.s
# int sumsqr(int* v, int n) {   //  v <-> esi, n <-> edi, s <-> ebx
#     int s = 0;
#     while (n>0) {
#         n--;
#         s += sqr(v[n]);
#     }
#     return s;
# }

.globl sumsqr
sumsqr:
    pushl %esi
    pushl %edi
    pushl %ebx
    subl $4, %esp

    movl 20(%esp), %esi         #    esi <- v
    movl 24(%esp), %edi         #    edi <- n
    movl $0, %ebx               #    int s = 0;
L:  cmpl $0, %edi               # L: if (n<=0) goto E;
    jle E
    decl %edi                   #    n--;
    movl (%esi, %edi, 4), %eax
    movl %eax, (%esp)
    call sqr
    addl %eax, %ebx             #    s += sqr(v[n]);
    jmp L                       #    goto L;
E:  movl %ebx, %eax             # E: return s;

    addl $4, %esp
    popl %ebx
    popl %edi
    popl %esi
    ret


main.c
#include <stdio.h>

int sommaQuadrati(char * v, int n);

int main() {
    char v[] = {2,3,4};
    printf("res=%d (atteso: %d)\n", sommaQuadrati(v, 3), 29);
    return 0;
}


Esercizio: variabili locali con LEA

f.c
int f() {
    int x;
    g(&x);
    return x;
}


f.s
.globl f

f:
    subl $8, %esp # prologo
    leal 4(%esp), %eax
    movl %eax, (%esp)
    call g
    movl 4(%esp), %eax
    addl $8, %esp # epilogo
    ret


main.c
#include <stdio.h>

int f();

void g(int * p) {
    *p = 23;
}

int main() {
    printf("%d\n", f());
    return 0;
}



Esercizio: SETcc (esempio esonero 2016/2017)

Tradurre in IA32 la seguente funzione C:

test.c
int test(int min, int max, int* x) {
    return (*x<min || *x>max) && max>min;
}


test-equiv.c
int test(int min, int max, int* x) {
    int si, di, d;
    char a, c;
    si = min;
    di = max;
    d = *x;
    a = d < si;
    c = d > di;
    a |= c;
    c = di > si;
    a &= c;
    return (int)a;
}


test.s
# int test(int min, int max, int* x) {
#     return (*x<min || *x>max) && max>min;
# }

.globl test

test:
    pushl %esi
    pushl %edi
    movl 12(%esp), %esi # min
    movl 16(%esp), %edi # max
    movl 20(%esp), %edx # x
    movl (%edx), %edx   # *x
    cmpl %esi, %edx
    setl %al
    cmpl %edi, %edx
    setg %cl
    orb %cl, %al
    cmpl %esi, %edi
    setg %cl
    andb %cl, %al
    movzbl %al, %eax
    popl %edi
    popl %esi
    ret
Valid XHTML 1.0 Transitional :: Valid CSS :: Powered by WikkaWiki
Page was generated in 0.0592 seconds