# =============================================================================
# Makefile for Stanford CS149 Lecture 15 demos (memory consistency, locks)
# =============================================================================
#
# [What this builds]
#   02_litmus_hw     litmus tests (SB, MP, LB) on real cores
#   03_data_race     a racy flag hand-off and counter, and their fixes
#   03_data_race_tsan  the same source built with ThreadSanitizer
#   04_spinlocks     TAS, CAS, LL/SC, TTAS, ticket and std::mutex under contention
#   Demos 01 and 05 are Python (standard library only); 05 imports
#   ../lecture14/coherence.py.
#
# [How to use]
#   make            # build
#   make run        # run all demos in lecture order (~15 s)
#   make selftest   # self-check of memmodel.py
#   make clean
# -----------------------------------------------------------------------------

CXX      ?= c++
CXXFLAGS := -std=c++20 -O2 -g -Wall -Wextra -pthread
PYTHON   ?= python3
HEADERS  := ../lecture01/cs149_timer.h ../lecture01/machine_info.h
BINS     := 02_litmus_hw 03_data_race 04_spinlocks

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

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

# ThreadSanitizer: -O1 keeps the report readable; TSAN_BUILD skips the parts
# that are only meaningful without instrumentation
03_data_race_tsan: 03_data_race.cpp
	$(CXX) -std=c++20 -O1 -g -Wall -Wextra -pthread -fsanitize=thread -DTSAN_BUILD -o $@ $<

run: all
	@echo; $(PYTHON) 01_litmus_models.py
	@echo; ./02_litmus_hw
	@echo; ./03_data_race
	@echo; echo "[TSan] ThreadSanitizer on the same program (report lines only):"
	@TSAN_OPTIONS=exitcode=0 ./03_data_race_tsan 2>&1 | grep -E "WARNING: ThreadSanitizer|of size|Location is|SUMMARY|reported" | sed -e 's/ (03_data_race_tsan.*//' -e 's/ in void\*.*//' | uniq || true
	@echo; ./04_spinlocks
	@echo; $(PYTHON) 05_lock_traffic.py

selftest:
	$(PYTHON) memmodel.py

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