teaching machines

CS 352 Lecture 19 – Jumping

October 21, 2016 by . Filed under cs352, fall 2016, lectures.

Dear students,

We now jump into jumps. Normally, the flow of control goes from top to bottom in a sequence of code. But that’s not how it works in our high-level code, where we have loops and conditionals. At the assembly level, there is no such thing as if. Nor is there while or for. There’s only jmp and its conditional cousins. To make non-marching flow of control, we first need bookmarks into our code, which are usually called labels:

  ...

(LOOP)
  ...

(POSTLOOP)
  ...

Then we can jump to these labels with a jump instruction. Jumps in the Hack assembly from our textbook have this form:

@LABEL_TO_JUMP_TO
expr;jmp-instruction

expr can be any expression that the ALU can perform. You should avoid assigning to M in the jump expression, because A holds the address of an instruction, thanks to the @ instruction. A write to M would interpret an instruction address as a data address, which seems like a pretty bad idea. The jmp-instruction comes in eight different flavors:

mnemonic effect
JGT if expr > 0
JGE if expr >= 0
JLT if expr < 0
JLE if expr <= 0
JEQ if expr == 0
JNE if expr != 0
JMP unconditional jump
null jump to PC + 1

Let’s start by writing a forever counter:

  @i
  M=0

(LOOP)
  @i
  M=M+1
 
  // Load up PC target.
  @LOOP
  0;JMP

That is an unconditional jump for an infinite loop.

Next let’s write a program that sets R2 to 1 if R1 is greater than 0, to 0 if R1 equals 0, or to -1 if R1 is less than 0. This function is sometimes called sign.

Now, let’s have a little Program This:

Our ALU computes a few arithmetic operations, but one in particular is missing: multiplication. First, write in a HLL a function multiply with this signature—but without using the * operator:
int multiply(int a, int b) {
  // produce the product
}
Let’s write a program that multiples R4 by R5 and stores the product in R6. The trick to multiplication is to expand it out to repeated addition.

See you next class!

Sincerely,

P.S. It’s Haiku Friday!

Considered harmful
goto had no place to go
But terrorism