From the Super Mario Wiki
The Nightmare Machine (also known as the Dream Machine) is a machine stolen by Wart prior to the events of the non-Mario game, Yume Kojo: Doki Doki Panic and the Mario game, Super Mario Bros. 2.
Yume Kojo: Doki Doki Panic
The Dream Machine from Yume Kojo: Doki Doki Panic
In the Tale of the Dream World of Muu (known as Subcon in the Mario series), the Dream Machine was created by the Muu people to control the weather and sustain good dreams to all the people. Mamu (later renamed Wart) suddenly appeared and converted the Dream Machine to produce several monsters to conquer the land. The Muu people originally managed to defeat Mamu on their own, but when the twins Piki and Poki accidentally ripped out the book's ending, Mamu stopped them in their tracks and kidnapped them. At the final battle, the Dream Machine creates Turnips, which the Arabian Family has to throw four times in Mamu's open mouth in order to defeat him.
Super Mario series
Super Mario Bros. 2
In Super Mario Bros. 2, the Nightmare Machine creates monsters that Wart then uses to increase the numbers of soldiers for the 8 bits and to take control of the land of Subcon and imprison the lands protectors, the Subcon Fairies. During the final battle between Mario and Wart, the Nightmare Machine will shoot out vegetables, which are the only way to defeat Wart.
The Nightmare Machine in Super Mario Bros. 2
BS Super Mario USA
The Nightmare Machine made its return in the pseudo-sequel, BS Super Mario USA. It only makes an appearance in Wart's secret room in a Vase from Subspace that is almost identical to that of the Subcon Castle's final room. The Nightmare Machine is used for the same purpose it had in the first game.