IFs, LOOPs and DBRA

IF

Simple IF

a)HLL               b) 68K

x:=x+1              ADDQ.W   #1,X
IF A=7 THEN         CMPI.W   #7,A
   B:=3;            BNE      NEXT
   C:=4;            MOVEQ    #3,B
END IF              MOVEQ    #4,C
x:=X+2;        NEXT:
                    ADDQ.W   #2,X

b) At HLL

IF X=2 THEN                   CODE:=2;
   CODE:=1;       change to   IF X=2 THEN
ELSE                             CODE:=1;
   CODE:=2;                   END IF
END IF

This simplifies the code.

c) GENERAL LOOP

HLL                        68K

IF (I>GT> 0) THEN          CMPI.W   #0,I
   CODE(A)                 BLE      ELSE
ELSE                       CODE(A)
   CODE(B)                 BRA      NEXT
END IF                ELSE:
                           CODE(B)
NEXT                  NEXT:


d) I never want to see:

      STUFF                           STUFF
      BRA NEXT    replace with    NEXT:
NEXT:

You want to reduce the number of branches not put in superflous ones.

Loops

There are two types of loops in the world - REPEAT loops and WHILE loops. Repeat Loops are always executed once which is a rare for loops. You must always check yourself to see if it is safe to use a repeat loop. A while loop can be executed zero times and is always safe and very common in programming.

REPEAT Loops

a) Standard Repeat Loop
REPEAT:                        A read with a sentinel is 
     JSR     DECIN             suitable for a reat loop.
     CMP.W   '-1',d0
     BNE     REPEAT


b) General Loop

Loop:
     CODE(A)               Since CODE(A) always executed this
     CMPI.W   #0,I         is a repeat loop.
     BLT      NEXT
     CODE(B)
     BRA      LOOP


While Loop

a) OK VERSION b) Better Version PREVIOUS CODE PREVIOUS CODE Loop: BRA CHECK CMP --- LOOP: BEQ ENDLOOP CODE(C) CODE(C) CHECK: BRA LOOP CMP --- ENDLOOP: BNE LOOP NEXT CODE NEXT CODE

Some General Points about Loops

The DBRA Instruction 68000k

dbra  Di,Addr
sub.w #1,Di
cmp.w #-1,Di
bne   Addr
      move.w N,D2 ;Get N into a D reg, if not there already
      bra    EndL ;Start at the dbra instruction at the bottom
Loop: ...
      ...
EndL: dbra   D2,Loop
      move.w N,D1
Loop: ...
      ...
      dbra   Loop
      move.w  N,D1
      sub.w  #1,D1
Loop: ...
      ...
      dbra   Loop