Thermodynamic analysis of anion exchange during heteroepitaxy