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