1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/MC/SubtargetFeature.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FormattedStream.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Transforms/IPO.h"
35 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
36 #include "llvm/Transforms/Instrumentation.h"
37 #include "llvm/Transforms/ObjCARC.h"
38 #include "llvm/Transforms/Scalar.h"
39 using namespace clang;
40 using namespace llvm;
41 
42 namespace {
43 
44 class EmitAssemblyHelper {
45   DiagnosticsEngine &Diags;
46   const CodeGenOptions &CodeGenOpts;
47   const clang::TargetOptions &TargetOpts;
48   const LangOptions &LangOpts;
49   Module *TheModule;
50 
51   Timer CodeGenerationTime;
52 
53   mutable PassManager *CodeGenPasses;
54   mutable PassManager *PerModulePasses;
55   mutable FunctionPassManager *PerFunctionPasses;
56 
57 private:
58   PassManager *getCodeGenPasses(TargetMachine *TM) const {
59     if (!CodeGenPasses) {
60       CodeGenPasses = new PassManager();
61       CodeGenPasses->add(new DataLayout(TheModule));
62       if (TM)
63         TM->addAnalysisPasses(*CodeGenPasses);
64     }
65     return CodeGenPasses;
66   }
67 
68   PassManager *getPerModulePasses(TargetMachine *TM) const {
69     if (!PerModulePasses) {
70       PerModulePasses = new PassManager();
71       PerModulePasses->add(new DataLayout(TheModule));
72       if (TM)
73         TM->addAnalysisPasses(*PerModulePasses);
74     }
75     return PerModulePasses;
76   }
77 
78   FunctionPassManager *getPerFunctionPasses(TargetMachine *TM) const {
79     if (!PerFunctionPasses) {
80       PerFunctionPasses = new FunctionPassManager(TheModule);
81       PerFunctionPasses->add(new DataLayout(TheModule));
82       if (TM)
83         TM->addAnalysisPasses(*PerFunctionPasses);
84     }
85     return PerFunctionPasses;
86   }
87 
88 
89   void CreatePasses(TargetMachine *TM);
90 
91   /// CreateTargetMachine - Generates the TargetMachine.
92   /// Returns Null if it is unable to create the target machine.
93   /// Some of our clang tests specify triples which are not built
94   /// into clang. This is okay because these tests check the generated
95   /// IR, and they require DataLayout which depends on the triple.
96   /// In this case, we allow this method to fail and not report an error.
97   /// When MustCreateTM is used, we print an error if we are unable to load
98   /// the requested target.
99   TargetMachine *CreateTargetMachine(bool MustCreateTM);
100 
101   /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
102   ///
103   /// \return True on success.
104   bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS,
105                      TargetMachine *TM);
106 
107 public:
108   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
109                      const CodeGenOptions &CGOpts,
110                      const clang::TargetOptions &TOpts,
111                      const LangOptions &LOpts,
112                      Module *M)
113     : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
114       TheModule(M), CodeGenerationTime("Code Generation Time"),
115       CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
116 
117   ~EmitAssemblyHelper() {
118     delete CodeGenPasses;
119     delete PerModulePasses;
120     delete PerFunctionPasses;
121   }
122 
123   void EmitAssembly(BackendAction Action, raw_ostream *OS);
124 };
125 
126 // We need this wrapper to access LangOpts and CGOpts from extension functions
127 // that we add to the PassManagerBuilder.
128 class PassManagerBuilderWrapper : public PassManagerBuilder {
129 public:
130   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
131                             const LangOptions &LangOpts)
132       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
133   const CodeGenOptions &getCGOpts() const { return CGOpts; }
134   const LangOptions &getLangOpts() const { return LangOpts; }
135 private:
136   const CodeGenOptions &CGOpts;
137   const LangOptions &LangOpts;
138 };
139 
140 }
141 
142 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
143   if (Builder.OptLevel > 0)
144     PM.add(createObjCARCAPElimPass());
145 }
146 
147 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148   if (Builder.OptLevel > 0)
149     PM.add(createObjCARCExpandPass());
150 }
151 
152 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153   if (Builder.OptLevel > 0)
154     PM.add(createObjCARCOptPass());
155 }
156 
157 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
158                                     PassManagerBase &PM) {
159   PM.add(createBoundsCheckingPass());
160 }
161 
162 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
163                                       PassManagerBase &PM) {
164   const PassManagerBuilderWrapper &BuilderWrapper =
165       static_cast<const PassManagerBuilderWrapper&>(Builder);
166   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
167   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
168   PM.add(createAddressSanitizerFunctionPass(
169       LangOpts.Sanitize.InitOrder,
170       LangOpts.Sanitize.UseAfterReturn,
171       LangOpts.Sanitize.UseAfterScope,
172       CGOpts.SanitizerBlacklistFile,
173       CGOpts.SanitizeAddressZeroBaseShadow));
174   PM.add(createAddressSanitizerModulePass(
175       LangOpts.Sanitize.InitOrder,
176       CGOpts.SanitizerBlacklistFile,
177       CGOpts.SanitizeAddressZeroBaseShadow));
178 }
179 
180 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
181                                    PassManagerBase &PM) {
182   const PassManagerBuilderWrapper &BuilderWrapper =
183       static_cast<const PassManagerBuilderWrapper&>(Builder);
184   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
185   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins,
186                                    CGOpts.SanitizerBlacklistFile));
187 
188   // MemorySanitizer inserts complex instrumentation that mostly follows
189   // the logic of the original code, but operates on "shadow" values.
190   // It can benefit from re-running some general purpose optimization passes.
191   if (Builder.OptLevel > 0) {
192     PM.add(createEarlyCSEPass());
193     PM.add(createReassociatePass());
194     PM.add(createLICMPass());
195     PM.add(createGVNPass());
196     PM.add(createInstructionCombiningPass());
197     PM.add(createDeadStoreEliminationPass());
198   }
199 }
200 
201 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
202                                    PassManagerBase &PM) {
203   const PassManagerBuilderWrapper &BuilderWrapper =
204       static_cast<const PassManagerBuilderWrapper&>(Builder);
205   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
206   PM.add(createThreadSanitizerPass(CGOpts.SanitizerBlacklistFile));
207 }
208 
209 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
210                                      PassManagerBase &PM) {
211   const PassManagerBuilderWrapper &BuilderWrapper =
212       static_cast<const PassManagerBuilderWrapper&>(Builder);
213   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
214   PM.add(createDataFlowSanitizerPass(CGOpts.SanitizerBlacklistFile));
215 }
216 
217 void EmitAssemblyHelper::CreatePasses(TargetMachine *TM) {
218   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
219   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
220 
221   // Handle disabling of LLVM optimization, where we want to preserve the
222   // internal module before any optimization.
223   if (CodeGenOpts.DisableLLVMOpts) {
224     OptLevel = 0;
225     Inlining = CodeGenOpts.NoInlining;
226   }
227 
228   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
229   PMBuilder.OptLevel = OptLevel;
230   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
231   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
232   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
233   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
234 
235   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
236   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
237 
238   // In ObjC ARC mode, add the main ARC optimization passes.
239   if (LangOpts.ObjCAutoRefCount) {
240     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
241                            addObjCARCExpandPass);
242     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
243                            addObjCARCAPElimPass);
244     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
245                            addObjCARCOptPass);
246   }
247 
248   if (LangOpts.Sanitize.LocalBounds) {
249     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
250                            addBoundsCheckingPass);
251     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
252                            addBoundsCheckingPass);
253   }
254 
255   if (LangOpts.Sanitize.Address) {
256     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
257                            addAddressSanitizerPasses);
258     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
259                            addAddressSanitizerPasses);
260   }
261 
262   if (LangOpts.Sanitize.Memory) {
263     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
264                            addMemorySanitizerPass);
265     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
266                            addMemorySanitizerPass);
267   }
268 
269   if (LangOpts.Sanitize.Thread) {
270     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
271                            addThreadSanitizerPass);
272     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
273                            addThreadSanitizerPass);
274   }
275 
276   if (LangOpts.Sanitize.DataFlow) {
277     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
278                            addDataFlowSanitizerPass);
279     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
280                            addDataFlowSanitizerPass);
281   }
282 
283   // Figure out TargetLibraryInfo.
284   Triple TargetTriple(TheModule->getTargetTriple());
285   PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
286   if (!CodeGenOpts.SimplifyLibCalls)
287     PMBuilder.LibraryInfo->disableAllFunctions();
288 
289   switch (Inlining) {
290   case CodeGenOptions::NoInlining: break;
291   case CodeGenOptions::NormalInlining: {
292     // FIXME: Derive these constants in a principled fashion.
293     unsigned Threshold = 225;
294     if (CodeGenOpts.OptimizeSize == 1)      // -Os
295       Threshold = 75;
296     else if (CodeGenOpts.OptimizeSize == 2) // -Oz
297       Threshold = 25;
298     else if (OptLevel > 2)
299       Threshold = 275;
300     PMBuilder.Inliner = createFunctionInliningPass(Threshold);
301     break;
302   }
303   case CodeGenOptions::OnlyAlwaysInlining:
304     // Respect always_inline.
305     if (OptLevel == 0)
306       // Do not insert lifetime intrinsics at -O0.
307       PMBuilder.Inliner = createAlwaysInlinerPass(false);
308     else
309       PMBuilder.Inliner = createAlwaysInlinerPass();
310     break;
311   }
312 
313   // Set up the per-function pass manager.
314   FunctionPassManager *FPM = getPerFunctionPasses(TM);
315   if (CodeGenOpts.VerifyModule)
316     FPM->add(createVerifierPass());
317   PMBuilder.populateFunctionPassManager(*FPM);
318 
319   // Set up the per-module pass manager.
320   PassManager *MPM = getPerModulePasses(TM);
321 
322   if (!CodeGenOpts.DisableGCov &&
323       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
324     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
325     // LLVM's -default-gcov-version flag is set to something invalid.
326     GCOVOptions Options;
327     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
328     Options.EmitData = CodeGenOpts.EmitGcovArcs;
329     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
330     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
331     Options.NoRedZone = CodeGenOpts.DisableRedZone;
332     Options.FunctionNamesInData =
333         !CodeGenOpts.CoverageNoFunctionNamesInData;
334     MPM->add(createGCOVProfilerPass(Options));
335     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
336       MPM->add(createStripSymbolsPass(true));
337   }
338 
339   PMBuilder.populateModulePassManager(*MPM);
340 }
341 
342 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
343   // Create the TargetMachine for generating code.
344   std::string Error;
345   std::string Triple = TheModule->getTargetTriple();
346   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
347   if (!TheTarget) {
348     if (MustCreateTM)
349       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
350     return 0;
351   }
352 
353   // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
354   // being gross, this is also totally broken if we ever care about
355   // concurrency.
356 
357   TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
358 
359   TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
360   TargetMachine::setDataSections    (CodeGenOpts.DataSections);
361 
362   // FIXME: Parse this earlier.
363   llvm::CodeModel::Model CM;
364   if (CodeGenOpts.CodeModel == "small") {
365     CM = llvm::CodeModel::Small;
366   } else if (CodeGenOpts.CodeModel == "kernel") {
367     CM = llvm::CodeModel::Kernel;
368   } else if (CodeGenOpts.CodeModel == "medium") {
369     CM = llvm::CodeModel::Medium;
370   } else if (CodeGenOpts.CodeModel == "large") {
371     CM = llvm::CodeModel::Large;
372   } else {
373     assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
374     CM = llvm::CodeModel::Default;
375   }
376 
377   SmallVector<const char *, 16> BackendArgs;
378   BackendArgs.push_back("clang"); // Fake program name.
379   if (!CodeGenOpts.DebugPass.empty()) {
380     BackendArgs.push_back("-debug-pass");
381     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
382   }
383   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
384     BackendArgs.push_back("-limit-float-precision");
385     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
386   }
387   if (llvm::TimePassesIsEnabled)
388     BackendArgs.push_back("-time-passes");
389   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
390     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
391   if (CodeGenOpts.NoGlobalMerge)
392     BackendArgs.push_back("-global-merge=false");
393   BackendArgs.push_back(0);
394   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
395                                     BackendArgs.data());
396 
397   std::string FeaturesStr;
398   if (TargetOpts.Features.size()) {
399     SubtargetFeatures Features;
400     for (std::vector<std::string>::const_iterator
401            it = TargetOpts.Features.begin(),
402            ie = TargetOpts.Features.end(); it != ie; ++it)
403       Features.AddFeature(*it);
404     FeaturesStr = Features.getString();
405   }
406 
407   llvm::Reloc::Model RM = llvm::Reloc::Default;
408   if (CodeGenOpts.RelocationModel == "static") {
409     RM = llvm::Reloc::Static;
410   } else if (CodeGenOpts.RelocationModel == "pic") {
411     RM = llvm::Reloc::PIC_;
412   } else {
413     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
414            "Invalid PIC model!");
415     RM = llvm::Reloc::DynamicNoPIC;
416   }
417 
418   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
419   switch (CodeGenOpts.OptimizationLevel) {
420   default: break;
421   case 0: OptLevel = CodeGenOpt::None; break;
422   case 3: OptLevel = CodeGenOpt::Aggressive; break;
423   }
424 
425   llvm::TargetOptions Options;
426 
427   // Set frame pointer elimination mode.
428   if (!CodeGenOpts.DisableFPElim) {
429     Options.NoFramePointerElim = false;
430   } else if (CodeGenOpts.OmitLeafFramePointer) {
431     Options.NoFramePointerElim = false;
432   } else {
433     Options.NoFramePointerElim = true;
434   }
435 
436   if (CodeGenOpts.UseInitArray)
437     Options.UseInitArray = true;
438 
439   // Set float ABI type.
440   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
441     Options.FloatABIType = llvm::FloatABI::Soft;
442   else if (CodeGenOpts.FloatABI == "hard")
443     Options.FloatABIType = llvm::FloatABI::Hard;
444   else {
445     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
446     Options.FloatABIType = llvm::FloatABI::Default;
447   }
448 
449   // Set FP fusion mode.
450   switch (CodeGenOpts.getFPContractMode()) {
451   case CodeGenOptions::FPC_Off:
452     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
453     break;
454   case CodeGenOptions::FPC_On:
455     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
456     break;
457   case CodeGenOptions::FPC_Fast:
458     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
459     break;
460   }
461 
462   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
463   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
464   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
465   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
466   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
467   Options.UseSoftFloat = CodeGenOpts.SoftFloat;
468   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
469   Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
470   Options.TrapFuncName = CodeGenOpts.TrapFuncName;
471   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
472   Options.EnableSegmentedStacks = CodeGenOpts.EnableSegmentedStacks;
473 
474   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
475                                                      FeaturesStr, Options,
476                                                      RM, CM, OptLevel);
477 
478   if (CodeGenOpts.RelaxAll)
479     TM->setMCRelaxAll(true);
480   if (CodeGenOpts.SaveTempLabels)
481     TM->setMCSaveTempLabels(true);
482   if (CodeGenOpts.NoDwarf2CFIAsm)
483     TM->setMCUseCFI(false);
484   if (!CodeGenOpts.NoDwarfDirectoryAsm)
485     TM->setMCUseDwarfDirectory(true);
486   if (CodeGenOpts.NoExecStack)
487     TM->setMCNoExecStack(true);
488 
489   return TM;
490 }
491 
492 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
493                                        formatted_raw_ostream &OS,
494                                        TargetMachine *TM) {
495 
496   // Create the code generator passes.
497   PassManager *PM = getCodeGenPasses(TM);
498 
499   // Add LibraryInfo.
500   llvm::Triple TargetTriple(TheModule->getTargetTriple());
501   TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
502   if (!CodeGenOpts.SimplifyLibCalls)
503     TLI->disableAllFunctions();
504   PM->add(TLI);
505 
506   // Add Target specific analysis passes.
507   TM->addAnalysisPasses(*PM);
508 
509   // Normal mode, emit a .s or .o file by running the code generator. Note,
510   // this also adds codegenerator level optimization passes.
511   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
512   if (Action == Backend_EmitObj)
513     CGFT = TargetMachine::CGFT_ObjectFile;
514   else if (Action == Backend_EmitMCNull)
515     CGFT = TargetMachine::CGFT_Null;
516   else
517     assert(Action == Backend_EmitAssembly && "Invalid action!");
518 
519   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
520   // "codegen" passes so that it isn't run multiple times when there is
521   // inlining happening.
522   if (LangOpts.ObjCAutoRefCount &&
523       CodeGenOpts.OptimizationLevel > 0)
524     PM->add(createObjCARCContractPass());
525 
526   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
527                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
528     Diags.Report(diag::err_fe_unable_to_interface_with_target);
529     return false;
530   }
531 
532   return true;
533 }
534 
535 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
536   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
537   llvm::formatted_raw_ostream FormattedOS;
538 
539   bool UsesCodeGen = (Action != Backend_EmitNothing &&
540                       Action != Backend_EmitBC &&
541                       Action != Backend_EmitLL);
542   TargetMachine *TM = CreateTargetMachine(UsesCodeGen);
543   if (UsesCodeGen && !TM) return;
544   llvm::OwningPtr<TargetMachine> TMOwner(CodeGenOpts.DisableFree ? 0 : TM);
545   CreatePasses(TM);
546 
547   switch (Action) {
548   case Backend_EmitNothing:
549     break;
550 
551   case Backend_EmitBC:
552     getPerModulePasses(TM)->add(createBitcodeWriterPass(*OS));
553     break;
554 
555   case Backend_EmitLL:
556     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
557     getPerModulePasses(TM)->add(createPrintModulePass(&FormattedOS));
558     break;
559 
560   default:
561     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
562     if (!AddEmitPasses(Action, FormattedOS, TM))
563       return;
564   }
565 
566   // Before executing passes, print the final values of the LLVM options.
567   cl::PrintOptionValues();
568 
569   // Run passes. For now we do all passes at once, but eventually we
570   // would like to have the option of streaming code generation.
571 
572   if (PerFunctionPasses) {
573     PrettyStackTraceString CrashInfo("Per-function optimization");
574 
575     PerFunctionPasses->doInitialization();
576     for (Module::iterator I = TheModule->begin(),
577            E = TheModule->end(); I != E; ++I)
578       if (!I->isDeclaration())
579         PerFunctionPasses->run(*I);
580     PerFunctionPasses->doFinalization();
581   }
582 
583   if (PerModulePasses) {
584     PrettyStackTraceString CrashInfo("Per-module optimization passes");
585     PerModulePasses->run(*TheModule);
586   }
587 
588   if (CodeGenPasses) {
589     PrettyStackTraceString CrashInfo("Code generation");
590     CodeGenPasses->run(*TheModule);
591   }
592 }
593 
594 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
595                               const CodeGenOptions &CGOpts,
596                               const clang::TargetOptions &TOpts,
597                               const LangOptions &LOpts,
598                               Module *M,
599                               BackendAction Action, raw_ostream *OS) {
600   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
601 
602   AsmHelper.EmitAssembly(Action, OS);
603 }
604