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