Module with a Target-incompatible DataLayout attached

My code to generate an object file, migrated from 3.3 to 3.8, is
producing the error:

    leaf: /opt/llvm/lib/CodeGen/MachineFunction.cpp:108:
llvm::MachineFunction::MachineFunction(const llvm::Function*, const
llvm::TargetMachine&, unsigned int, llvm::MachineModuleInfo&): Assertion
`TM.isCompatibleDataLayout(getDataLayout()) && "Can't create a
MachineFunction using a Module with a " "Target-incompatible DataLayout
attached\n"' failed.

I looked at my code and noticed I had a line commented out since it
didn't work in 3.8, but I'm guessing may be the source of the issue:

    llvm::legacy::PassManager fpm;
    //MIGRATE: fpm.add( new llvm::DataLayout( *data_layout ) );
    bool ret = machine->addPassesToEmitFile( fpm, out.os(),
llvm::TargetMachine::CGFT_ObjectFile );
    STATE_CHECK( !ret );
    fpm.run( *module );

Where `data_layout` was created as:

    data_layout.reset( new llvm::DataLayout( module ) );

What do I have to do to avoid the error message? Note that I'm not
trying to get a different data layout, at the moment I just want the
default data layout for the system.

If helpful, here is more context to the object generation code:

    std::string triple_name = llvm::sys::getDefaultTargetTriple();
    llvm::Triple triple(llvm::Triple::normalize(triple_name));
    llvm::Target const * target = llvm::TargetRegistry::lookupTarget(
"x86-64", triple, err_str );
    STATE_CHECK( target, err_str );
   
    llvm::TargetOptions topts;
    llvm::TargetMachine * machine = target->createTargetMachine(
triple.getTriple(),
        "" /*cpu*/, "" /*featurestr*/, topts,
        gopts.pic ? llvm::Reloc::PIC_ : llvm::Reloc::Default,
        llvm::CodeModel::Default,
        llvm::CodeGenOpt::Default );
   
    llvm::tool_output_file out( (base_path + ".o").c_str(),
llvm::sys::fs::OpenFlags::F_None );
   
    llvm::legacy::PassManager fpm;
    //MIGRATE: fpm.add( new llvm::DataLayout( *data_layout ) );
    bool ret = machine->addPassesToEmitFile( fpm, out.os(),
llvm::TargetMachine::CGFT_ObjectFile );
    STATE_CHECK( !ret );
    fpm.run( *module );
   
    out.keep();

The data layout needs to be set on the module directly, you can create one from the TargetMachine.