Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

This is homework for which we have prepared Nios 2 assembly and C:

########################################
# Definitions of device-addresses
# and important constants.
#

# de2_pio_keys4 - 0x840
.equ    keys4base,0x840
.equ    TRAPCODE, 0x003B683A

# uart_0 - 0x860
.equ    uart0base,0x860

# timer_1 - 0x920
.equ    timer1base,0x920

#
# Timer 1 time-out definition.
# The clock frequency at the lab session is 50 MHz.
# For simulation, use a 0.1-second time-out.
# At the lab session, use a 1-second time-out.
#
.equ    timer1count,5000000    # Change this value at the lab session

#
# End of definitions of device-addresses
# and important constants.
########################################


########################################
# Macro definitions begin here
#

#
# PUSH reg - push a single register on the stack
#
.macro PUSH reg
    subi sp,sp,4    # reserve space on stack
    stw  \reg,0(sp) # store register
.endm

#
# POP  reg - pop a single register from the stack
#
.macro POP  reg
    ldw  \reg,0(sp) # fetch top of stack contents
    addi sp,sp,4    # return previously reserved space
.endm

#
# PUSHMOST - push all caller-save registers plus ra
#
.set noat           # required since we push r1
.macro PUSHMOST
    PUSH  at        # push assembler-temporary register r1
    PUSH  r2
    PUSH  r3
    PUSH  r4
    PUSH  r5
    PUSH  r6
    PUSH  r7
    PUSH  r8
    PUSH  r9
    PUSH r10
    PUSH r11
    PUSH r12
    PUSH r13
    PUSH r14
    PUSH r15
    PUSH  ra        # push return address register r31
.endm

#
# POPMOST - pop ra plus all caller-save registers
# POPMOST is the reverse of PUSHMOST
#
# .set noat is already done above - no need to repeat that
.macro POPMOST
    POP   ra
    POP  r15
    POP  r14
    POP  r13
    POP  r12
    POP  r11
    POP  r10
    POP   r9
    POP   r8
    POP   r7
    POP   r6
    POP   r5
    POP   r4
    POP   r3
    POP   r2
    POP   at
.endm

#for use in trap inside of interuptions
.macro POPINT
    POP r29
    POP r24
    POP r4
    POP r5
.endm

#for use in trap inside of interuptions
.macro PUSHINT
    PUSH r5
    PUSH r4
    PUSH r24
    PUSH r29
.endm

.macro SysCall index
    movia r4, \index
    trap
.endm

#
# Macro definitions end here
########################################

.text
.align 2

########################################
# Stub/trampoline
# Three machine instructions (remember,
# movia is expanded into two instructions).
# The stub/trampoline-code must be copied
# to the exception-address
# (0x800020 in the current system).
#
# Stub/trampoline explanation:
# move address of exception handler
# into exception-temporary register et
# Use JMP to jump to the interrupt handler
# (whose address is now in et)
stub:
    movia   et,exchand
    jmp     et
#
# End of stub/trampoline.
########################################


########################################
# The following section replaces the
# Altera-supplied initialization code.
#
.global alt_main
alt_main:
    nop
    wrctl   status,r0
    br      main

    nop
    nop
    # Those NOPs are really not necessary,
    # but may help when you debug the program.
    # Without the NOPs, the branch instruction
    # would just jump to the next address
    # sequentially, which can be confusing.

#
# End of replacement for Altera-supplied
# initialization code.
########################################


########################################
# Main program follows.
#

    .data
    .align 2
mytime: .word 0x5957

    .text
    .align 2

#
# The label main
# must be declared global
#
.global main

