These $f$ are exactly those non-negative functions on the real line which are entire (=represented by their Taylor series on the whole real line). For example, $f(x)=(\arctan x)^2$ is not in your class since the Taylor series at $0$ has finite radius of convergence. Neither $f(x)=e^{-1/x^2}$ is
in your class since the Taylor series at zero does not converge to the function).

Proof. Suppose that $g$ is an entire function.
Define $g^*(z)=\overline{g(\overline{z})}$ which is also entire. Then
on the real line $f(z)=|g(z)|^2=g(z)g^*(z)$, so your function $f(x)$ is non-negative on the real line and entire (as a product of entire functions).

Conversely. Let $f$ be an entire function which is non-negative on the real line.
Then all real roots are of even multiplicities, and the rest are symmetric with respect to the real line. Let $X$ be the divisor in the plane which consists of those roots which lie in
the open upper half-plane with their multiplicities,
and real roots with half of their
multiplicities. We have the Weierstrass factorization $f=P e^h$
where $P$ is the canonical product, and $h$ is entire, both $P$ and $h$ real on the real line. Let $P_1$ be the canonical product over $X$,
then $P=P_1P_1^*$, and set $g=P_1e^{h/2}$. Then on the real line
$$|g(x)|^2=|P_1(x)|^2|e^{h(x)}|=P(x)e^{h(x)}=f(x).$$

Remark. If $f$ has infinitely many non-real zeros, then there are infinitely many different $g$'s which give such a representation: the zeros can be split between $P_1$ and $P_1^*$ in many ways: if $Y$ is the divisor of zeros of $f$, then any $X$ such that $Y=X+\overline{X}$ will do the job.

Remark 2. How to determine that a function of a real variable is in fact entire. A criterion is that $|f^{(n)}(x)|^{1/n}/n\to 0$ uniformly on compact subsets of the real line.
This follows from the Taylor formula with remainder combined with Stirling's formula.