A method is developed for optimizing the complex thermo-fluid phenomena that occur in welding processes where fluid convection is present. A mathematical model of a typical welding problem which includes conservation of mass, momentum and energy, and assumes that the process is steady in the frame of reference moving with the heat source is considered. An optimal control problem in which the heat input from the heat source is determined to ensure a prescribed geometry of the weld is formulated and solved. The problem is solved with a gradient-based optimization approach in which the gradient (sensitivity) of the cost functional with respect to the control variables is determined using a suitably defined adjoint system. An important aspect of the problem is that it is of the free-boundary type. Therefore it is necessary to use methods of the shape calculus to derive the adjoint equations. A number of computational results which validate our approach and feature qualitatively different flow patterns in problems with different material properties are presented.