# =============================================================================
# Makefile for CMU 15-213 Lecture 4 (machine-level programming II: control)
# =============================================================================
#
#   make          build/oracle, build/oracle_x86 (real compiled control.c) and
#                 build/branch_prediction (native timing benchmark)
#   make asm      build/control.{Og,O1}.x86_64.s
#   make run      run every demo
#   make clean
#
# The Python demos import x86sim from ../lecture03 (see course_path.py).
# -----------------------------------------------------------------------------

CC       ?= cc
ASMFLAGS := -std=c11 -Og -fno-asynchronous-unwind-tables -fomit-frame-pointer \
            -fno-stack-protector -fcf-protection=none
CFLAGS   := $(ASMFLAGS) -Wall -Wextra -g
UNAME_S  := $(shell uname -s)
UNAME_M  := $(shell uname -m)

ifeq ($(UNAME_M),x86_64)
  X86 :=
else ifeq ($(UNAME_S),Darwin)
  X86 := -arch x86_64
else
  X86 := NONE
endif

PY := 01_instruction_encoding.py 02_branches_and_cmov.py 04_loops.py \
      05_switch_jump_tables.py 06_stack_call_ret.py 07_crosscheck.py

.PHONY: all asm run clean
all: build/oracle build/oracle_x86 build/branch_prediction

build:
	mkdir -p build

build/oracle: oracle.c control.c control.h | build
	$(CC) $(CFLAGS) -o $@ oracle.c control.c

build/oracle_x86: oracle.c control.c control.h | build
ifeq ($(X86),NONE)
	@echo "no x86-64 compiler here; skipping $@"
else
	$(CC) $(CFLAGS) $(X86) -o $@ oracle.c control.c
endif

# The benchmark is about the CPU we run on, so it is built natively at -O1.
build/branch_prediction: 03_branch_prediction.c | build
	$(CC) -std=c11 -Wall -Wextra -O1 -o $@ $<

asm: control.c control.h | build
ifneq ($(X86),NONE)
	$(CC) $(ASMFLAGS) $(X86) -S -o build/control.Og.x86_64.s control.c
	$(CC) $(subst -Og,-O1,$(ASMFLAGS)) $(X86) -S -o build/control.O1.x86_64.s control.c
endif

run: all
	@python3 01_instruction_encoding.py
	@echo; python3 02_branches_and_cmov.py
	@echo; ./build/branch_prediction
	@for p in 04_loops.py 05_switch_jump_tables.py 06_stack_call_ret.py 07_crosscheck.py; \
	  do echo; python3 $$p; done

clean:
	rm -rf build __pycache__
