teaching machines

CS 330 Lecture 8 – Flow Control and Functions

February 8, 2013 by . Filed under cs330, lectures, spring 2013.

Agenda

TODO

Code

heads_tails.s

.section .data

format_string:
  .asciz "The random number was: %d\n"
heads_message:
  .asciz "Heads"
tails_message:
  .asciz "Tails"

.section .text
.globl main

main:
  # Seed the random sequence.
  pushl $58  
  call srand

  # Get random number, dropped into %eax.
  call rand

  pushl %eax

  # Is it even? Bitwise and -> even if its last bit is 0.
  andl $1, %eax

  # Compare the last bit to 1. Set flags to show result.
  cmpl $1, %eax

  # If equal, go to tails code.
  je tails

heads:
  pushl $heads_message
  call printf
  addl $4, %esp
  jmp quit

tails:
  pushl $tails_message
  call printf
  addl $4, %esp

quit:
  popl %eax

  pushl %eax
  pushl $format_string
  call printf
  addl $8, %esp

  pushl $0
  call exit

sum.s

.section .data

npeople:
  .long 43

nsiblings:
  .long 2,1,1,2,2,0,1,2,1,2,1,1,0,0,3,1,1,1,3,2,2,1,6,2,0,1,1,3,2,5,1,2,2,0,2,2,1,2,1,2,1,7,2

message:
  .asciz "The number of siblings is: %d\n"

.section .text
.globl main

main:
  movl $0, %eax
  movl $0, %edi

loop:
  cmpl %edi, npeople
  je exit_loop
  
  addl nsiblings(,%edi,4), %eax
  incl %edi

  jmp loop

exit_loop:
  pushl %eax
  pushl $message
  call printf
  addl $8, %esp

  pushl $0
  call exit

mult.s

.section .data

message:
  .asciz "The product is %d\n"

.section .text
.globl main

main:
  pushl $5
  pushl $4
  call myadd
  addl $8, %esp

  pushl %eax
  pushl $message
  call printf
  addl $8, %esp

  pushl $0
  call exit

myadd:
  # Save the caller's break pointer on
  # the stack.
  pushl %ebp

  # Set our break pointer to the current
  # top of stack. We'll use ebp as a
  # bookmark to get at our local variables
  # and function parameters.
  movl %esp, %ebp
  
  # Make a local variable for the sum.
  # A register would be faster, but
  # I want to demonstrate the
  # "declaration."
  subl $4, %esp

  # Add on first operand to the result.
  # I'd rather not introduce a register
  # (ebx) here, but the hardware only
  # supports so many memory references.
  movl 8(%ebp), %ebx
  movl %ebx, -4(%ebp)

  # Add on second operand.
  movl 12(%ebp), %ebx
  addl %ebx, -4(%ebp)

  # Drop return value in eax.
  movl -4(%ebp), %eax

  # Our work is mostly done. But we need
  # to tidy up. First, let's return the
  # stack pointer to what it was when
  # we started. ebp has that, 'cuz that's
  # what got assigned to ebp and it never
  # changed.
  movl %ebp, %esp

  # Now we restore the caller's break pointer,
  # which we pushed on the stack right away.
  popl %ebp

  # Go back to the instruction after the call.
  ret

Haiku

I am a pop star.
I put the funk in function.
I’ve got the movls.