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   PM.add(createDataFlowSanitizerPass());
212 }
213 
214 void EmitAssemblyHelper::CreatePasses(TargetMachine *TM) {
215   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
216   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
217 
218   // Handle disabling of LLVM optimization, where we want to preserve the
219   // internal module before any optimization.
220   if (CodeGenOpts.DisableLLVMOpts) {
221     OptLevel = 0;
222     Inlining = CodeGenOpts.NoInlining;
223   }
224 
225   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
226   PMBuilder.OptLevel = OptLevel;
227   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
228   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
229   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
230   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
231 
232   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
233   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
234 
235   // In ObjC ARC mode, add the main ARC optimization passes.
236   if (LangOpts.ObjCAutoRefCount) {
237     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
238                            addObjCARCExpandPass);
239     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
240                            addObjCARCAPElimPass);
241     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
242                            addObjCARCOptPass);
243   }
244 
245   if (LangOpts.Sanitize.Bounds) {
246     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
247                            addBoundsCheckingPass);
248     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
249                            addBoundsCheckingPass);
250   }
251 
252   if (LangOpts.Sanitize.Address) {
253     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
254                            addAddressSanitizerPasses);
255     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
256                            addAddressSanitizerPasses);
257   }
258 
259   if (LangOpts.Sanitize.Memory) {
260     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
261                            addMemorySanitizerPass);
262     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
263                            addMemorySanitizerPass);
264   }
265 
266   if (LangOpts.Sanitize.Thread) {
267     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
268                            addThreadSanitizerPass);
269     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
270                            addThreadSanitizerPass);
271   }
272 
273   if (LangOpts.Sanitize.DataFlow) {
274     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
275                            addDataFlowSanitizerPass);
276     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
277                            addDataFlowSanitizerPass);
278   }
279 
280   // Figure out TargetLibraryInfo.
281   Triple TargetTriple(TheModule->getTargetTriple());
282   PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
283   if (!CodeGenOpts.SimplifyLibCalls)
284     PMBuilder.LibraryInfo->disableAllFunctions();
285 
286   switch (Inlining) {
287   case CodeGenOptions::NoInlining: break;
288   case CodeGenOptions::NormalInlining: {
289     // FIXME: Derive these constants in a principled fashion.
290     unsigned Threshold = 225;
291     if (CodeGenOpts.OptimizeSize == 1)      // -Os
292       Threshold = 75;
293     else if (CodeGenOpts.OptimizeSize == 2) // -Oz
294       Threshold = 25;
295     else if (OptLevel > 2)
296       Threshold = 275;
297     PMBuilder.Inliner = createFunctionInliningPass(Threshold);
298     break;
299   }
300   case CodeGenOptions::OnlyAlwaysInlining:
301     // Respect always_inline.
302     if (OptLevel == 0)
303       // Do not insert lifetime intrinsics at -O0.
304       PMBuilder.Inliner = createAlwaysInlinerPass(false);
305     else
306       PMBuilder.Inliner = createAlwaysInlinerPass();
307     break;
308   }
309 
310   // Set up the per-function pass manager.
311   FunctionPassManager *FPM = getPerFunctionPasses(TM);
312   if (CodeGenOpts.VerifyModule)
313     FPM->add(createVerifierPass());
314   PMBuilder.populateFunctionPassManager(*FPM);
315 
316   // Set up the per-module pass manager.
317   PassManager *MPM = getPerModulePasses(TM);
318 
319   if (!CodeGenOpts.DisableGCov &&
320       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
321     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
322     // LLVM's -default-gcov-version flag is set to something invalid.
323     GCOVOptions Options;
324     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
325     Options.EmitData = CodeGenOpts.EmitGcovArcs;
326     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
327     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
328     Options.NoRedZone = CodeGenOpts.DisableRedZone;
329     Options.FunctionNamesInData =
330         !CodeGenOpts.CoverageNoFunctionNamesInData;
331     MPM->add(createGCOVProfilerPass(Options));
332     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
333       MPM->add(createStripSymbolsPass(true));
334   }
335 
336   PMBuilder.populateModulePassManager(*MPM);
337 }
338 
339 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
340   // Create the TargetMachine for generating code.
341   std::string Error;
342   std::string Triple = TheModule->getTargetTriple();
343   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
344   if (!TheTarget) {
345     if (MustCreateTM)
346       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
347     return 0;
348   }
349 
350   // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
351   // being gross, this is also totally broken if we ever care about
352   // concurrency.
353 
354   TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
355 
356   TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
357   TargetMachine::setDataSections    (CodeGenOpts.DataSections);
358 
359   // FIXME: Parse this earlier.
360   llvm::CodeModel::Model CM;
361   if (CodeGenOpts.CodeModel == "small") {
362     CM = llvm::CodeModel::Small;
363   } else if (CodeGenOpts.CodeModel == "kernel") {
364     CM = llvm::CodeModel::Kernel;
365   } else if (CodeGenOpts.CodeModel == "medium") {
366     CM = llvm::CodeModel::Medium;
367   } else if (CodeGenOpts.CodeModel == "large") {
368     CM = llvm::CodeModel::Large;
369   } else {
370     assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
371     CM = llvm::CodeModel::Default;
372   }
373 
374   SmallVector<const char *, 16> BackendArgs;
375   BackendArgs.push_back("clang"); // Fake program name.
376   if (!CodeGenOpts.DebugPass.empty()) {
377     BackendArgs.push_back("-debug-pass");
378     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
379   }
380   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
381     BackendArgs.push_back("-limit-float-precision");
382     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
383   }
384   if (llvm::TimePassesIsEnabled)
385     BackendArgs.push_back("-time-passes");
386   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
387     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
388   if (CodeGenOpts.NoGlobalMerge)
389     BackendArgs.push_back("-global-merge=false");
390   BackendArgs.push_back(0);
391   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
392                                     BackendArgs.data());
393 
394   std::string FeaturesStr;
395   if (TargetOpts.Features.size()) {
396     SubtargetFeatures Features;
397     for (std::vector<std::string>::const_iterator
398            it = TargetOpts.Features.begin(),
399            ie = TargetOpts.Features.end(); it != ie; ++it)
400       Features.AddFeature(*it);
401     FeaturesStr = Features.getString();
402   }
403 
404   llvm::Reloc::Model RM = llvm::Reloc::Default;
405   if (CodeGenOpts.RelocationModel == "static") {
406     RM = llvm::Reloc::Static;
407   } else if (CodeGenOpts.RelocationModel == "pic") {
408     RM = llvm::Reloc::PIC_;
409   } else {
410     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
411            "Invalid PIC model!");
412     RM = llvm::Reloc::DynamicNoPIC;
413   }
414 
415   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
416   switch (CodeGenOpts.OptimizationLevel) {
417   default: break;
418   case 0: OptLevel = CodeGenOpt::None; break;
419   case 3: OptLevel = CodeGenOpt::Aggressive; break;
420   }
421 
422   llvm::TargetOptions Options;
423 
424   // Set frame pointer elimination mode.
425   if (!CodeGenOpts.DisableFPElim) {
426     Options.NoFramePointerElim = false;
427   } else if (CodeGenOpts.OmitLeafFramePointer) {
428     Options.NoFramePointerElim = false;
429   } else {
430     Options.NoFramePointerElim = true;
431   }
432 
433   if (CodeGenOpts.UseInitArray)
434     Options.UseInitArray = true;
435 
436   // Set float ABI type.
437   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
438     Options.FloatABIType = llvm::FloatABI::Soft;
439   else if (CodeGenOpts.FloatABI == "hard")
440     Options.FloatABIType = llvm::FloatABI::Hard;
441   else {
442     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
443     Options.FloatABIType = llvm::FloatABI::Default;
444   }
445 
446   // Set FP fusion mode.
447   switch (CodeGenOpts.getFPContractMode()) {
448   case CodeGenOptions::FPC_Off:
449     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
450     break;
451   case CodeGenOptions::FPC_On:
452     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
453     break;
454   case CodeGenOptions::FPC_Fast:
455     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
456     break;
457   }
458 
459   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
460   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
461   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
462   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
463   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
464   Options.UseSoftFloat = CodeGenOpts.SoftFloat;
465   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
466   Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
467   Options.TrapFuncName = CodeGenOpts.TrapFuncName;
468   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
469   Options.EnableSegmentedStacks = CodeGenOpts.EnableSegmentedStacks;
470 
471   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
472                                                      FeaturesStr, Options,
473                                                      RM, CM, OptLevel);
474 
475   if (CodeGenOpts.RelaxAll)
476     TM->setMCRelaxAll(true);
477   if (CodeGenOpts.SaveTempLabels)
478     TM->setMCSaveTempLabels(true);
479   if (CodeGenOpts.NoDwarf2CFIAsm)
480     TM->setMCUseCFI(false);
481   if (!CodeGenOpts.NoDwarfDirectoryAsm)
482     TM->setMCUseDwarfDirectory(true);
483   if (CodeGenOpts.NoExecStack)
484     TM->setMCNoExecStack(true);
485 
486   return TM;
487 }
488 
489 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
490                                        formatted_raw_ostream &OS,
491                                        TargetMachine *TM) {
492 
493   // Create the code generator passes.
494   PassManager *PM = getCodeGenPasses(TM);
495 
496   // Add LibraryInfo.
497   llvm::Triple TargetTriple(TheModule->getTargetTriple());
498   TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
499   if (!CodeGenOpts.SimplifyLibCalls)
500     TLI->disableAllFunctions();
501   PM->add(TLI);
502 
503   // Add Target specific analysis passes.
504   TM->addAnalysisPasses(*PM);
505 
506   // Normal mode, emit a .s or .o file by running the code generator. Note,
507   // this also adds codegenerator level optimization passes.
508   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
509   if (Action == Backend_EmitObj)
510     CGFT = TargetMachine::CGFT_ObjectFile;
511   else if (Action == Backend_EmitMCNull)
512     CGFT = TargetMachine::CGFT_Null;
513   else
514     assert(Action == Backend_EmitAssembly && "Invalid action!");
515 
516   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
517   // "codegen" passes so that it isn't run multiple times when there is
518   // inlining happening.
519   if (LangOpts.ObjCAutoRefCount &&
520       CodeGenOpts.OptimizationLevel > 0)
521     PM->add(createObjCARCContractPass());
522 
523   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
524                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
525     Diags.Report(diag::err_fe_unable_to_interface_with_target);
526     return false;
527   }
528 
529   return true;
530 }
531 
532 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
533   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
534   llvm::formatted_raw_ostream FormattedOS;
535 
536   bool UsesCodeGen = (Action != Backend_EmitNothing &&
537                       Action != Backend_EmitBC &&
538                       Action != Backend_EmitLL);
539   TargetMachine *TM = CreateTargetMachine(UsesCodeGen);
540   if (UsesCodeGen && !TM) return;
541   llvm::OwningPtr<TargetMachine> TMOwner(CodeGenOpts.DisableFree ? 0 : TM);
542   CreatePasses(TM);
543 
544   switch (Action) {
545   case Backend_EmitNothing:
546     break;
547 
548   case Backend_EmitBC:
549     getPerModulePasses(TM)->add(createBitcodeWriterPass(*OS));
550     break;
551 
552   case Backend_EmitLL:
553     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
554     getPerModulePasses(TM)->add(createPrintModulePass(&FormattedOS));
555     break;
556 
557   default:
558     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
559     if (!AddEmitPasses(Action, FormattedOS, TM))
560       return;
561   }
562 
563   // Before executing passes, print the final values of the LLVM options.
564   cl::PrintOptionValues();
565 
566   // Run passes. For now we do all passes at once, but eventually we
567   // would like to have the option of streaming code generation.
568 
569   if (PerFunctionPasses) {
570     PrettyStackTraceString CrashInfo("Per-function optimization");
571 
572     PerFunctionPasses->doInitialization();
573     for (Module::iterator I = TheModule->begin(),
574            E = TheModule->end(); I != E; ++I)
575       if (!I->isDeclaration())
576         PerFunctionPasses->run(*I);
577     PerFunctionPasses->doFinalization();
578   }
579 
580   if (PerModulePasses) {
581     PrettyStackTraceString CrashInfo("Per-module optimization passes");
582     PerModulePasses->run(*TheModule);
583   }
584 
585   if (CodeGenPasses) {
586     PrettyStackTraceString CrashInfo("Code generation");
587     CodeGenPasses->run(*TheModule);
588   }
589 }
590 
591 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
592                               const CodeGenOptions &CGOpts,
593                               const clang::TargetOptions &TOpts,
594                               const LangOptions &LOpts,
595                               Module *M,
596                               BackendAction Action, raw_ostream *OS) {
597   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
598 
599   AsmHelper.EmitAssembly(Action, OS);
600 }
601