Thiem, the 2018 Roland Garros runner-up and victor of the Barcelona title last month, prevailed in two hours 10 minutes against Federer having saved two match points in a 15-minute second set tie-break.
Federer had started strongly, breaking Thiem in the second game of the match.
The Frenchman continued to have the upper hand in the third jumping out to a 4-1 lead until Federer roared back. I'm very, very happy to win. It's in this kind of match that I need to play my best.
Djokovic will next face Marin Cilic, who came from behind to beat Laslo Djere 4-6, 6-3, 6-2.
The Spaniard outclassed Stan Wawrinka last night, easing to a straight set victory without facing a single break point, and only losing three games in the process.
On the women's side, Simona Halep made it back to the Madrid final for the first time since 2017 with a 6-2, 6-7 (2), 6-0 win over unseeded Belinda Bencic.
Federer spurned two match points and Thiem only clinched the set on his sixth set point as he won the breaker 13-11 to force a decider.
"I don't want to think about that".
But this proved to be a false dawn as Thiem broke again in the next game and he served it out to clinch an epic victory. "As I said yesterday, he already won against Basilashvili and Kohlschreiber, so he came to this match with good confidence and winning against two great players on clay".
Thiem has won the last two matches he played against Djokovic, who got the day off because of Cilic's withdrawal.
Federer bageled Monfils 6-0 in the first set, lost his momentum in the second, and looked like he was down and nearly out in the third.
"I'll probably only decide on the weekend, but I'm not sure if I'm going to go". "I went back on the court, trained for another hour and got a good sweat in".
Federer, who earned his 20th win of the season, skipped the clay swing the last two years to remain fit for the rest of the season.
"I felt my chances were bigger at the net than from the baseline, so it was a desperation, panic move", Federer said.