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