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