# =============================================================================
# Makefile for CMU 15-213 Lecture 5 (machine-level programming III:
# procedures and arrays)
# =============================================================================
#
#   make          build/oracle, build/oracle_x86 (real compiled procs.c) and
#                 the native C demos build/05_frames_in_real_memory{,_x86},
#                 build/06_arrays
#   make asm      build/procs.{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

.PHONY: all asm run clean
all: build/oracle build/oracle_x86 build/05_frames_in_real_memory \
     build/05_frames_in_real_memory_x86 build/06_arrays

build:
	mkdir -p build

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

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

# Native demos. -O1 keeps the recursion honest (no inlining across levels
# because of noinline) while still looking like real optimized code.
build/05_frames_in_real_memory: 05_frames_in_real_memory.c | build
	$(CC) -std=c11 -Wall -Wextra -O1 -o $@ $<

build/05_frames_in_real_memory_x86: 05_frames_in_real_memory.c | build
ifeq ($(X86),NONE)
	@echo "no x86-64 compiler here; skipping $@"
else
	$(CC) -std=c11 -Wall -Wextra -O1 $(X86) -o $@ $<
endif

build/06_arrays: 06_arrays.c | build
	$(CC) -std=c11 -Wall -Wextra -O1 -o $@ $<

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

run: all
	@python3 01_passing_data.py
	@echo; python3 02_stack_frames.py
	@echo; python3 03_register_conventions.py
	@echo; python3 04_recursion.py
	@echo; ./build/05_frames_in_real_memory
	@if [ -x build/05_frames_in_real_memory_x86 ]; then echo; ./build/05_frames_in_real_memory_x86; fi
	@echo; ./build/06_arrays
	@echo; python3 07_array_code.py
	@echo; python3 08_crosscheck.py

clean:
	rm -rf build __pycache__
