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   if (CodeGenOpts.VerifyModule)
338     MPM->add(createDebugInfoVerifierPass());
339 
340   if (!CodeGenOpts.DisableGCov &&
341       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
342     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
343     // LLVM's -default-gcov-version flag is set to something invalid.
344     GCOVOptions Options;
345     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
346     Options.EmitData = CodeGenOpts.EmitGcovArcs;
347     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
348     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
349     Options.NoRedZone = CodeGenOpts.DisableRedZone;
350     Options.FunctionNamesInData =
351         !CodeGenOpts.CoverageNoFunctionNamesInData;
352     MPM->add(createGCOVProfilerPass(Options));
353     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
354       MPM->add(createStripSymbolsPass(true));
355   }
356 
357   PMBuilder.populateModulePassManager(*MPM);
358 }
359 
360 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
361   // Create the TargetMachine for generating code.
362   std::string Error;
363   std::string Triple = TheModule->getTargetTriple();
364   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
365   if (!TheTarget) {
366     if (MustCreateTM)
367       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
368     return 0;
369   }
370 
371   // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
372   // being gross, this is also totally broken if we ever care about
373   // concurrency.
374 
375   TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
376 
377   TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
378   TargetMachine::setDataSections    (CodeGenOpts.DataSections);
379 
380   // FIXME: Parse this earlier.
381   llvm::CodeModel::Model CM;
382   if (CodeGenOpts.CodeModel == "small") {
383     CM = llvm::CodeModel::Small;
384   } else if (CodeGenOpts.CodeModel == "kernel") {
385     CM = llvm::CodeModel::Kernel;
386   } else if (CodeGenOpts.CodeModel == "medium") {
387     CM = llvm::CodeModel::Medium;
388   } else if (CodeGenOpts.CodeModel == "large") {
389     CM = llvm::CodeModel::Large;
390   } else {
391     assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
392     CM = llvm::CodeModel::Default;
393   }
394 
395   SmallVector<const char *, 16> BackendArgs;
396   BackendArgs.push_back("clang"); // Fake program name.
397   if (!CodeGenOpts.DebugPass.empty()) {
398     BackendArgs.push_back("-debug-pass");
399     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
400   }
401   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
402     BackendArgs.push_back("-limit-float-precision");
403     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
404   }
405   if (llvm::TimePassesIsEnabled)
406     BackendArgs.push_back("-time-passes");
407   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
408     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
409   if (CodeGenOpts.NoGlobalMerge)
410     BackendArgs.push_back("-global-merge=false");
411   BackendArgs.push_back(0);
412   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
413                                     BackendArgs.data());
414 
415   std::string FeaturesStr;
416   if (TargetOpts.Features.size()) {
417     SubtargetFeatures Features;
418     for (std::vector<std::string>::const_iterator
419            it = TargetOpts.Features.begin(),
420            ie = TargetOpts.Features.end(); it != ie; ++it)
421       Features.AddFeature(*it);
422     FeaturesStr = Features.getString();
423   }
424 
425   llvm::Reloc::Model RM = llvm::Reloc::Default;
426   if (CodeGenOpts.RelocationModel == "static") {
427     RM = llvm::Reloc::Static;
428   } else if (CodeGenOpts.RelocationModel == "pic") {
429     RM = llvm::Reloc::PIC_;
430   } else {
431     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
432            "Invalid PIC model!");
433     RM = llvm::Reloc::DynamicNoPIC;
434   }
435 
436   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
437   switch (CodeGenOpts.OptimizationLevel) {
438   default: break;
439   case 0: OptLevel = CodeGenOpt::None; break;
440   case 3: OptLevel = CodeGenOpt::Aggressive; break;
441   }
442 
443   llvm::TargetOptions Options;
444 
445   if (CodeGenOpts.DisableIntegratedAS)
446     Options.DisableIntegratedAS = true;
447 
448   if (CodeGenOpts.CompressDebugSections)
449     Options.CompressDebugSections = true;
450 
451   // Set frame pointer elimination mode.
452   if (!CodeGenOpts.DisableFPElim) {
453     Options.NoFramePointerElim = false;
454   } else if (CodeGenOpts.OmitLeafFramePointer) {
455     Options.NoFramePointerElim = false;
456   } else {
457     Options.NoFramePointerElim = true;
458   }
459 
460   if (CodeGenOpts.UseInitArray)
461     Options.UseInitArray = true;
462 
463   // Set float ABI type.
464   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
465     Options.FloatABIType = llvm::FloatABI::Soft;
466   else if (CodeGenOpts.FloatABI == "hard")
467     Options.FloatABIType = llvm::FloatABI::Hard;
468   else {
469     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
470     Options.FloatABIType = llvm::FloatABI::Default;
471   }
472 
473   // Set FP fusion mode.
474   switch (CodeGenOpts.getFPContractMode()) {
475   case CodeGenOptions::FPC_Off:
476     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
477     break;
478   case CodeGenOptions::FPC_On:
479     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
480     break;
481   case CodeGenOptions::FPC_Fast:
482     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
483     break;
484   }
485 
486   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
487   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
488   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
489   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
490   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
491   Options.UseSoftFloat = CodeGenOpts.SoftFloat;
492   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
493   Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
494   Options.TrapFuncName = CodeGenOpts.TrapFuncName;
495   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
496 
497   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
498                                                      FeaturesStr, Options,
499                                                      RM, CM, OptLevel);
500 
501   if (CodeGenOpts.RelaxAll)
502     TM->setMCRelaxAll(true);
503   if (CodeGenOpts.SaveTempLabels)
504     TM->setMCSaveTempLabels(true);
505   if (CodeGenOpts.NoDwarf2CFIAsm)
506     TM->setMCUseCFI(false);
507   if (!CodeGenOpts.NoDwarfDirectoryAsm)
508     TM->setMCUseDwarfDirectory(true);
509   if (CodeGenOpts.NoExecStack)
510     TM->setMCNoExecStack(true);
511 
512   return TM;
513 }
514 
515 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
516                                        formatted_raw_ostream &OS) {
517 
518   // Create the code generator passes.
519   PassManager *PM = getCodeGenPasses();
520 
521   // Add LibraryInfo.
522   llvm::Triple TargetTriple(TheModule->getTargetTriple());
523   TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
524   if (!CodeGenOpts.SimplifyLibCalls)
525     TLI->disableAllFunctions();
526   PM->add(TLI);
527 
528   // Add Target specific analysis passes.
529   TM->addAnalysisPasses(*PM);
530 
531   // Normal mode, emit a .s or .o file by running the code generator. Note,
532   // this also adds codegenerator level optimization passes.
533   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
534   if (Action == Backend_EmitObj)
535     CGFT = TargetMachine::CGFT_ObjectFile;
536   else if (Action == Backend_EmitMCNull)
537     CGFT = TargetMachine::CGFT_Null;
538   else
539     assert(Action == Backend_EmitAssembly && "Invalid action!");
540 
541   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
542   // "codegen" passes so that it isn't run multiple times when there is
543   // inlining happening.
544   if (LangOpts.ObjCAutoRefCount &&
545       CodeGenOpts.OptimizationLevel > 0)
546     PM->add(createObjCARCContractPass());
547 
548   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
549                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
550     Diags.Report(diag::err_fe_unable_to_interface_with_target);
551     return false;
552   }
553 
554   return true;
555 }
556 
557 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
558   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
559   llvm::formatted_raw_ostream FormattedOS;
560 
561   bool UsesCodeGen = (Action != Backend_EmitNothing &&
562                       Action != Backend_EmitBC &&
563                       Action != Backend_EmitLL);
564   if (!TM)
565     TM.reset(CreateTargetMachine(UsesCodeGen));
566 
567   if (UsesCodeGen && !TM) return;
568   CreatePasses();
569 
570   switch (Action) {
571   case Backend_EmitNothing:
572     break;
573 
574   case Backend_EmitBC:
575     getPerModulePasses()->add(createBitcodeWriterPass(*OS));
576     break;
577 
578   case Backend_EmitLL:
579     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
580     getPerModulePasses()->add(createPrintModulePass(FormattedOS));
581     break;
582 
583   default:
584     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
585     if (!AddEmitPasses(Action, FormattedOS))
586       return;
587   }
588 
589   // Before executing passes, print the final values of the LLVM options.
590   cl::PrintOptionValues();
591 
592   // Run passes. For now we do all passes at once, but eventually we
593   // would like to have the option of streaming code generation.
594 
595   if (PerFunctionPasses) {
596     PrettyStackTraceString CrashInfo("Per-function optimization");
597 
598     PerFunctionPasses->doInitialization();
599     for (Module::iterator I = TheModule->begin(),
600            E = TheModule->end(); I != E; ++I)
601       if (!I->isDeclaration())
602         PerFunctionPasses->run(*I);
603     PerFunctionPasses->doFinalization();
604   }
605 
606   if (PerModulePasses) {
607     PrettyStackTraceString CrashInfo("Per-module optimization passes");
608     PerModulePasses->run(*TheModule);
609   }
610 
611   if (CodeGenPasses) {
612     PrettyStackTraceString CrashInfo("Code generation");
613     CodeGenPasses->run(*TheModule);
614   }
615 }
616 
617 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
618                               const CodeGenOptions &CGOpts,
619                               const clang::TargetOptions &TOpts,
620                               const LangOptions &LOpts, StringRef TDesc,
621                               Module *M, BackendAction Action,
622                               raw_ostream *OS) {
623   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
624 
625   AsmHelper.EmitAssembly(Action, OS);
626 
627   // If an optional clang TargetInfo description string was passed in, use it to
628   // verify the LLVM TargetMachine's DataLayout.
629   if (AsmHelper.TM && !TDesc.empty()) {
630     std::string DLDesc =
631         AsmHelper.TM->getDataLayout()->getStringRepresentation();
632     if (DLDesc != TDesc) {
633       unsigned DiagID = Diags.getCustomDiagID(
634           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
635                                     "expected target description '%1'");
636       Diags.Report(DiagID) << DLDesc << TDesc;
637     }
638   }
639 }
640