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