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