The Fallen's war on the sun frames everything that follows, so the film opens in the distant past. Seven Primes once harvested suns for energy, but one of them broke their rule and tried to destroy Earth's sun, and he became the Fallen. In the present, NEST keeps hunting Decepticons, and a captured prisoner warns that the Fallen will return.
The middle of the film is a run of captures and escapes. The AllSpark shard puts alien symbols into Sam's head, and the Decepticons hunt him for what those symbols hold: the location of a lost Matrix of Leadership. Megatron is revived, and the Fallen orders him to kill Optimus Prime and take Sam alive. Sam and his friends are seized, then pulled out by the Autobots, but Optimus dies shielding Sam while Decepticon strikes hit cities around the world.
With Optimus gone, Sam, Mikaela, Leo, Simmons and two small robots go looking for the ancient Autobot Jetfire. He teleports the group to Egypt, where the Matrix lies in a desert tomb. It crumbles to dust the moment Sam grabs it, although Sam still carries it with him.
The finale plays out by the Giza pyramids, where the Fallen's forces hit the Autobots and NEST while a giant machine hidden there is aimed at the sun. Sam is killed in the fighting. In an otherworldly place, the old Primes tell him he can still bring back Optimus. Sam returns to life and uses the Matrix to revive Optimus, and Jetfire gives up his own body to join with him, giving Optimus new power and flight. Optimus destroys the machine and kills the Fallen, while Megatron and Starscream flee.