2 * inline-asm-array-sum - an example of inline assembly accessing arrays
4 * Copyright (C) 2013 Antonio Ospite <ospite@studenti.unina.it>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 static int array_sum(int *values, unsigned int n)
30 #if defined(__x86_64__)
32 "movq $0, %%rdi\n\t" /* i = 0 */
34 "cmpl %%edi, %%ecx\n\t" /* if (i == n) */
36 /* TODO: try incrementing the pointer by 4 */
37 "movq (%%rbx,%%rdi,4), %%rdx\n\t" /* tmp = values[i]; 64 bit register */
38 "addl %%edx, %%eax\n\t" /* sum += tmp[31:0]; */
39 "incl %%edi\n\t" /* i++ */
43 : "b"(values), "c"(n), "0"(sum)
44 : "%rdx", "%rdi", "cc"
48 for (i = 0; i < n; i++)
64 values = malloc(n * sizeof(*values));
67 for (i = 0; i < n; i++) {
69 expected += values[i];
72 sum = array_sum(values, n);
74 printf("expected = %d; sum = %d; %s\n", expected, sum, sum == expected ? "OK" : "FAILED");
75 return (sum == expected);