It is the bodies way of keeping the blood flow and the spongy tissue in the penis functioning properly. This is necessary so that there is not a lessening of proper function. Actually, it happens a few times throughout the night. It happens during REM sleep, when the guy dreams. The subject of the dream is of no importance. It could be sexual or it could be scary, at least according to the articles that I have read.
whytry has given an excellent explanation. I just wanted to add that if men lose these AM erections, it's usually a tell tale sign of some problem....Usually low T, otherwise known as testosterone. Morning erections are typically the indicator as to whether or not things are "functioning."