main:
    # Always disable interupts before
    # initializing any devices
    wrctl   status,r0

    #
    # Add your code here to copy the stub
    # to address 0x800020 and on.
    # Remember to copy all three instructions
    # (movia is expanded to two instructions).
    #

    movia   r5, stub
    movia   r6, 0x800020
    #copy movia del 1
    ldw     r7, 0(r5)
    stw     r7, 0(r6)
    #copy movia del 2
    ldw     r7, 4(r5)
    stw     r7, 4(r6)
    #copy jmp
    ldw     r7, 8(r5)
    stw     r7, 8(r6)


    #
    # Add your code here to initialize timer_1 for
    # continuous interrupts every 100 ms (0.1 s)
    #
    movia r8, timer1base  # basadressen till timern
    movia r9, timer1count
    srli r10, r9, 16 #flytta h�ga bitar till h�gerkant
    stwio r10,12(r8)   # periodh
    stwio r9, 8(r8)    # periodl
    movi r9, 0b0111  # R9 = 0b0111 (continuous=1 start=1, ITO=1)
    stwio r9, 4(r8)    # skriv till control


    #
    # For Assignment 4 (but not earlier!),
    # add code here to initialize de2_pio_keys4
    # for interrupts from KEY0
    #

    movia r8, keys4base # basadress till keys.
    movi  r9, 0b0001 #interrupt enable key0 only
    stwio r9, 8(r8) #interrupt mask raden förskjuten med 8 bytes i minnet.

    #
    # Add your code here to initialize the CPU for
    # interrupts from timer_1 (index 10) only.
    # For Assignment 4 (but not earlier!),
    # add code here to also initialize the CPU for
    # interrupts from de2_pio_keys4 (index 2)
    #
    movia r5, 0x0404    #index 2 & 10 ienable
    wrctl ctl3, r5
    movia r6, 0b1       #PIE status bit
    wrctl ctl0, r6

    #
    # Add your code here to enable interrupts
    # by writing 1 to the status register
    #
    movia   r5, 1
    wrctl   ctl1,r5 #status reg == ctl1

    #
    # Set start value for prime-space exploration.
    movia    r4,987654
#
# Main loop starts here.
mainloop:
    call    primesearch

    PUSH r4
    movi r4,33
    trap
    POP r4

    mov     r4,r2
#
# This is the end of the main loop.
# We jump back to the beginning.
    br      mainloop

#
# End of main program.
########################################


########################################
# Exception handler.
#
# This exception handler is extremely simplified.
# You will expand and improve the handler.
# When you do this, you must add comments -
# and change this comment - to reflect your changes.
#
exchand:
    nop
    nop
    # Those NOPs are not really necessary.
    # However, in this particular program,
    # they may help you setting a breakpoint
    # at the beginning of the handler
    # when you debug the program.

    # Here we should check the contents of estatus
    # to see if interrupts were enabled (Condition 1).

    #movia r5, 0b1      #comparebit
    #rdctl r6, ctl1     #PIE status bit
    #andi r7, r6, 0b1   #maska fram PIE status bit
    #bne r5, r7, noint  #if not, check if trap

    rdctl r24, ctl1 # läs estatus
    andi r24, r24, 1 # kolla EPIE-biten
    beq r24, r0, noint # hopp om EPIE=0
    rdctl r24, ctl4 # read from ipending
    beq r24, r0, noint # branch to noint if no pending interrupts


    # Then we should check if ipending is nonzero
    # (Condition 2).

    #rdctl r24, ctl14   #ipending
    #bne    r24, r0, noint  #if not, check if trap

    # If Conditions 1 and 2 are both true, the cause of
    # exception must have been an interrupt. In this case,
    # we should jump to the interrupt-handling code
    # at label exc_was_interrupt.
    movia r24, exc_was_interrupt
    jmp r24

    # Label noint - branch here (or fall-through) if you
    # are sure that the exception was NOT an interrupt.
noint:

    # Now, we should check if the instruction at the
    # exception location is a TRAP instruction.
    mov r24, r29
    subi r24, r24, 4
    ldw r24, 0(r24)
    PUSH r8
    movia r8, TRAPCODE
    cmpeq r24, r24, r8 #if instruktion at ea-4 is trap
    POP r8
    bne r24, r0, exc_was_trap #om trap, hoppa till exc_was_trap

    # If it was a TRAP instruction,
    # we should jump to label exc_was_trap.

    # Then we should perhaps check if the bit-pattern,
    # at the exception location, is that of
    # an unimplemented instruction
    # that we handle by software emulation. However,
    # this would be beyond the scope of this course.
    # In this extremely simplified handler, we check nothing.

    # The following label is a place to jump to,
    # after making sure that the cause of exception
    # really was an interrupt.
exc_was_interrupt:

    # Since we had an interrupt, and not a TRAP,
    # we must subtract 4 from the contents of the
    # exception-address register (ea), so that
    # the interrupted instruction gets restarted
    # when we return from the interrupt.
    # This requirement is Nios2-specific.
    subi    ea,ea,4

    # This is the place to check if the interrupt
    # came from timer_1 or from another source.
    # If the interrupt came from another source,
    # we must jump to a handler for that source.
    # Since we have only one source right now,
    # we omit the check (until Assignment 4).

    rdctl r24, ipending
    PUSH r8
    PUSH r9

    movi r8, 0x0400 #timer
    and r9, r24, r8 #maska fram
    beq  r8, r9, timer1int

    movi r8, 0x0004 #keys
    and r9, r24, r8 #maska fram
    beq  r8, r9, key0int
    #POP r8 & POP r9 need to be first in every interrupt handler. :)

    #om koden kommer hit har vi misslyckats epicly. odefinierat beteende
    jmpi -1
    #crashar förhoppningsvis och antagligen programmet...


