# =============================================================================
# Makefile for Stanford CS149 Lecture 2 demos
# =============================================================================
#
# [What this builds]
#   Four C++ programs (real threads, real SIMD instructions, real timing) and
#   runs two Python simulators.
#
# [How to use]
#   make            # build every C++ demo for this machine (NEON on Apple/Arm)
#   make run        # build, then run all demos in order (~15 s in total)
#   make selftest   # self-checks of the two Python modules
#   make avx2       # optional: x86-64 AVX2 build of demo 01 (Intel/AMD Linux,
#                   #   or Rosetta 2 on an Apple Silicon Mac), then run it
#   make clean      # remove built files
#
# [Why these flags]
#   -std=c++20 -O2 -pthread  as in Lecture 1.
#   No -march/-mcpu flag is needed on arm64: NEON is part of every 64-bit Arm
#   CPU. On x86-64, AVX2 and FMA must be enabled explicitly (-mavx2 -mfma), and
#   the program then runs only on CPUs that have them (any Intel since 2013).
#   The headers come from ../lecture01 (timer, machine info) and sinx.h here.
# -----------------------------------------------------------------------------

CXX      ?= c++
CXXFLAGS := -std=c++20 -O2 -g -Wall -Wextra -pthread
PYTHON   ?= python3

HEADERS := sinx.h ../lecture01/cs149_timer.h ../lecture01/machine_info.h

BINS := 01_sinx_ladder 03_divergence_on_neon 05_latency_hiding 06_peak_flops

# On x86-64 the SIMD demos need AVX2 + FMA switched on.
ARCH := $(shell uname -m)
ifeq ($(ARCH),x86_64)
  SIMDFLAGS := -mavx2 -mfma
endif

.PHONY: all run selftest avx2 clean
all: $(BINS)

$(BINS): %: %.cpp $(HEADERS)
	$(CXX) $(CXXFLAGS) $(SIMDFLAGS) -o $@ $<

run: all
	@echo; ./01_sinx_ladder
	@echo; $(PYTHON) 02_divergence.py
	@echo; ./03_divergence_on_neon
	@echo; $(PYTHON) 04_hardware_multithreading.py
	@echo; ./05_latency_hiding
	@echo; ./06_peak_flops

selftest:
	$(PYTHON) simd_emulator.py
	$(PYTHON) mtcore.py

# Cross-compile demo 01 for x86-64 with AVX2. On an Apple Silicon Mac this
# needs Rosetta 2 to run; the timings then measure Rosetta's translation of
# AVX2 into 128-bit NEON, not a real 256-bit SIMD unit (see README).
01_sinx_ladder_avx2: 01_sinx_ladder.cpp $(HEADERS)
	$(CXX) $(CXXFLAGS) -arch x86_64 -mavx2 -mfma -o $@ $<

avx2: 01_sinx_ladder_avx2
	./01_sinx_ladder_avx2

clean:
	rm -f $(BINS) 01_sinx_ladder_avx2
	rm -rf *.dSYM __pycache__
