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/FunctionInfo.h"
26 #include "llvm/IR/IRPrintingPasses.h"
27 #include "llvm/IR/LegacyPassManager.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Object/FunctionIndexObjectFile.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/Timer.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include "llvm/Transforms/IPO.h"
41 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
42 #include "llvm/Transforms/Instrumentation.h"
43 #include "llvm/Transforms/ObjCARC.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/Transforms/Utils/SymbolRewriter.h"
46 #include <memory>
47 using namespace clang;
48 using namespace llvm;
49 
50 namespace {
51 
52 class EmitAssemblyHelper {
53   DiagnosticsEngine &Diags;
54   const CodeGenOptions &CodeGenOpts;
55   const clang::TargetOptions &TargetOpts;
56   const LangOptions &LangOpts;
57   Module *TheModule;
58 
59   Timer CodeGenerationTime;
60 
61   mutable legacy::PassManager *CodeGenPasses;
62   mutable legacy::PassManager *PerModulePasses;
63   mutable legacy::FunctionPassManager *PerFunctionPasses;
64 
65 private:
66   TargetIRAnalysis getTargetIRAnalysis() const {
67     if (TM)
68       return TM->getTargetIRAnalysis();
69 
70     return TargetIRAnalysis();
71   }
72 
73   legacy::PassManager *getCodeGenPasses() const {
74     if (!CodeGenPasses) {
75       CodeGenPasses = new legacy::PassManager();
76       CodeGenPasses->add(
77           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
78     }
79     return CodeGenPasses;
80   }
81 
82   legacy::PassManager *getPerModulePasses() const {
83     if (!PerModulePasses) {
84       PerModulePasses = new legacy::PassManager();
85       PerModulePasses->add(
86           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
87     }
88     return PerModulePasses;
89   }
90 
91   legacy::FunctionPassManager *getPerFunctionPasses() const {
92     if (!PerFunctionPasses) {
93       PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
94       PerFunctionPasses->add(
95           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
96     }
97     return PerFunctionPasses;
98   }
99 
100   void CreatePasses(FunctionInfoIndex *FunctionIndex);
101 
102   /// Generates the TargetMachine.
103   /// Returns Null if it is unable to create the target machine.
104   /// Some of our clang tests specify triples which are not built
105   /// into clang. This is okay because these tests check the generated
106   /// IR, and they require DataLayout which depends on the triple.
107   /// In this case, we allow this method to fail and not report an error.
108   /// When MustCreateTM is used, we print an error if we are unable to load
109   /// the requested target.
110   TargetMachine *CreateTargetMachine(bool MustCreateTM);
111 
112   /// Add passes necessary to emit assembly or LLVM IR.
113   ///
114   /// \return True on success.
115   bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
116 
117 public:
118   EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts,
119                      const clang::TargetOptions &TOpts,
120                      const LangOptions &LOpts, 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   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
193   PM.add(createSanitizerCoverageModulePass(Opts));
194 }
195 
196 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
197                                       legacy::PassManagerBase &PM) {
198   const PassManagerBuilderWrapper &BuilderWrapper =
199       static_cast<const PassManagerBuilderWrapper&>(Builder);
200   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
201   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
202   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false, Recover));
203   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
204 }
205 
206 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
207                                             legacy::PassManagerBase &PM) {
208   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true,
209                                             /*Recover*/true));
210   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
211                                           /*Recover*/true));
212 }
213 
214 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
215                                    legacy::PassManagerBase &PM) {
216   const PassManagerBuilderWrapper &BuilderWrapper =
217       static_cast<const PassManagerBuilderWrapper&>(Builder);
218   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
219   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
220 
221   // MemorySanitizer inserts complex instrumentation that mostly follows
222   // the logic of the original code, but operates on "shadow" values.
223   // It can benefit from re-running some general purpose optimization passes.
224   if (Builder.OptLevel > 0) {
225     PM.add(createEarlyCSEPass());
226     PM.add(createReassociatePass());
227     PM.add(createLICMPass());
228     PM.add(createGVNPass());
229     PM.add(createInstructionCombiningPass());
230     PM.add(createDeadStoreEliminationPass());
231   }
232 }
233 
234 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
235                                    legacy::PassManagerBase &PM) {
236   PM.add(createThreadSanitizerPass());
237 }
238 
239 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
240                                      legacy::PassManagerBase &PM) {
241   const PassManagerBuilderWrapper &BuilderWrapper =
242       static_cast<const PassManagerBuilderWrapper&>(Builder);
243   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
244   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
245 }
246 
247 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
248                                          const CodeGenOptions &CodeGenOpts) {
249   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
250   if (!CodeGenOpts.SimplifyLibCalls)
251     TLII->disableAllFunctions();
252   else {
253     // Disable individual libc/libm calls in TargetLibraryInfo.
254     LibFunc::Func F;
255     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
256       if (TLII->getLibFunc(FuncName, F))
257         TLII->setUnavailable(F);
258   }
259 
260   switch (CodeGenOpts.getVecLib()) {
261   case CodeGenOptions::Accelerate:
262     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
263     break;
264   default:
265     break;
266   }
267   return TLII;
268 }
269 
270 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
271                                   legacy::PassManager *MPM) {
272   llvm::SymbolRewriter::RewriteDescriptorList DL;
273 
274   llvm::SymbolRewriter::RewriteMapParser MapParser;
275   for (const auto &MapFile : Opts.RewriteMapFiles)
276     MapParser.parse(MapFile, &DL);
277 
278   MPM->add(createRewriteSymbolsPass(DL));
279 }
280 
281 void EmitAssemblyHelper::CreatePasses(FunctionInfoIndex *FunctionIndex) {
282   if (CodeGenOpts.DisableLLVMPasses)
283     return;
284 
285   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
286   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
287 
288   // Handle disabling of LLVM optimization, where we want to preserve the
289   // internal module before any optimization.
290   if (CodeGenOpts.DisableLLVMOpts) {
291     OptLevel = 0;
292     Inlining = CodeGenOpts.NoInlining;
293   }
294 
295   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
296 
297   // Figure out TargetLibraryInfo.
298   Triple TargetTriple(TheModule->getTargetTriple());
299   PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
300 
301   switch (Inlining) {
302   case CodeGenOptions::NoInlining:
303     break;
304   case CodeGenOptions::NormalInlining: {
305     PMBuilder.Inliner =
306         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
307     break;
308   }
309   case CodeGenOptions::OnlyAlwaysInlining:
310     // Respect always_inline.
311     if (OptLevel == 0)
312       // Do not insert lifetime intrinsics at -O0.
313       PMBuilder.Inliner = createAlwaysInlinerPass(false);
314     else
315       PMBuilder.Inliner = createAlwaysInlinerPass();
316     break;
317   }
318 
319   PMBuilder.OptLevel = OptLevel;
320   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
321   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
322   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
323   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
324 
325   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
326   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
327   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
328   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitFunctionSummary;
329   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
330   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
331 
332   legacy::PassManager *MPM = getPerModulePasses();
333 
334   // If we are performing a ThinLTO importing compile, invoke the LTO
335   // pipeline and pass down the in-memory function index.
336   if (FunctionIndex) {
337     PMBuilder.FunctionIndex = FunctionIndex;
338     PMBuilder.populateThinLTOPassManager(*MPM);
339     return;
340   }
341 
342   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
343                          addAddDiscriminatorsPass);
344 
345   // In ObjC ARC mode, add the main ARC optimization passes.
346   if (LangOpts.ObjCAutoRefCount) {
347     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
348                            addObjCARCExpandPass);
349     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
350                            addObjCARCAPElimPass);
351     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
352                            addObjCARCOptPass);
353   }
354 
355   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
356     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
357                            addBoundsCheckingPass);
358     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
359                            addBoundsCheckingPass);
360   }
361 
362   if (CodeGenOpts.SanitizeCoverageType ||
363       CodeGenOpts.SanitizeCoverageIndirectCalls ||
364       CodeGenOpts.SanitizeCoverageTraceCmp) {
365     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
366                            addSanitizerCoveragePass);
367     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
368                            addSanitizerCoveragePass);
369   }
370 
371   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
372     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
373                            addAddressSanitizerPasses);
374     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
375                            addAddressSanitizerPasses);
376   }
377 
378   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
379     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
380                            addKernelAddressSanitizerPasses);
381     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
382                            addKernelAddressSanitizerPasses);
383   }
384 
385   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
386     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
387                            addMemorySanitizerPass);
388     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
389                            addMemorySanitizerPass);
390   }
391 
392   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
393     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
394                            addThreadSanitizerPass);
395     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
396                            addThreadSanitizerPass);
397   }
398 
399   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
400     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
401                            addDataFlowSanitizerPass);
402     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
403                            addDataFlowSanitizerPass);
404   }
405 
406   // Set up the per-function pass manager.
407   legacy::FunctionPassManager *FPM = getPerFunctionPasses();
408   if (CodeGenOpts.VerifyModule)
409     FPM->add(createVerifierPass());
410   PMBuilder.populateFunctionPassManager(*FPM);
411 
412   // Set up the per-module pass manager.
413   if (!CodeGenOpts.RewriteMapFiles.empty())
414     addSymbolRewriterPass(CodeGenOpts, MPM);
415 
416   if (!CodeGenOpts.DisableGCov &&
417       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
418     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
419     // LLVM's -default-gcov-version flag is set to something invalid.
420     GCOVOptions Options;
421     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
422     Options.EmitData = CodeGenOpts.EmitGcovArcs;
423     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
424     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
425     Options.NoRedZone = CodeGenOpts.DisableRedZone;
426     Options.FunctionNamesInData =
427         !CodeGenOpts.CoverageNoFunctionNamesInData;
428     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
429     MPM->add(createGCOVProfilerPass(Options));
430     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
431       MPM->add(createStripSymbolsPass(true));
432   }
433 
434   if (CodeGenOpts.hasProfileClangInstr()) {
435     InstrProfOptions Options;
436     Options.NoRedZone = CodeGenOpts.DisableRedZone;
437     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
438     MPM->add(createInstrProfilingPass(Options));
439   }
440   if (CodeGenOpts.hasProfileIRInstr()) {
441     if (!CodeGenOpts.InstrProfileOutput.empty())
442       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
443     else
444       PMBuilder.PGOInstrGen = "default.profraw";
445   }
446   if (CodeGenOpts.hasProfileIRUse())
447     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
448 
449   if (!CodeGenOpts.SampleProfileFile.empty())
450     MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
451 
452   PMBuilder.populateModulePassManager(*MPM);
453 }
454 
455 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
456   // Create the TargetMachine for generating code.
457   std::string Error;
458   std::string Triple = TheModule->getTargetTriple();
459   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
460   if (!TheTarget) {
461     if (MustCreateTM)
462       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
463     return nullptr;
464   }
465 
466   unsigned CodeModel =
467     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
468       .Case("small", llvm::CodeModel::Small)
469       .Case("kernel", llvm::CodeModel::Kernel)
470       .Case("medium", llvm::CodeModel::Medium)
471       .Case("large", llvm::CodeModel::Large)
472       .Case("default", llvm::CodeModel::Default)
473       .Default(~0u);
474   assert(CodeModel != ~0u && "invalid code model!");
475   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
476 
477   SmallVector<const char *, 16> BackendArgs;
478   BackendArgs.push_back("clang"); // Fake program name.
479   if (!CodeGenOpts.DebugPass.empty()) {
480     BackendArgs.push_back("-debug-pass");
481     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
482   }
483   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
484     BackendArgs.push_back("-limit-float-precision");
485     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
486   }
487   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
488     BackendArgs.push_back(BackendOption.c_str());
489   BackendArgs.push_back(nullptr);
490   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
491                                     BackendArgs.data());
492 
493   std::string FeaturesStr =
494       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
495 
496   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
497   llvm::Reloc::Model RM = llvm::Reloc::Default;
498   if (CodeGenOpts.RelocationModel == "static") {
499     RM = llvm::Reloc::Static;
500   } else if (CodeGenOpts.RelocationModel == "pic") {
501     RM = llvm::Reloc::PIC_;
502   } else {
503     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
504            "Invalid PIC model!");
505     RM = llvm::Reloc::DynamicNoPIC;
506   }
507 
508   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
509   switch (CodeGenOpts.OptimizationLevel) {
510   default: break;
511   case 0: OptLevel = CodeGenOpt::None; break;
512   case 3: OptLevel = CodeGenOpt::Aggressive; break;
513   }
514 
515   llvm::TargetOptions Options;
516 
517   if (!TargetOpts.Reciprocals.empty())
518     Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
519 
520   Options.ThreadModel =
521     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
522       .Case("posix", llvm::ThreadModel::POSIX)
523       .Case("single", llvm::ThreadModel::Single);
524 
525   // Set float ABI type.
526   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
527           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
528          "Invalid Floating Point ABI!");
529   Options.FloatABIType =
530       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
531           .Case("soft", llvm::FloatABI::Soft)
532           .Case("softfp", llvm::FloatABI::Soft)
533           .Case("hard", llvm::FloatABI::Hard)
534           .Default(llvm::FloatABI::Default);
535 
536   // Set FP fusion mode.
537   switch (CodeGenOpts.getFPContractMode()) {
538   case CodeGenOptions::FPC_Off:
539     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
540     break;
541   case CodeGenOptions::FPC_On:
542     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
543     break;
544   case CodeGenOptions::FPC_Fast:
545     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
546     break;
547   }
548 
549   Options.UseInitArray = CodeGenOpts.UseInitArray;
550   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
551   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
552 
553   // Set EABI version.
554   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(CodeGenOpts.EABIVersion)
555                             .Case("4", llvm::EABI::EABI4)
556                             .Case("5", llvm::EABI::EABI5)
557                             .Case("gnu", llvm::EABI::GNU)
558                             .Default(llvm::EABI::Default);
559 
560   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
561   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
562   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
563   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
564   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
565   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
566   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
567   Options.FunctionSections = CodeGenOpts.FunctionSections;
568   Options.DataSections = CodeGenOpts.DataSections;
569   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
570   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
571   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
572 
573   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
574   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
575   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
576   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
577   Options.MCOptions.MCIncrementalLinkerCompatible =
578       CodeGenOpts.IncrementalLinkerCompatible;
579   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
580   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
581   Options.MCOptions.ABIName = TargetOpts.ABI;
582 
583   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
584                                                      FeaturesStr, Options,
585                                                      RM, CM, OptLevel);
586 
587   return TM;
588 }
589 
590 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
591                                        raw_pwrite_stream &OS) {
592 
593   // Create the code generator passes.
594   legacy::PassManager *PM = getCodeGenPasses();
595 
596   // Add LibraryInfo.
597   llvm::Triple TargetTriple(TheModule->getTargetTriple());
598   std::unique_ptr<TargetLibraryInfoImpl> TLII(
599       createTLII(TargetTriple, CodeGenOpts));
600   PM->add(new TargetLibraryInfoWrapperPass(*TLII));
601 
602   // Normal mode, emit a .s or .o file by running the code generator. Note,
603   // this also adds codegenerator level optimization passes.
604   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
605   if (Action == Backend_EmitObj)
606     CGFT = TargetMachine::CGFT_ObjectFile;
607   else if (Action == Backend_EmitMCNull)
608     CGFT = TargetMachine::CGFT_Null;
609   else
610     assert(Action == Backend_EmitAssembly && "Invalid action!");
611 
612   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
613   // "codegen" passes so that it isn't run multiple times when there is
614   // inlining happening.
615   if (CodeGenOpts.OptimizationLevel > 0)
616     PM->add(createObjCARCContractPass());
617 
618   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
619                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
620     Diags.Report(diag::err_fe_unable_to_interface_with_target);
621     return false;
622   }
623 
624   return true;
625 }
626 
627 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
628                                       raw_pwrite_stream *OS) {
629   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
630 
631   bool UsesCodeGen = (Action != Backend_EmitNothing &&
632                       Action != Backend_EmitBC &&
633                       Action != Backend_EmitLL);
634   if (!TM)
635     TM.reset(CreateTargetMachine(UsesCodeGen));
636 
637   if (UsesCodeGen && !TM)
638     return;
639   if (TM)
640     TheModule->setDataLayout(TM->createDataLayout());
641 
642   // If we are performing a ThinLTO importing compile, load the function
643   // index into memory and pass it into CreatePasses, which will add it
644   // to the PassManagerBuilder and invoke LTO passes.
645   std::unique_ptr<FunctionInfoIndex> FunctionIndex;
646   if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
647     ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
648         llvm::getFunctionIndexForFile(CodeGenOpts.ThinLTOIndexFile,
649                                       [&](const DiagnosticInfo &DI) {
650                                         TheModule->getContext().diagnose(DI);
651                                       });
652     if (std::error_code EC = IndexOrErr.getError()) {
653       std::string Error = EC.message();
654       errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile
655              << "': " << Error << "\n";
656       return;
657     }
658     FunctionIndex = std::move(IndexOrErr.get());
659     assert(FunctionIndex && "Expected non-empty function index");
660   }
661 
662   CreatePasses(FunctionIndex.get());
663 
664   switch (Action) {
665   case Backend_EmitNothing:
666     break;
667 
668   case Backend_EmitBC:
669     getPerModulePasses()->add(createBitcodeWriterPass(
670         *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitFunctionSummary));
671     break;
672 
673   case Backend_EmitLL:
674     getPerModulePasses()->add(
675         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
676     break;
677 
678   default:
679     if (!AddEmitPasses(Action, *OS))
680       return;
681   }
682 
683   // Before executing passes, print the final values of the LLVM options.
684   cl::PrintOptionValues();
685 
686   // Run passes. For now we do all passes at once, but eventually we
687   // would like to have the option of streaming code generation.
688 
689   if (PerFunctionPasses) {
690     PrettyStackTraceString CrashInfo("Per-function optimization");
691 
692     PerFunctionPasses->doInitialization();
693     for (Function &F : *TheModule)
694       if (!F.isDeclaration())
695         PerFunctionPasses->run(F);
696     PerFunctionPasses->doFinalization();
697   }
698 
699   if (PerModulePasses) {
700     PrettyStackTraceString CrashInfo("Per-module optimization passes");
701     PerModulePasses->run(*TheModule);
702   }
703 
704   if (CodeGenPasses) {
705     PrettyStackTraceString CrashInfo("Code generation");
706     CodeGenPasses->run(*TheModule);
707   }
708 }
709 
710 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
711                               const CodeGenOptions &CGOpts,
712                               const clang::TargetOptions &TOpts,
713                               const LangOptions &LOpts, const llvm::DataLayout &TDesc,
714                               Module *M, BackendAction Action,
715                               raw_pwrite_stream *OS) {
716   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
717 
718   AsmHelper.EmitAssembly(Action, OS);
719 
720   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
721   // DataLayout.
722   if (AsmHelper.TM) {
723     std::string DLDesc = M->getDataLayout().getStringRepresentation();
724     if (DLDesc != TDesc.getStringRepresentation()) {
725       unsigned DiagID = Diags.getCustomDiagID(
726           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
727                                     "expected target description '%1'");
728       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
729     }
730   }
731 }
732