Overview

In this reading, you will be introduced to the basics of control flow x86-64, specifically how if statements and conditionals (e.g. x < 10) are implemented in x86-64.

Control flow in x86-64 is much more convoluted than in a high-level language like Java. You’ll likely need to read the same material multiple times before it starts to fully sink in: make sure you give yourself a break between successive readings and use the book’s practice problems to your advantage.

Required Reading

Sections 3.6.0-3.6.5 (pp. 200-213), excluding section 3.6.4, 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. Describe the role of each of the condition code registers.
  2. Compare the CMP instruction with both of the following instructions: SUB and TEST.
  3. Given some C code, determine which lines might require the use of SET and JUMP instructions.
  4. Given a JUMP instruction, determine: the condition(s) under which the jump will occur; the destination of the jump.
  5. Convert an if-else statement in C to an equivalent C implementation that mimics assembly and uses goto.

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 a table of register and memory values as well as an x86-64 instruction, determine the contents of the condition registers after executing the instruction.
  2. Given C code that assigns a comparison to a variable (e.g. int x = a > b), determine the set of CMP, TEST, and SET instructions that will be used.
  3. Convert between C code that contains if-else statements 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. In your own words, describe why x86-64 has condition code registers.

  2. Identify the lines in the follow C code where x86-64 SET and JUMP instructions would likely be used, indicating which type of instruction (SET or JUMP) would be used for each of those lines.

    a = b && c;
    d = a > 0;
    if (d)
        return (x << 2);
  3. Consider the following x86-64 code.

    cmpq X, %rax
    jge foo

    For what integer values (replacing X) would this code jump to the foo target? Assume that %rax contains the value 7.

  4. Convert the following C code into an equivalent version that mimics assembly code and uses goto. To be clear, your answer should still be in C (not x86-64 code).

    int foo(int a, int b) {
        int x = 0;
    
        if (a > b)
            x = rand();
        else
            x = 1;
    
        return x;
    }