Pearl formation in mollusks is actually a sort of defense mechanism. Pearls are formed when a bit of sand, grit, or any foreign object makes its way between a mollusk’s mantle and shell. The clam recognizes the object as an irritant and coats it in layers of nacre (what the inside, pearlescent part of clam shells are made out of), making a larger, but less rough and prettier version of the intrusive object.
The round pearls you see used in jewelry are cultured by humans inserting small, perfectly round objects into a certain species of freshwater oysters to make them produce perfectly spheroid pearls. It’s essentially an art of perpetually annoying the oysters to have them produce beautiful things.