A Fary-Milnor theorem for CAT(0) spaces