CS 352 Lecture 19 – Jumping
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 functionmultiplywith this signature—but without using the*operator:Let’s write a program that multiplesint multiply(int a, int b) { // produce the product }R4byR5and stores the product inR6. The trick to multiplication is to expand it out to repeated addition.
See you next class!

P.S. It’s Haiku Friday!
Considered harmfulgotohad no place to go
But terrorism