Assembly Language Programming

Layout of Program in Memory.

When a program is in memory it expects certain parts of its address space to contain certain parts of the program. The top 2 Gbytes are reserved for kernel data structures and code. The following 4 Kbytes are reserved for the urea which is where paramaters between user and kernel are exchanged. The stack follows the urea and grows down. From the bottom the first 4 Mbytes are reserved, followed by the program text (the instructions). Then there is reserved space for shared libraries followed by segments for the all the different types of statically allocated data. The .data segments are for data that has an initial value while the .bss segments are for zero initialized data.

Mips Register Conventions

The Mips processor has 32 registers that are general purpose. This implies that they can be used interchangeably. However, for programming reasons certain conventions are used in order to determine what values those registers are expected to contain.

How to pass parameters to assembly procedures

A simple C routine

  
  int gcd (int a, int b)
  {
    int remainder;
    while (1) {
       if (a > b)
          remainder = a%b;
       else
          remainder = b%a;
       if (remainder == 0) {
          if (a>b)
             return b;
          else 
             return a;
       } else {
          if (a>b)
             a = remainder;
          else
             b = remainder;
       }
    }
  }
  

The not so simple Assembly equivalent with annotated C in Assembly Comments

Lines that start with # are comment lines.
  
          .text
          .global gcd
          .ent gcd
          .set noreorder
  gcd:
   #      while (1)
  $L1:
   #      if (a > b)
          slt     $2,$5,$4
          beq     $2,$0,$L2
   #      remainder = a%b
          rem     $3,$4,$5
          j       $L3
  $L2:
   #      remainder = b%a
          rem     $3,$5,$4
  $L3:
   #      if (remainder == 0)
          bne     $3,$0,$L4
   #      if (a > b)        
          slt     $3,$5,$4
          move    $2,$4
   #      return a
          beq     $3,$0,$end
          move    $2,$5
   #      return b
          j       $end
  $L4:
   #      else
   #      if (a > b)
          slt     $2,$5,$4
          beq     $2,$0,$L5
   #      a = remainder
          move    $4,$3
          j       $L1
   #      else
   #      b = remainder
          move    $5,$3
          j       $L1
  $end:
          j       $31