diff --git a/include/clang/CodeGen/BackendUtil.h b/include/clang/CodeGen/BackendUtil.h
index b9f352c..3a31e5b 100644
--- a/include/clang/CodeGen/BackendUtil.h
+++ b/include/clang/CodeGen/BackendUtil.h
@@ -14,6 +14,7 @@
 
 namespace llvm {
   class Module;
+  class TargetMachine;
 }
 
 namespace clang {
@@ -31,10 +32,24 @@ namespace clang {
     Backend_EmitObj        ///< Emit native object files
   };
 
-  void EmitBackendOutput(DiagnosticsEngine &Diags, const CodeGenOptions &CGOpts,
-                         const TargetOptions &TOpts, const LangOptions &LOpts,
-                         llvm::Module *M,
-                         BackendAction Action, raw_ostream *OS);
+  /// Generates the TargetMachine.
+  /// Returns Null if it is unable to create the target machine.
+  /// Some of our clang tests specify triples which are not built
+  /// into clang. This is okay because these tests check the generated
+  /// IR, and they require DataLayout which depends on the triple.
+  /// In this case, we allow this method to fail and not report an error.
+  /// When the action is one that requires llvm's CodeGen, we print an error
+  /// if we are unable to load the requested target.
+  llvm::TargetMachine *
+  CreateTargetMachine(DiagnosticsEngine &Diags, StringRef Triple,
+                      const CodeGenOptions &CodeGenOpts,
+                      const clang::TargetOptions &TargetOpts,
+                      const LangOptions &LangOpts, BackendAction Action);
+
+  void EmitBackendOutput(llvm::TargetMachine *TM, DiagnosticsEngine &Diags,
+                         const CodeGenOptions &CGOpts, const LangOptions &LOpts,
+                         llvm::Module *M, BackendAction Action,
+                         raw_ostream *OS);
 }
 
 #endif
diff --git a/include/clang/CodeGen/ModuleBuilder.h b/include/clang/CodeGen/ModuleBuilder.h
index cda7863..fb21833 100644
--- a/include/clang/CodeGen/ModuleBuilder.h
+++ b/include/clang/CodeGen/ModuleBuilder.h
@@ -15,6 +15,7 @@
 #define LLVM_CLANG_CODEGEN_MODULEBUILDER_H
 
 #include "clang/AST/ASTConsumer.h"
+#include "clang/CodeGen/BackendUtil.h"
 #include <string>
 
 namespace llvm {
@@ -33,6 +34,7 @@ namespace clang {
   public:
     virtual llvm::Module* GetModule() = 0;
     virtual llvm::Module* ReleaseModule() = 0;
+    virtual llvm::TargetMachine *getTargetMachine() = 0;
   };
 
   /// CreateLLVMCodeGen - Create a CodeGenerator instance.
@@ -42,6 +44,8 @@ namespace clang {
                                    const std::string &ModuleName,
                                    const CodeGenOptions &CGO,
                                    const TargetOptions &TO,
+                                   const LangOptions &LO,
+                                   BackendAction Action,
                                    llvm::LLVMContext& C);
 }
 
diff --git a/lib/CodeGen/BackendUtil.cpp b/lib/CodeGen/BackendUtil.cpp
index 90b0f68..b4fc0cd 100644
--- a/lib/CodeGen/BackendUtil.cpp
+++ b/lib/CodeGen/BackendUtil.cpp
@@ -44,7 +44,6 @@ namespace {
 class EmitAssemblyHelper {
   DiagnosticsEngine &Diags;
   const CodeGenOptions &CodeGenOpts;
-  const clang::TargetOptions &TargetOpts;
   const LangOptions &LangOpts;
   Module *TheModule;
 
@@ -88,16 +87,6 @@ private:
 
   void CreatePasses(TargetMachine *TM);
 
-  /// CreateTargetMachine - Generates the TargetMachine.
-  /// Returns Null if it is unable to create the target machine.
-  /// Some of our clang tests specify triples which are not built
-  /// into clang. This is okay because these tests check the generated
-  /// IR, and they require DataLayout which depends on the triple.
-  /// In this case, we allow this method to fail and not report an error.
-  /// When MustCreateTM is used, we print an error if we are unable to load
-  /// the requested target.
-  TargetMachine *CreateTargetMachine(bool MustCreateTM);
-
   /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
   ///
   /// \return True on success.
@@ -107,10 +96,9 @@ private:
 public:
   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
                      const CodeGenOptions &CGOpts,
-                     const clang::TargetOptions &TOpts,
                      const LangOptions &LOpts,
                      Module *M)
-    : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
+    : Diags(_Diags), CodeGenOpts(CGOpts), LangOpts(LOpts),
       TheModule(M), CodeGenerationTime("Code Generation Time"),
       CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
 
@@ -120,7 +108,7 @@ public:
     delete PerFunctionPasses;
   }
 
