Overview

In this reading, you’ll continue your investigation into control flow in x86-64, this time with a focus on how loops are implemented. Loops share many characteristics with if statements in x86-64, but with their own basic algorithms to convert from C code to assembly. Focusing on these basic algorithms should help you while studying.

Required Reading

Section 3.6.7 (pp. 220-232) from the course textbook.

Learning Objectives

BASIC Learning Objectives

Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.

  1. Compare and contrast the jump to middle and guarded do implementations of while loops.
  2. Convert a for loop in C to an equivalent C “goto” implementation using either jump to middle or guarded do.

ADVANCED Learning Objectives

The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.

  1. Given x86-64 code, identify those instructions that correspond to if-else statements and those that correspond to loops.
  2. Convert between C code that contains do-while, while, and for loops and the equivalent x86-64 assembly code.

Pre-class Exercises

These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.

  1. Convert the following C code into two equivalent “goto versions” that mimic assembly code. One version should use jump to middle for loops while the other version should use guarded do.

    void arrayCopy(int *arr1, int *arr2, int len) {
        int i;
        for (i = 0; i < len; i++) {
            arr1[i] = arr2[i];
        }
    }
  2. Convert the following “goto version” of a C function to an equivalent version that does NOT use goto.

    int doSomething(int *arr, int len) {
        int i = 0, foo = 0;
        goto test;
    
    loop:
        foo += arr[i];
        i++;
    test:
        int t = (i < len);
        if (t) goto loop;
    
        return foo;
    }