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