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