-  void EmitAssembly(BackendAction Action, raw_ostream *OS);
+  void EmitAssembly(TargetMachine *TM, BackendAction Action, raw_ostream *OS);
 };
 
 // We need this wrapper to access LangOpts and CGOpts from extension functions
@@ -352,10 +340,15 @@ void EmitAssemblyHelper::CreatePasses(TargetMachine *TM) {
   PMBuilder.populateModulePassManager(*MPM);
 }
 
-TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
+TargetMachine *
+clang::CreateTargetMachine(DiagnosticsEngine &Diags, StringRef Triple,
+                           const CodeGenOptions &CodeGenOpts,
+                           const clang::TargetOptions &TargetOpts,
+                           const LangOptions &LangOpts, BackendAction Action) {
   // Create the TargetMachine for generating code.
+  bool MustCreateTM = Action != Backend_EmitNothing &&
+                      Action != Backend_EmitBC && Action != Backend_EmitLL;
   std::string Error;
-  std::string Triple = TheModule->getTargetTriple();
   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
   if (!TheTarget) {
     if (MustCreateTM)
@@ -545,16 +538,10 @@ bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
   return true;
 }
 
-void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
+void EmitAssemblyHelper::EmitAssembly(TargetMachine *TM, BackendAction Action,
+                                      raw_ostream *OS) {
   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
   llvm::formatted_raw_ostream FormattedOS;
-
-  bool UsesCodeGen = (Action != Backend_EmitNothing &&
-                      Action != Backend_EmitBC &&
-                      Action != Backend_EmitLL);
-  TargetMachine *TM = CreateTargetMachine(UsesCodeGen);
-  if (UsesCodeGen && !TM) return;
-  llvm::OwningPtr<TargetMachine> TMOwner(CodeGenOpts.DisableFree ? 0 : TM);
   CreatePasses(TM);
 
   switch (Action) {
@@ -571,6 +558,8 @@ void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
     break;
 
   default:
+    if (!TM)
+      return;
     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
     if (!AddEmitPasses(Action, FormattedOS, TM))
       return;
@@ -604,13 +593,13 @@ void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
   }
 }
 
-void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
+void clang::EmitBackendOutput(TargetMachine *TM,
+                              DiagnosticsEngine &Diags,
                               const CodeGenOptions &CGOpts,
-                              const clang::TargetOptions &TOpts,
                               const LangOptions &LOpts,
                               Module *M,
                               BackendAction Action, raw_ostream *OS) {
-  EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
+  EmitAssemblyHelper AsmHelper(Diags, CGOpts, LOpts, M);
 
-  AsmHelper.EmitAssembly(Action, OS);
+  AsmHelper.EmitAssembly(TM, Action, OS);
 }
diff --git a/lib/CodeGen/CodeGenAction.cpp b/lib/CodeGen/CodeGenAction.cpp
index 047dc53..deec257 100644
--- a/lib/CodeGen/CodeGenAction.cpp
+++ b/lib/CodeGen/CodeGenAction.cpp
@@ -29,6 +29,7 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/Timer.h"
+#include "llvm/Target/TargetMachine.h"
 using namespace clang;
 using namespace llvm;
 
@@ -38,7 +39,6 @@ namespace clang {
     DiagnosticsEngine &Diags;
     BackendAction Action;
     const CodeGenOptions &CodeGenOpts;
-    const TargetOptions &TargetOpts;
     const LangOptions &LangOpts;
     raw_ostream *AsmOutStream;
     ASTContext *Context;
@@ -57,9 +57,10 @@ namespace clang {
                     const std::string &infile, llvm::Module *LinkModule,
                     raw_ostream *OS, LLVMContext &C)
         : Diags(_Diags), Action(action), CodeGenOpts(compopts),
-          TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
-          Context(), LLVMIRGeneration("LLVM IR Generation Time"),
-          Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
+          LangOpts(langopts), AsmOutStream(OS), Context(),
+          LLVMIRGeneration("LLVM IR Generation Time"),
+          Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, langopts,
+                                action, C)),
           LinkModule(LinkModule) {
       llvm::TimePassesIsEnabled = TimePasses;
     }
