SAO PAULO, Brazil — Brazil for years reveled in its image as a post-racial, left-leaning society. Now Jair Bolsonaro — a far-right outsider who says he “loves” President Trump — has surged to the front of the pack in Sunday’s presidential election, sharply dividing Latin America’s largest nation.

To tackle runaway crime, Bolsonaro says, police should gun down more criminals. “A gay son is the result of a lack of beatings,” he once quipped, and insists that homosexuality should not be discussed in elementary schools.

He once said that women — because they get pregnant — ­deserve less pay than men. He has called some minorities fat and lazy.

Like Trump, he embraces social media to reach legions of loyal followers. His rallies have become outlets for white men rattled by social and economic change. He has vowed to drain the swamp in the capital and make Brazil “great.”

“It’s going to be beautiful,” the front-runner’s 34-year-old son, Eduardo Bolsonaro, said while envisioning his father’s presidency at a rally last week. “It will be just like Trump in the United States.”

As this nation of 208 million goes to the polls Sunday, Brazil is a polarized, angst-filled place. The economy is floundering. Huge swaths of its political class are tainted by corruption. The homicide rate has reached epic highs.

Bolsonaro, 63, has advanced with a Brazil-first campaign that attacks the traditional press while grabbing headlines with tough talk and his own set of alternative facts. His popularity, some say, reflects the globalization of the anti-globalists and the rise of Western candidates who seek to exploit racial and social fault lines.

In Europe and the United States, far-right and populist movements have aimed their anger at immigrants and minorities. In Brazil, the mostly white upper-middle class has felt threatened by the rise of a largely black lower-middle class whose income shot up faster than that of the wealthiest segment of society during more than a decade of leftist Workers’ Party rule starting in 2003. During those years, affirmative-action-like programs sent many black Brazilians to college for the first time.

With the economy languishing, however, all segments of society are hurting, and Bolsonaro’s impassioned speeches are touching a raw nerve. His rallies attract not only ultraconservatives in camouflage pants and T-shirts with skulls but also angry professionals who feel they have lost ground.

“Today, if you are a white, heterosexual man of means, you must be punished,” said Marcio Ferraz, 47, a Sao Paulo doctor who attended a Bolsonaro rally Sunday. “We don’t have a social debt to blacks. We need to be responsible for ourselves.”

Politics of fear

Yet much like Trump in 2016, Bolsonaro is winning support from many voters who are turning to him despite his words on minorities and women, not because of them. His pledge to crack down on crime and political corruption and prevent the return of a leftist government are resounding with millions who see him as the last, best chance for law and order. He has managed to portray himself as an outsider despite his 27 years as a lawmaker in Congress.

Bolsonaro in recent months has sought to tone down his most controversial rhetoric, praising Brazil’s cultural diversity in a tweet Thursday and softening his stance on gender inequality, in what analysts say is an attempt to increase his electability.

“He’s not the savior of the country, but to beat the communists in the Workers’ Party, he is the best option,” said Danilo Monato, a black, 30-year-old ­physical education teacher who attended the recent Bolsonaro rally.

In much of Latin America, polls show, Trump is desperately unpopular. But Bolsonaro and his supporters — who sometimes fly American flags at rallies — view the U.S. president as a political touchstone.

Bolsonaro’s similarities with Trump are “conscious and deliberate,” said Guilherme Casarões, a comparative politics professor at the Getulio Vargas Foundation, a university in Sao Paulo. “Five years ago, he was just another congressman with anti-gay views. Now Bolsonaro, like Trump, has become a larger-than-life figure.”

He continued: “Bolsonaro uses well-crafted rhetoric — his slogan is ‘Brazil before everything, and God above all.’ He has been able to reach out to different groups of voters who feel abandoned by the political class. They are now blind to the negative things he says and does, and tend to overlook any aspect that speaks against their candidate.”

Bolsonaro has embraced the politics of fear. He demonized his opponents on the left as corrupt, inept radicals and his foes on the right as weak centrists unable to “strongly” represent the conservative cause.

Conspiracy theories rule his world: If he loses, it will be only because of a plot to steal the presidency from him, he says.

“I will not accept an election result that is not my own victory,” Bolsonaro said in a television interview last month.

His talk of bringing back family values has been music to the ears of conservative Catholics and evangelicals, even though he is now on his third wife. After an unsuccessful assassination attempt last month — a man stabbed Bolsonaro in the abdomen at a rally — some Brazilians even tweeted Bible verses and proclaimed his survival a divine sign.

Lula's shadow

Like Trump, Bolsonaro was initially underestimated by Brazilian pundits, who laughed off his candidacy. They aren’t laughing now. A former army captain whose running mate is a retired general, Bolsonaro has lavished praise on the 21-year, right-wing military dictatorship that ruled Brazil until 1985. If he wins and finds himself unable to cobble together a majority in Congress, some observers fear he may back military intervention and seize authoritarian powers.

Bolsonaro has rejected such concerns. “If one day the military comes to power, it will be through a vote,” he said at a march in June.

A new poll from respected firm Datafolha released Thursday shows Bolsonaro with 39 percent of the vote, compared with 25 percent for Fernando Haddad, the candidate representing the Workers’ Party. In Brazil’s electoral system, a candidate needs more than 50 percent to win — a figure none of the 13 aspirants in the race is expected to reach Sunday. That would set up an Oct. 28 runoff between the two top finishers, in which Bolsonaro would probably be in a dogfight with Haddad.

Part of Haddad’s problem is his role as a stand-in for former president Luiz Inácio Lula da Silva. Lula, as he is widely known here, was barred from the race after he was sent to prison for 12 years for his involvement in a massive corruption scandal involving construction company bribes.

Haddad has met with investment bankers and is considered more moderate than most members of his party, which has not endeared him to the more militant leftists. Nonetheless, investors fear he won’t be willing to pass crucial reforms to the country’s pension system to avert a financial crisis. Some voters also worry that Haddad — whose slogan is “Lula is Haddad” — will adopt more-radical policies as president if Lula wishes it.

The chances of a Bolsonaro victory, meanwhile, are stoking fears among liberals here and abroad, turning Brazil’s election into a globally watched race. Celebrities including Madonna, Cher and the British actor Stephen Fry have denounced Bolsonaro. In Brazil, social movements against him have sprung up — including one involving hundreds of thousands of tweets under the hashtag #elenao, or ­#NotHim. Last weekend, tens of thousands of women, blacks, gay people and indigenous activists jointed in anti-Bolsonaro street protests.

Many here argue that Bolsonaro’s incendiary rhetoric is emboldening others to use hate speech, bringing racism and homophobia into mainstream dialogue. On Saturday, Cesar Augusto da Silva, 28, a gay black illustrator in Sao Paulo, attended a rally with a sign around his neck that read: “Beware, Bolsonaro kills gays” — a reference to a homophobic chant among Bolsonaro supporters at a soccer game that recently went viral on social media.

“If we stay silent, it will make the discrimination worse,” he said. “I’m here so that one day I can tell my children, I tried.”