key0int:
    POP r8
    POP r9

    # check if key0 is down (0) or up (1) and write 'D' or 'U' respectively to uart0.
    PUSH r8
    PUSH r9

    movi r8, 0b0001 #maska fram key0.
    movia r9, keys4base
    ldwio r9, 0(r9)
    and r9, r9, r8
    beq r9, r0, keydown #if 0, key down

keyup:

    PUSHMOST
    # Print character in R4 using out_char_uart_0.
    movia r4, 'U'
    call    out_char_uart_0
    # Restore the saved registers.
    POPMOST

    br acknowledgekeyint

keydown:

    PUSHMOST
    # Print character in R4 using out_char_uart_0.
    movia r4, 'D'
    call    out_char_uart_0
    # Restore the saved registers.
    POPMOST

acknowledgekeyint:
    POP r9
    POP r8

    # Acknowledge the interrupt
    movia   et,keys4base
    PUSH    r8
    movi    r8,1
    stwio   r8,12(et)    # clears int bits
    POP     r8

    # Branch to the end of the exception handler.
    br      excend

    # The following code is specific for
    # interrupts from timer_1
timer1int:
    POP r8
    POP r9

    # Acknowledge the interrupt
    movia   et,timer1base
    PUSH    r8
    movi    r8,1
    stwio   r8,0(et)    # clears timeout bit
    POP     r8

    # This is a first, simple handler.
    # All we do when we get a timer interrupt
    # is print a T on the console.
    # Since the JTAG UART uses interrupts itself,
    # this program must be compiled with a special
    # system library using another UART for the console:
    # We use uart_0.

    # Before calling a subroutine, push r1 through r15, and r31.
    PUSHMOST

    movia   r4,mytime
    call    puttime
    movia   r4,mytime
    call    tick

    # pushint pushes ea, r4, r5 on stack
    PUSHINT

    # read control register estatus to r5 so we can push it.
    rdctl r5, estatus
    PUSH r5

    movi r4,'T'
    trap

    # restore control register estatus from r5 after we pop r5.
    POP r5
    wrctl estatus, r5

    # popint restores ea, r4, r5 from stack
    POPINT

# Add code here for Assignment 3

    POPMOST
    # Afterwards, restore saved register values.

    # Branch to the end of the exception handler.
    br      excend

    # The following label is a place to jump to,
    # after making sure that the cause of exception
    # really was the result of a trap instruction.
exc_was_trap:

    # Our trap handler will call a subroutine.
    # We save all caller-saved registers here,
    # to avoid problems for the code containing
    # the trap instruction.
    PUSHMOST
    # Print character in R4 using out_char_uart_0.
    #movia r4, 33
    call    out_char_uart_0
    # Restore the saved registers.
    POPMOST

    # Fall-through to the end of the handler.
    # No branch needed (right now at least).

    # This is the end of the exception handler.
excend:
    eret
#
########################################

########################################
# Helper functions and support code.
# You do not need to study the following code.
#

# out_char_uart_0 - send byte on uart0
# one parameter, in r4: byte to send
# no return value
#
    .global out_char_uart_0
out_char_uart_0:
    movia   r8,uart0base
    ldwio   r8,8(r8)        # get uart0 status
    andi    r8,r8,0x40      # check TxRDY bit
    beq     r8,r0,out_char_uart_0   # loop if not ready
    andi    r4,r4,0xff      # sanitize argument
    movia   r8,uart0base
    stwio   r4,4(r8)        # write to uart0 TX data
    ret

################################################################
#
# A simplified printf() replacement.
# Implements the following conversions: %c, %d, %s and %x.
# No format-width specifications are allowed,
# for example "%08x" is not implemented.
# Up to four arguments are accepted, i.e. the format string
# and three more. Any extra arguments are silently ignored.
#
# The printf() replacement relies on routines
# out_char_uart_0, out_hex_uart_0,
# out_number_uart_0 and out_string_uart_0
# in file oslab_lowlevel_c.c
#
# We need the macros PUSH and POP (defined previously).
#

