Spring 2016 CSCI 320 Homework 11

Back to CSCI 255

In the Fall 2015 offering of CSCI 255, Homework 10 required a few of you to rewrite a C routine, bubblepass, into MIPS32 assembly language.

Here’s a copy of the C version of bubblepass.

int bubblePass(int V[], int n) {
    int i ;
    int swappedCount = 0 ;
    for (i=0; i < n-1; ++i) {
	if (V[i] > V[i+1]) {
            int tmpSwapVar;
            tmpSwapVar = V[i] ;
            V[i] = V[i+1] ;
            V[i+1] = tmpSwapVar ;
            swappedCount++ ;
    return swappedCount ;

A compiler-generated solution

If you use gcc on a MIPS32processor running Linux to generate MIPS32 assembly language for this routine, the following code is obtained. (In this example, registers have been renamed from their numeric names, $5, to their symbolic names, $a1. Also, this code was generated at optimization level 2.)

	.file	1 "bubblepass.c"
	.section .mdebug.abi32
	.gnu_attribute 4, 3
	.align	2
	.globl	bubblePass
	.set	nomips16
	.ent	bubblePass
	.type	bubblePass, @function
	.frame	$sp,0,$ra		# vars= 0, regs= 0/0, args= 0, gp= 0
	.mask	0x00000000,0
	.fmask	0x00000000,0
	.set	noreorder
	.set	nomacro
	addiu	$a1,$a1,-1
	blez	$a1,$L9
	move	$v0,$zero

	move	$v1,$zero
	lw	$a2,0($a0)
	lw	$a3,4($a0)
	addiu	$v1,$v1,1
	slt	$t1,$a3,$a2
	beq	$t1,$zero,$L3
	slt	$t0,$v1,$a1

	sw	$a3,0($a0)
	sw	$a2,4($a0)
	addiu	$v0,$v0,1
	bne	$t0,$zero,$L4
	addiu	$a0,$a0,4

	j	$ra

	.set	macro
	.set	reorder
	.end	bubblePass
	.size	bubblePass, .-bubblePass
	.ident	"GCC: (GNU) 4.6.2"

Compiler-generated x86-64 code

You can also ask gcc to generate, also at optimization level 2, x86-64 assembly code.

	.file	"bubblepass.c"
	.p2align 4,,15
	.globl	bubblePass
	.type	bubblePass, @function
	subl	$1, %esi
	testl	%esi, %esi
	jle	.L5
	xorl	%edx, %edx
	xorl	%eax, %eax
	.p2align 4,,10
	.p2align 3
	movl	(%rdi,%rdx,4), %ecx
	movl	4(%rdi,%rdx,4), %r8d
	cmpl	%r8d, %ecx
	jle	.L3
	movl	%r8d, (%rdi,%rdx,4)
	movl	%ecx, 4(%rdi,%rdx,4)
	addl	$1, %eax
	addq	$1, %rdx
	cmpl	%edx, %esi
	jg	.L4
	rep ret
	xorl	%eax, %eax
	.size	bubblePass, .-bubblePass
	.ident	"GCC: (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4"
	.section	.note.GNU-stack,"",@progbits

Now that is pretty succinct: only eighteen instructions!

The Task

It’s not as hard as you might think. Look at the C code. Look at the x86-64 assembly code. Figure out how the registers of the x86-64 code correspond to the variables of the C code. Figure out how the instructions of the x86-64 code implement the statements of the C code.

Download a copy of the x86-64 code, load it into your favorite text editor, and annotate the x86-64 code with what you figured out in the previous paragraph. Finally upload your annotated x86-64 code to the Homework 11 moodle page. You can upload a text file or a PDF file.