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