.text
.global nios2int_printf
nios2int_printf:
    PUSH    ra      # PUSH return address register r31.
    PUSH    r16     # R16 will point into format string.
    PUSH    r17     # R17 will contain the argument number.
    PUSH    r18     # R18 will contain a copy of r5.
    PUSH    r19     # R19 will contain a copy of r6.
    PUSH    r20     # R20 will contain a copy of r7.
    mov     r16,r4  # Get format string argument
    movi    r17,0   # Clear argument number.
    mov     r18,r5  # Copy r5 to safe place.
    mov     r19,r6  # Copy r6 to safe place.
    mov     r20,r7  # Copy r7 to safe place.
asm_printf_loop:
    ldb     r4,0(r16)   # Get a byte of format string.
    addi    r16,r16,1   # Point to next byte
    # End of format string is marked by a zero-byte.
    beq     r4,r0,asm_printf_end
    cmpeqi  r9,r4,92    # Check for backslash escape.
    bne     r9,r0,asm_printf_backslash
    cmpeqi  r9,r4,'%'   # Check for percent-sign escape.
    bne     r9,r0,asm_printf_percentsign
asm_printf_doprint:
    # No escapes present, just print the character.
    movia   r8,out_char_uart_0
    callr   r8
    br      asm_printf_loop
asm_printf_backslash:
    # Preload address to out_char_uart_0 into r8.
    movia   r8,out_char_uart_0
    ldb     r4,0(r16)   # Get byte after backslash
    addi    r16,r16,1   # Increase byte count.
    # Having a backslash at the end of the format string
    # is illegal, but must not crash our printf code.
    beq     r4,r0,asm_printf_end
    cmpeqi  r9,r4,'n'   # Newline
    beq     r9,r0,asm_printf_backslash_not_newline
    movi    r4,10       # Newline
    callr   r8
    br      asm_printf_loop
asm_printf_backslash_not_newline:
    cmpeqi  r9,r4,'r'   # Return
    beq     r9,r0,asm_printf_backslash_not_return
    movi    r4,13       # Return
    callr   r8
    br      asm_printf_loop
asm_printf_backslash_not_return:
    # Unknown character after backslash - ignore.
    br      asm_printf_loop
asm_printf_percentsign:
    addi    r17,r17,1   # Increase argument count.
    cmpgei  r8,r17,4    # Check against maximum argument count.
    # If maximum argument count exceeded, print format string.
    bne     r8,r0,asm_printf_doprint
    cmpeqi  r9,r17,1    # Is argument number equal to 1?
    beq     r9,r0,asm_printf_not_r5 # beq jumps if cmpeqi false
    mov     r4,r18      # If yes, get argument from saved copy of r5.
    br      asm_printf_do_conversion
asm_printf_not_r5:
    cmpeqi  r9,r17,2    # Is argument number equal to 2?
    beq     r9,r0,asm_printf_not_r6 # beq jumps if cmpeqi false
    mov     r4,r19      # If yes, get argument from saved copy of r6.
    br      asm_printf_do_conversion
asm_printf_not_r6:
    cmpeqi  r9,r17,3    # Is argument number equal to 3?
    beq     r9,r0,asm_printf_not_r7 # beq jumps if cmpeqi false
    mov     r4,r20       # If yes, get argument from saved copy of r7.
    br      asm_printf_do_conversion
asm_printf_not_r7:
    # This should not be possible.
    # If this strange error happens, print format string.
    br      asm_printf_doprint
asm_printf_do_conversion:
    ldb     r8,0(r16)   # Get byte after percent-sign.
    addi    r16,r16,1   # Increase byte count.
    cmpeqi  r9,r8,'x'   # Check for %x (hexadecimal).
    beq     r9,r0,asm_printf_not_x
    movia   r8,out_hex_uart_0
    callr   r8
    br      asm_printf_loop
asm_printf_not_x:
    cmpeqi  r9,r8,'d'   # Check for %d (decimal).
    beq     r9,r0,asm_printf_not_d
    movia   r8,out_number_uart_0
    callr   r8
    br      asm_printf_loop
asm_printf_not_d:
    cmpeqi  r9,r8,'c'   # Check for %c (character).
    beq     r9,r0,asm_printf_not_c
    # Print character argument.
    br      asm_printf_doprint
asm_printf_not_c:
    cmpeqi  r9,r8,'s'   # Check for %s (string).
    beq     r9,r0,asm_printf_not_s
    movia   r8,out_string_uart_0
    callr   r8
    br      asm_printf_loop
asm_printf_not_s:
asm_printf_unknown:
    # We do not know what to do with other formats.
    # Print the format string text.
    movi    r4,'%'
    movia   r8,out_char_uart_0
    callr   r8
    ldb     r4,-1(r16)
    br      asm_printf_doprint
