Following is Aarchv8 assembly language program. Identify error in printarray function…
- User
Following is Aarchv8 assembly language program. Identify error in print_array function and fix it. Here is the code: .section .rodata getnstr: .string "Enter a value of n: " .align 3 intstr: .string "%d" .align 3 prntstr: .string "The array values are: \n" .align 3 tab10dintstr: .string "\t%10d\n" .align 3 nlstr: .string "\n" .align 3
.section .bss n: .skip 4 n16: .skip 4
.section .text .global main .type main, @function
main: stp x29, x30, [sp, #-16]! // main prolog
code// seed the random mov x0, 0 bl time bl srand //print and get the array size // printf (getnstr) ldr x0, =getnstr bl printf // scanf(intstr, &n) ldr x0, =intstr ldr x1, =n // memory location of n bl scanf // compute next highest multiple of 16 >= n. // SP has to be multiples of 16 ldr x1, =n ldr w1, [x1] sbfiz x1, x1, #2, #20 add x1, x1, #0xf // 0xf = 15 and x1, x1, #0xfffffffffffffff0 //15f's ldr x2, =n16 str w1, [x2] // create the storage for "n" integer, using stack sub sp, sp, x1 // create storage for the array // call init_array mov x0, sp ldr x1, =n ldr w1, [x1] bl init_array // call print_array mov x0, sp ldr x1, =n ldr w1, [x1] bl print_array // Return the local array back to the stack ldr x1, =n16 ldr x1, [x1] add sp, sp, x1 ldp x29, x30, [sp, #16] // main epilog ret// void init_array(int arr[], int n); .type init_array, @function // this is a private function init_array: stp x29, x30, [sp, #-16]! // function prolog mov x2, #0 // initialize loop counter mov x3, #0xa0a0 // 0xa0a0 is element stored in arr. could be changed to rand number.
loop1: cmp x2, x1 //compare i & n bge endloop1 str w3, [x0, x2, lsl 2] // store at [base adr of arr + i*4] add x2, x2, #1 b loop1
endloop1: ldp x29, x30, [sp], #16 //function epilog ret
// void print_array(int arr[], int n); .type print_array, @function print_array: stp x29, x30, [sp, #-16]! //function prolog mov x2, #0 // initialize loop counter
loop2: cmp x2, x1 // compare i & n bge endloop2 ldr w3, [x0, x2, lsl 2] // load at [base adr of arr + i*4] ldr x0, =tab10dintstr bl printf add x2, x2, #1 b loop2
endloop2: ldp x29, x30, [sp], #16 //function epilog ret
- Assistant
The error in the print_array function is that it is loading the format string tab10dintstr in each iteration of the loop. This is unnecessary and inefficient. The format string should be loaded outside the loop and stored in a register.
Here is the corrected code:
// void print_array(int arr[], int n); .type print_array, @function print_array: stp x29, x30, [sp, #-16]! //function prolog mov x2, #0 // initialize loop counter ldr x3, =tab10dintstr // load format string outside the loop
loop2: cmp x2, x1 // compare i & n bge endloop2 ldr w4, [x0, x2, lsl 2] // load at [base adr of arr + i*4] mov x0, x4 // move array element to argument register bl printf add x2, x2, #1 b loop2
endloop2: ldp x29, x30, [sp], #16 //function epilog ret