Dovid had 400 children from war‑time rape (yafas to’ar)
Sanhedrin(21a): Dovid had 400 children and all of them were the result of war‑time rape with non‑Jewish women captured in battle (yafas to’ar), and they all had long hair and all of them rode in golden carriages. They led the soldiers and they were the men of power in Dovid’s household.
Aruch LeNer(Sanhedrin 21a): Dovid had 400 children - It appears at first glance to be incomprehensible that from those wives who were yafas to’ar of his 18 wives - he would have 400 children. I saw that Rashi (Kiddushin 76b) was aware of this problem. He wrote that not all were children of Dovid but were rather the children of other Jews. However Tosfos Rid (Kiddushin 21b) quotes one of the major rishonim who says that they were definitely Dovid’s children from the yofas to’ar that Dovid had raped in battle. But he did not take them as wives and thus they were not counted among the 18 wives that were permitted to him.
Rashi(Kiddushin 76b): Dovid had four hundred children – they were children of his soldiers from yofas to’ar but they were not his biological children.
Tosfos Rid(Kiddushin 21b): Those four hundred children [that Sanhedrin (21a) said that Dovid had] they were the result of the permitted first intercourse with their mothers who were raped in battle. However Dovid did not keep them as wives because then he would have had more than the allowed 18 wives.