asm_printf_end:
    POP     r20
    POP     r19
    POP     r18
    POP     r17
    POP     r16
    POP     ra
    ret

#
# End of simplified printf() replacement code.
#
################################################################

#
# End of file.
#
.end

/*
 * lab3upg1helpers.c - version 2010-02-22
 *
 * Written by F Lundevall.
 * Copyright abandoned.
 * This file is in the public domain.
 */

/* Declare functions which are defined in other files,
 * or late in this file (after their first use). */
int nextprime( int );
void out_char_uart_0( int );

/* The sloppy declaration of nios2int_printf below
 * hides the variable number of arguments,
 * and the variable types of those arguments. */
void nios2int_printf();

int primesearch( int next )
{
  next = nextprime( next );   /* Produce a new prime. */
  nios2int_printf( "\n\rMain: %d is prime", next );
  return( next );
}

/*
 * ********************************************************
 * *** You don't have to study the code below this line ***
 * ********************************************************
 */

/*
 * nextprime
 *
 * Return the first prime number larger than the integer
 * given as a parameter. The integer must be positive.
 */
#define PRIME_FALSE   0     /* Constant to help readability. */
#define PRIME_TRUE    1     /* Constant to help readability. */
int nextprime( int inval )
{
   register int perhapsprime = 0; /* Holds a tentative prime while we check it. */
   register int testfactor; /* Holds various factors for which we test perhapsprime. */
   register int found;      /* Flag, false until we find a prime. */

   if (inval < 3 )          /* Initial sanity check of parameter. */
   {
     if(inval <= 0) return(1);  /* Return 1 for zero or negative input. */
     if(inval == 1) return(2);  /* Easy special case. */
     if(inval == 2) return(3);  /* Easy special case. */
   }
   else
   {
     /* Testing an even number for primeness is pointless, since
      * all even numbers are divisible by 2. Therefore, we make sure
      * that perhapsprime is larger than the parameter, and odd. */
     perhapsprime = ( inval + 1 ) | 1 ;
   }
   /* While prime not found, loop. */
   for( found = PRIME_FALSE; found != PRIME_TRUE; perhapsprime += 2 )
   {
     /* Check factors from 3 up to perhapsprime/2. */
     for( testfactor = 3; testfactor <= (perhapsprime >> 1) + 1; testfactor += 1 )
     {
       found = PRIME_TRUE;      /* Assume we will find a prime. */
       if( (perhapsprime % testfactor) == 0 ) /* If testfactor divides perhapsprime... */
       {
         found = PRIME_FALSE;   /* ...then, perhapsprime was non-prime. */
         goto check_next_prime; /* Break the inner loop, go test a new perhapsprime. */
       }
     }
     check_next_prime:;         /* This label is used to break the inner loop. */
     if( found == PRIME_TRUE )  /* If the loop ended normally, we found a prime. */
     {
       return( perhapsprime );  /* Return the prime we found. */
     }
   }
   return( perhapsprime );      /* When the loop ends, perhapsprime is a real prime. */
}

/*
 * out_string_uart_0
 *
 * Simple output routine, replaces printf()
 * for constant strings.
 *
 * The argument is a pointer to an array of char.
 * The array can have any length, as long as there
 * is a trailing null-character at the end.
 *
 * This routine calls out_char_uart_0 repeatedly,
 * to do the actual output.
 */
void out_string_uart_0( char * cp )
{
  while( *cp )
  {
    out_char_uart_0( *cp );
    cp += 1;
  }
}

The improvement I can think of is placing the macros in files of their own instead of everything in the same file so that the file does not get this large and cumbersome.

share|improve this question

1 Answer 1

Macros in assembler language can be useful but you have to be careful not to over use them. Your PUSH/POP macros are overused and hence inefficient - and in interrupt related code, efficiency is king.

For example your PUSH macro has two instructions, reserving space and storing a register. You then use it 16 times in PUSHMOST (and its equivalent, POP in POPMOST). This will be processed into:

    subi sp, sp,4
    stw  at, 0(sp)
    subi sp, sp,4
    stw  r2, 0(sp)
    subi sp, sp,4
    stw  r3, 0(sp)
    subi sp, sp,4
    stw  r4, 0(sp)
    ... etc

It reserves 4 bytes 16 times! What you should do in PUSHMOST is to reserve space once and then store each register:

.macro PUSHMOST reg
    subi sp, sp,48
    stw  at, 0(sp)
    stw  r2, 0(sp)
    stw  r3, 0(sp)
    stw  r4, 0(sp)
    ... etc
.endm

Same goes for POPINT and PUSHINT

I'll come back to the main code later...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.