Topology optimization is a powerful tool for designing structures in many fields but has been limited to static or passively moving objects made of hard materials. Designing soft and actively moving objects, such as soft robots equipped with actuators, is challenging because simulating dynamics problems is difficult and the optimal structure depends on how the object will move. We propose "4D topology optimization," which extends density-based topology optimization to include time, for simultaneously optimizing the structure and movement of self-actuating soft bodies. The method uses hierarchized and multi-indexed density variables distributed over the spatiotemporal design domain to represent the material layout, actuator layout, and time-varying actuation, thus allowing for simultaneous optimization of structure and movement with gradient-based methods. Forward and backward simulations of soft bodies are done using the material point method, a Lagrangian-Eulerian hybrid approach, implemented on a recent automatic differentiation framework. We present several numerical examples of self-actuating soft body designs targeted at performing locomotion, posture control, and rotation tasks. The results demonstrate that our method can successfully design soft bodies with complex structures and biomimetic movements because of its high degree of design freedom.