@@ -149,7 +150,7 @@ namespace clang {
       void *OldContext = Ctx.getInlineAsmDiagnosticContext();
       Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
 
-      EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
+      EmitBackendOutput(Gen->getTargetMachine(), Diags, CodeGenOpts, LangOpts,
                         TheModule.get(), Action, AsmOutStream);
 
       Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
@@ -420,10 +421,17 @@ void CodeGenAction::ExecuteAction() {
       return;
     }
 
-    EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
-                      CI.getTargetOpts(), CI.getLangOpts(),
-                      TheModule.get(),
-                      BA, OS);
+    const std::string &Triple = TheModule->getTargetTriple();
+    const CodeGenOptions &CodeGenOpts = CI.getCodeGenOpts();
+    const TargetOptions &TargetOpts = CI.getTargetOpts();
+    const LangOptions &LangOpts = CI.getLangOpts();
+    DiagnosticsEngine &Diags = CI.getDiagnostics();
+    TargetMachine *TM = CreateTargetMachine(Diags, Triple, CodeGenOpts,
+                                            TargetOpts, LangOpts, BA);
+    llvm::OwningPtr<TargetMachine> TMOwner(CodeGenOpts.DisableFree ? 0 : TM);
+
+    EmitBackendOutput(TM, Diags, CodeGenOpts, LangOpts, TheModule.get(), BA,
+                      OS);
     return;
   }
 
diff --git a/lib/CodeGen/ModuleBuilder.cpp b/lib/CodeGen/ModuleBuilder.cpp
index 6b81ce7..ec98e4b 100644
--- a/lib/CodeGen/ModuleBuilder.cpp
+++ b/lib/CodeGen/ModuleBuilder.cpp
@@ -19,12 +19,14 @@
 #include "clang/AST/Expr.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/CodeGen/BackendUtil.h"
 #include "clang/Frontend/CodeGenOptions.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
+#include "llvm/Target/TargetMachine.h"
 using namespace clang;
 
 namespace {
@@ -33,16 +35,26 @@ namespace {
     OwningPtr<const llvm::DataLayout> TD;
     ASTContext *Ctx;
     const CodeGenOptions CodeGenOpts;  // Intentionally copied in.
-  protected:
+    const TargetOptions &TargetOpts;
+    const LangOptions &LangOpts;
     OwningPtr<llvm::Module> M;
     OwningPtr<CodeGen::CodeGenModule> Builder;
+    OwningPtr<llvm::TargetMachine> TM;
+    BackendAction Action;
   public:
-    CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string& ModuleName,
-                      const CodeGenOptions &CGO, llvm::LLVMContext& C)
-      : Diags(diags), CodeGenOpts(CGO),
-        M(new llvm::Module(ModuleName, C)) {}
-
-    virtual ~CodeGeneratorImpl() {}
+    CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
+                      const CodeGenOptions &CGO,
+                      const TargetOptions &TargetOpts,
+                      const LangOptions &LangOpts, BackendAction Action,
+                      llvm::LLVMContext &C)
+        : Diags(diags), CodeGenOpts(CGO), TargetOpts(TargetOpts),
+          LangOpts(LangOpts), M(new llvm::Module(ModuleName, C)),
+          Action(Action) {}
+
+    virtual ~CodeGeneratorImpl() {
+      if (CodeGenOpts.DisableFree)
+        TM.take();
+    }
 
     virtual llvm::Module* GetModule() {
       return M.get();
@@ -52,13 +64,31 @@ namespace {
       return M.take();
     }
 
+    virtual llvm::TargetMachine *getTargetMachine() LLVM_OVERRIDE;
+
     virtual void Initialize(ASTContext &Context) {
       Ctx = &Context;
 
-      M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
-      M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
-      TD.reset(new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
-      Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *TD,
+      const TargetInfo &TI = Ctx->getTargetInfo();
+      const std::string &Triple = TI.getTriple().getTriple();
+      M->setTargetTriple(Triple);
+
+      llvm::TargetMachine *T = CreateTargetMachine(
+          Diags, Triple, CodeGenOpts, TargetOpts, LangOpts, Action);
+      std::string DLSpec;
+      const llvm::DataLayout *DL;
+      if (T) {
+        TM.reset(T);
+        DL = T->getDataLayout();
+        DLSpec = DL->getStringRepresentation();
+        assert(DLSpec == TI.getTargetDescription());
+      } else {
+        DLSpec = TI.getTargetDescription();
+        DL = new llvm::DataLayout(DLSpec);
+        TD.reset(DL);
+      }
+      M->setDataLayout(DLSpec);
+      Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *DL,
                                                Diags));
 
       for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
@@ -154,6 +184,10 @@ namespace {
       Builder->AddDependentLib(Lib);
     }
   };
+
+  llvm::TargetMachine *CodeGeneratorImpl::getTargetMachine() {
+    return TM.get();
+  }
 }
 
 void CodeGenerator::anchor() { }
@@ -161,7 +195,9 @@ void CodeGenerator::anchor() { }
 CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
                                         const std::string& ModuleName,
                                         const CodeGenOptions &CGO,
-                                        const TargetOptions &/*TO*/,
+                                        const TargetOptions &TO,
+                                        const LangOptions &LO,
+                                        BackendAction Action,
                                         llvm::LLVMContext& C) {
-  return new CodeGeneratorImpl(Diags, ModuleName, CGO, C);
+  return new CodeGeneratorImpl(Diags, ModuleName, CGO, TO, LO, Action, C);
 }
