Place beans into a large saucepan, and add water to cover. Add onions, garlic, salt and pepper. Bring to a boil, then simmer over medium-low heat until beans are tender, about 1 to 2 hours. Add additional water to the pan as needed to prevent burning.
Mash the beans with a potato masher, and mix in the butter. Continue cooking, stirring occasionally, until the mixture is thickened and the butter is absorbed. Adjust seasonings to taste.
Preheat oven to 350 degrees F (175 degrees C). Spread the bean mixture into a 9×13 inch baking dish, and sprinkle shredded cheese over the top. Bake for 15 minutes, or until cheese is melted.