This paper is devoted to a deeper understanding of the heat flow and to the refinement of calculus tools on metric measure spaces (X, d, m). Our main results are: \cdot A general study of the relations between the Hopf-Lax semigroup and Hamilton-Jacobi equation in metric spaces (X, d). \cdot The equivalence of the heat flow in L2(X,m) generated by a suitable Dirichlet energy and the Wasserstein gradient flow of the relative entropy functional Entm in the space of probability measures P(X). \cdot The proof of density in energy of Lipschitz functions in the Sobolev space W^{1,2}(X,d,m) under the only assumption that m is locally finite. \cdot A fine and very general analysis of the differentiability properties of a large class of Kantorovich potentials, in connection with the optimal transport problem. Our results apply in particular to spaces satisfying Ricci curvature bounds in the sense of Lott & Villani [28] and Sturm [35, 36] and require neither the doubling property nor the validity of the local Poincar\'e inequality.