Expansion dynamics and marginal climates drive adaptation across geographic ranges