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