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(/*CompileKernel*/false));
205   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false));
206 }
207 
208 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
209                                             legacy::PassManagerBase &PM) {
210   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true));
211   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true));
212 }
213 
214 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
215                                    legacy::PassManagerBase &PM) {
216   const PassManagerBuilderWrapper &BuilderWrapper =
217       static_cast<const PassManagerBuilderWrapper&>(Builder);
218   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
219   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
220 
221   // MemorySanitizer inserts complex instrumentation that mostly follows
222   // the logic of the original code, but operates on "shadow" values.
223   // It can benefit from re-running some general purpose optimization passes.
224   if (Builder.OptLevel > 0) {
225     PM.add(createEarlyCSEPass());
226     PM.add(createReassociatePass());
227     PM.add(createLICMPass());
228     PM.add(createGVNPass());
229     PM.add(createInstructionCombiningPass());
230     PM.add(createDeadStoreEliminationPass());
231   }
232 }
233 
234 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
235                                    legacy::PassManagerBase &PM) {
236   PM.add(createThreadSanitizerPass());
237 }
238 
239 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
240                                      legacy::PassManagerBase &PM) {
241   const PassManagerBuilderWrapper &BuilderWrapper =
242       static_cast<const PassManagerBuilderWrapper&>(Builder);
243   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
244   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
245 }
246 
247 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
248                                          const CodeGenOptions &CodeGenOpts) {
249   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
250   if (!CodeGenOpts.SimplifyLibCalls)
251     TLII->disableAllFunctions();
252 
253   switch (CodeGenOpts.getVecLib()) {
254   case CodeGenOptions::Accelerate:
255     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
256     break;
257   default:
258     break;
259   }
260   return TLII;
261 }
262 
263 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
264                                   legacy::PassManager *MPM) {
265   llvm::SymbolRewriter::RewriteDescriptorList DL;
266 
267   llvm::SymbolRewriter::RewriteMapParser MapParser;
268   for (const auto &MapFile : Opts.RewriteMapFiles)
269     MapParser.parse(MapFile, &DL);
270 
271   MPM->add(createRewriteSymbolsPass(DL));
272 }
273 
274 void EmitAssemblyHelper::CreatePasses() {
275   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
276   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
277 
278   // Handle disabling of LLVM optimization, where we want to preserve the
279   // internal module before any optimization.
280   if (CodeGenOpts.DisableLLVMOpts) {
281     OptLevel = 0;
282     Inlining = CodeGenOpts.NoInlining;
283   }
284 
285   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
286   PMBuilder.OptLevel = OptLevel;
287   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
288   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
289   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
290   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
291 
292   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
293   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
294   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
295   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
296 
297   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
298                          addAddDiscriminatorsPass);
299 
300   if (!CodeGenOpts.SampleProfileFile.empty())
301     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
302                            addSampleProfileLoaderPass);
303 
304   // In ObjC ARC mode, add the main ARC optimization passes.
305   if (LangOpts.ObjCAutoRefCount) {
306     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
307                            addObjCARCExpandPass);
308     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
309                            addObjCARCAPElimPass);
310     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
311                            addObjCARCOptPass);
312   }
313 
314   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
315     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
316                            addBoundsCheckingPass);
317     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
318                            addBoundsCheckingPass);
319   }
320 
321   if (CodeGenOpts.SanitizeCoverageType ||
322       CodeGenOpts.SanitizeCoverageIndirectCalls ||
323       CodeGenOpts.SanitizeCoverageTraceCmp) {
324     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
325                            addSanitizerCoveragePass);
326     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
327                            addSanitizerCoveragePass);
328   }
329 
330   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
331     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
332                            addAddressSanitizerPasses);
333     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
334                            addAddressSanitizerPasses);
335   }
336 
337   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
338     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
339                            addKernelAddressSanitizerPasses);
340     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
341                            addKernelAddressSanitizerPasses);
342   }
343 
344   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
345     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
346                            addMemorySanitizerPass);
347     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
348                            addMemorySanitizerPass);
349   }
350 
351   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
352     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
353                            addThreadSanitizerPass);
354     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
355                            addThreadSanitizerPass);
356   }
357 
358   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
359     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
360                            addDataFlowSanitizerPass);
361     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
362                            addDataFlowSanitizerPass);
363   }
364 
365   // Figure out TargetLibraryInfo.
366   Triple TargetTriple(TheModule->getTargetTriple());
367   PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
368 
369   switch (Inlining) {
370   case CodeGenOptions::NoInlining: break;
371   case CodeGenOptions::NormalInlining: {
372     PMBuilder.Inliner =
373         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
374     break;
375   }
376   case CodeGenOptions::OnlyAlwaysInlining:
377     // Respect always_inline.
378     if (OptLevel == 0)
379       // Do not insert lifetime intrinsics at -O0.
380       PMBuilder.Inliner = createAlwaysInlinerPass(false);
381     else
382       PMBuilder.Inliner = createAlwaysInlinerPass();
383     break;
384   }
385 
386   // Set up the per-function pass manager.
387   legacy::FunctionPassManager *FPM = getPerFunctionPasses();
388   if (CodeGenOpts.VerifyModule)
389     FPM->add(createVerifierPass());
390   PMBuilder.populateFunctionPassManager(*FPM);
391 
392   // Set up the per-module pass manager.
393   legacy::PassManager *MPM = getPerModulePasses();
394   if (!CodeGenOpts.RewriteMapFiles.empty())
395     addSymbolRewriterPass(CodeGenOpts, MPM);
396 
397   if (!CodeGenOpts.DisableGCov &&
398       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
399     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
400     // LLVM's -default-gcov-version flag is set to something invalid.
401     GCOVOptions Options;
402     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
403     Options.EmitData = CodeGenOpts.EmitGcovArcs;
404     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
405     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
406     Options.NoRedZone = CodeGenOpts.DisableRedZone;
407     Options.FunctionNamesInData =
408         !CodeGenOpts.CoverageNoFunctionNamesInData;
409     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
410     MPM->add(createGCOVProfilerPass(Options));
411     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
412       MPM->add(createStripSymbolsPass(true));
413   }
414 
415   if (CodeGenOpts.ProfileInstrGenerate) {
416     InstrProfOptions Options;
417     Options.NoRedZone = CodeGenOpts.DisableRedZone;
418     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
419     MPM->add(createInstrProfilingPass(Options));
420   }
421 
422   PMBuilder.populateModulePassManager(*MPM);
423 }
424 
425 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
426   // Create the TargetMachine for generating code.
427   std::string Error;
428   std::string Triple = TheModule->getTargetTriple();
429   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
430   if (!TheTarget) {
431     if (MustCreateTM)
432       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
433     return nullptr;
434   }
435 
436   unsigned CodeModel =
437     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
438       .Case("small", llvm::CodeModel::Small)
439       .Case("kernel", llvm::CodeModel::Kernel)
440       .Case("medium", llvm::CodeModel::Medium)
441       .Case("large", llvm::CodeModel::Large)
442       .Case("default", llvm::CodeModel::Default)
443       .Default(~0u);
444   assert(CodeModel != ~0u && "invalid code model!");
445   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
446 
447   SmallVector<const char *, 16> BackendArgs;
448   BackendArgs.push_back("clang"); // Fake program name.
449   if (!CodeGenOpts.DebugPass.empty()) {
450     BackendArgs.push_back("-debug-pass");
451     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
452   }
453   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
454     BackendArgs.push_back("-limit-float-precision");
455     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
456   }
457   if (llvm::TimePassesIsEnabled)
458     BackendArgs.push_back("-time-passes");
459   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
460     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
461   BackendArgs.push_back(nullptr);
462   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
463                                     BackendArgs.data());
464 
465   std::string FeaturesStr;
466   if (!TargetOpts.Features.empty()) {
467     SubtargetFeatures Features;
468     for (const std::string &Feature : TargetOpts.Features)
469       Features.AddFeature(Feature);
470     FeaturesStr = Features.getString();
471   }
472 
473   llvm::Reloc::Model RM = llvm::Reloc::Default;
474   if (CodeGenOpts.RelocationModel == "static") {
475     RM = llvm::Reloc::Static;
476   } else if (CodeGenOpts.RelocationModel == "pic") {
477     RM = llvm::Reloc::PIC_;
478   } else {
479     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
480            "Invalid PIC model!");
481     RM = llvm::Reloc::DynamicNoPIC;
482   }
483 
484   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
485   switch (CodeGenOpts.OptimizationLevel) {
486   default: break;
487   case 0: OptLevel = CodeGenOpt::None; break;
488   case 3: OptLevel = CodeGenOpt::Aggressive; break;
489   }
490 
491   llvm::TargetOptions Options;
492 
493   if (!TargetOpts.Reciprocals.empty())
494     Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
495 
496   Options.ThreadModel =
497     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
498       .Case("posix", llvm::ThreadModel::POSIX)
499       .Case("single", llvm::ThreadModel::Single);
500 
501   if (CodeGenOpts.DisableIntegratedAS)
502     Options.DisableIntegratedAS = true;
503 
504   if (CodeGenOpts.CompressDebugSections)
505     Options.CompressDebugSections = true;
506 
507   if (CodeGenOpts.UseInitArray)
508     Options.UseInitArray = true;
509 
510   // Set float ABI type.
511   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
512     Options.FloatABIType = llvm::FloatABI::Soft;
513   else if (CodeGenOpts.FloatABI == "hard")
514     Options.FloatABIType = llvm::FloatABI::Hard;
515   else {
516     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
517     Options.FloatABIType = llvm::FloatABI::Default;
518   }
519 
520   // Set FP fusion mode.
521   switch (CodeGenOpts.getFPContractMode()) {
522   case CodeGenOptions::FPC_Off:
523     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
524     break;
525   case CodeGenOptions::FPC_On:
526     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
527     break;
528   case CodeGenOptions::FPC_Fast:
529     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
530     break;
531   }
532 
533   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
534   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
535   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
536   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
537   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
538   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
539   Options.TrapFuncName = CodeGenOpts.TrapFuncName;
540   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
541   Options.FunctionSections = CodeGenOpts.FunctionSections;
542   Options.DataSections = CodeGenOpts.DataSections;
543   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
544 
545   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
546   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
547   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
548   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
549   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
550   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
551   Options.MCOptions.ABIName = TargetOpts.ABI;
552 
553   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
554                                                      FeaturesStr, Options,
555                                                      RM, CM, OptLevel);
556 
557   return TM;
558 }
559 
560 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
561                                        raw_pwrite_stream &OS) {
562 
563   // Create the code generator passes.
564   legacy::PassManager *PM = getCodeGenPasses();
565 
566   // Add LibraryInfo.
567   llvm::Triple TargetTriple(TheModule->getTargetTriple());
568   std::unique_ptr<TargetLibraryInfoImpl> TLII(
569       createTLII(TargetTriple, CodeGenOpts));
570   PM->add(new TargetLibraryInfoWrapperPass(*TLII));
571 
572   // Normal mode, emit a .s or .o file by running the code generator. Note,
573   // this also adds codegenerator level optimization passes.
574   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
575   if (Action == Backend_EmitObj)
576     CGFT = TargetMachine::CGFT_ObjectFile;
577   else if (Action == Backend_EmitMCNull)
578     CGFT = TargetMachine::CGFT_Null;
579   else
580     assert(Action == Backend_EmitAssembly && "Invalid action!");
581 
582   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
583   // "codegen" passes so that it isn't run multiple times when there is
584   // inlining happening.
585   if (CodeGenOpts.OptimizationLevel > 0)
586     PM->add(createObjCARCContractPass());
587 
588   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
589                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
590     Diags.Report(diag::err_fe_unable_to_interface_with_target);
591     return false;
592   }
593 
594   return true;
595 }
596 
597 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
598                                       raw_pwrite_stream *OS) {
599   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
600 
601   bool UsesCodeGen = (Action != Backend_EmitNothing &&
602                       Action != Backend_EmitBC &&
603                       Action != Backend_EmitLL);
604   if (!TM)
605     TM.reset(CreateTargetMachine(UsesCodeGen));
606 
607   if (UsesCodeGen && !TM)
608     return;
609   if (TM)
610     TheModule->setDataLayout(*TM->getDataLayout());
611   CreatePasses();
612 
613   switch (Action) {
614   case Backend_EmitNothing:
615     break;
616 
617   case Backend_EmitBC:
618     getPerModulePasses()->add(
619         createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
620     break;
621 
622   case Backend_EmitLL:
623     getPerModulePasses()->add(
624         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
625     break;
626 
627   default:
628     if (!AddEmitPasses(Action, *OS))
629       return;
630   }
631 
632   // Before executing passes, print the final values of the LLVM options.
633   cl::PrintOptionValues();
634 
635   // Run passes. For now we do all passes at once, but eventually we
636   // would like to have the option of streaming code generation.
637 
638   if (PerFunctionPasses) {
639     PrettyStackTraceString CrashInfo("Per-function optimization");
640 
641     PerFunctionPasses->doInitialization();
642     for (Function &F : *TheModule)
643       if (!F.isDeclaration())
644         PerFunctionPasses->run(F);
645     PerFunctionPasses->doFinalization();
646   }
647 
648   if (PerModulePasses) {
649     PrettyStackTraceString CrashInfo("Per-module optimization passes");
650     PerModulePasses->run(*TheModule);
651   }
652 
653   if (CodeGenPasses) {
654     PrettyStackTraceString CrashInfo("Code generation");
655     CodeGenPasses->run(*TheModule);
656   }
657 }
658 
659 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
660                               const CodeGenOptions &CGOpts,
661                               const clang::TargetOptions &TOpts,
662                               const LangOptions &LOpts, StringRef TDesc,
663                               Module *M, BackendAction Action,
664                               raw_pwrite_stream *OS) {
665   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
666 
667   AsmHelper.EmitAssembly(Action, OS);
668 
669   // If an optional clang TargetInfo description string was passed in, use it to
670   // verify the LLVM TargetMachine's DataLayout.
671   if (AsmHelper.TM && !TDesc.empty()) {
672     std::string DLDesc =
673         AsmHelper.TM->getDataLayout()->getStringRepresentation();
674     if (DLDesc != TDesc) {
675       unsigned DiagID = Diags.getCustomDiagID(
676           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
677                                     "expected target description '%1'");
678       Diags.Report(DiagID) << DLDesc << TDesc;
679     }
680   }
681 }
682