S&P 500 caps volatile quarter with gains as chip rally offsets Iran shock