# =============================================================================
# Makefile for Stanford CS149 Lecture 1 demos
# =============================================================================
#
# [What this builds]
#   Six C++ programs (real threads, real timing) and runs three Python models.
#
# [How to use]
#   make            # build every C++ demo
#   make run        # build, then run all demos in order (~30 s in total)
#   make selftest   # run the self-checks of the two Python modules
#   make clean      # remove built files
#
# [Why these flags]
#   -std=c++20   std::barrier (demo 03) is C++20; everything else is C++17.
#   -O2          timing optimized code is the only meaningful timing.
#   -pthread     link the threads library (needed on Linux, harmless on macOS).
#   Demo 05 is additionally built WITHOUT auto-vectorization, so it measures
#   instruction-level parallelism alone, not SIMD (that is Lecture 2). Clang
#   and GCC spell that flag differently; we ask the compiler which it is.
#
# [C++ tip] A rule is "target: prerequisites" followed by TAB-indented shell
#   commands. $@ = the target, $< = the first prerequisite. A line starting
#   with @ is run without echoing the command itself.
# -----------------------------------------------------------------------------

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

# "-fno-vectorize" for clang, "-fno-tree-vectorize" for gcc.
IS_CLANG := $(shell $(CXX) --version 2>/dev/null | grep -qi clang && echo yes)
ifeq ($(IS_CLANG),yes)
  NOVEC := -fno-vectorize -fno-slp-vectorize
else
  NOVEC := -fno-tree-vectorize -fno-tree-slp-vectorize
endif

HEADERS := cs149_timer.h machine_info.h

BINS := 00_know_your_machine \
        01_demo1_communication \
        02_demo2_load_imbalance \
        03_demo3_communication_dominated \
        05_ilp_on_real_cpu \
        08_memory_latency

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

# Every demo except 05 builds the same way: one .cpp -> one executable.
00_know_your_machine 01_demo1_communication 02_demo2_load_imbalance \
03_demo3_communication_dominated 08_memory_latency: %: %.cpp $(HEADERS)
	$(CXX) $(CXXFLAGS) -o $@ $<

05_ilp_on_real_cpu: 05_ilp_on_real_cpu.cpp $(HEADERS)
	$(CXX) $(CXXFLAGS) $(NOVEC) -o $@ $<

run: all
	@echo; ./00_know_your_machine
	@echo; ./01_demo1_communication
	@echo; ./02_demo2_load_imbalance
	@echo; ./03_demo3_communication_dominated
	@echo; $(PYTHON) 04_ilp_scheduling.py
	@echo; ./05_ilp_on_real_cpu
	@echo; $(PYTHON) 06_power_wall.py
	@echo; $(PYTHON) 07_caches_and_locality.py
	@echo; ./08_memory_latency

selftest:
	$(PYTHON) ilp_sched.py
	$(PYTHON) cachesim.py

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