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/ADT/Triple.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeWriterPass.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/CodeGen/SchedulerRegistry.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/ModuleSummaryIndex.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/Timer.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Instrumentation.h"
45 #include "llvm/Transforms/ObjCARC.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Scalar/GVN.h"
48 #include "llvm/Transforms/Utils/SymbolRewriter.h"
49 #include <memory>
50 using namespace clang;
51 using namespace llvm;
52 
53 namespace {
54 
55 class EmitAssemblyHelper {
56   DiagnosticsEngine &Diags;
57   const CodeGenOptions &CodeGenOpts;
58   const clang::TargetOptions &TargetOpts;
59   const LangOptions &LangOpts;
60   Module *TheModule;
61 
62   Timer CodeGenerationTime;
63 
64   mutable legacy::PassManager *CodeGenPasses;
65   mutable legacy::PassManager *PerModulePasses;
66   mutable legacy::FunctionPassManager *PerFunctionPasses;
67 
68 private:
69   TargetIRAnalysis getTargetIRAnalysis() const {
70     if (TM)
71       return TM->getTargetIRAnalysis();
72 
73     return TargetIRAnalysis();
74   }
75 
76   legacy::PassManager *getCodeGenPasses() const {
77     if (!CodeGenPasses) {
78       CodeGenPasses = new legacy::PassManager();
79       CodeGenPasses->add(
80           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
81     }
82     return CodeGenPasses;
83   }
84 
85   legacy::PassManager *getPerModulePasses() const {
86     if (!PerModulePasses) {
87       PerModulePasses = new legacy::PassManager();
88       PerModulePasses->add(
89           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
90     }
91     return PerModulePasses;
92   }
93 
94   legacy::FunctionPassManager *getPerFunctionPasses() const {
95     if (!PerFunctionPasses) {
96       PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
97       PerFunctionPasses->add(
98           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
99     }
100     return PerFunctionPasses;
101   }
102 
103   /// Set LLVM command line options passed through -backend-option.
104   void setCommandLineOpts();
105 
106   void CreatePasses(ModuleSummaryIndex *ModuleSummary);
107 
108   /// Generates the TargetMachine.
109   /// Returns Null if it is unable to create the target machine.
110   /// Some of our clang tests specify triples which are not built
111   /// into clang. This is okay because these tests check the generated
112   /// IR, and they require DataLayout which depends on the triple.
113   /// In this case, we allow this method to fail and not report an error.
114   /// When MustCreateTM is used, we print an error if we are unable to load
115   /// the requested target.
116   TargetMachine *CreateTargetMachine(bool MustCreateTM);
117 
118   /// Add passes necessary to emit assembly or LLVM IR.
119   ///
120   /// \return True on success.
121   bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
122 
123 public:
124   EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts,
125                      const clang::TargetOptions &TOpts,
126                      const LangOptions &LOpts, Module *M)
127       : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
128         TheModule(M), CodeGenerationTime("Code Generation Time"),
129         CodeGenPasses(nullptr), PerModulePasses(nullptr),
130         PerFunctionPasses(nullptr) {}
131 
132   ~EmitAssemblyHelper() {
133     delete CodeGenPasses;
134     delete PerModulePasses;
135     delete PerFunctionPasses;
136     if (CodeGenOpts.DisableFree)
137       BuryPointer(std::move(TM));
138   }
139 
140   std::unique_ptr<TargetMachine> TM;
141 
142   void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS);
143 };
144 
145 // We need this wrapper to access LangOpts and CGOpts from extension functions
146 // that we add to the PassManagerBuilder.
147 class PassManagerBuilderWrapper : public PassManagerBuilder {
148 public:
149   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
150                             const LangOptions &LangOpts)
151       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
152   const CodeGenOptions &getCGOpts() const { return CGOpts; }
153   const LangOptions &getLangOpts() const { return LangOpts; }
154 private:
155   const CodeGenOptions &CGOpts;
156   const LangOptions &LangOpts;
157 };
158 
159 }
160 
161 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
162   if (Builder.OptLevel > 0)
163     PM.add(createObjCARCAPElimPass());
164 }
165 
166 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
167   if (Builder.OptLevel > 0)
168     PM.add(createObjCARCExpandPass());
169 }
170 
171 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
172   if (Builder.OptLevel > 0)
173     PM.add(createObjCARCOptPass());
174 }
175 
176 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
177                                      legacy::PassManagerBase &PM) {
178   PM.add(createAddDiscriminatorsPass());
179 }
180 
181 static void addInstructionCombiningPass(const PassManagerBuilder &Builder,
182                                         legacy::PassManagerBase &PM) {
183   PM.add(createInstructionCombiningPass());
184 }
185 
186 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
187                                   legacy::PassManagerBase &PM) {
188   PM.add(createBoundsCheckingPass());
189 }
190 
191 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
192                                      legacy::PassManagerBase &PM) {
193   const PassManagerBuilderWrapper &BuilderWrapper =
194       static_cast<const PassManagerBuilderWrapper&>(Builder);
195   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
196   SanitizerCoverageOptions Opts;
197   Opts.CoverageType =
198       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
199   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
200   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
201   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
202   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
203   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
204   PM.add(createSanitizerCoverageModulePass(Opts));
205 }
206 
207 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
208                                       legacy::PassManagerBase &PM) {
209   const PassManagerBuilderWrapper &BuilderWrapper =
210       static_cast<const PassManagerBuilderWrapper&>(Builder);
211   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
212   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
213   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
214   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
215                                             UseAfterScope));
216   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
217 }
218 
219 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
220                                             legacy::PassManagerBase &PM) {
221   PM.add(createAddressSanitizerFunctionPass(
222       /*CompileKernel*/ true,
223       /*Recover*/ true, /*UseAfterScope*/ false));
224   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
225                                           /*Recover*/true));
226 }
227 
228 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
229                                    legacy::PassManagerBase &PM) {
230   const PassManagerBuilderWrapper &BuilderWrapper =
231       static_cast<const PassManagerBuilderWrapper&>(Builder);
232   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
233   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
234 
235   // MemorySanitizer inserts complex instrumentation that mostly follows
236   // the logic of the original code, but operates on "shadow" values.
237   // It can benefit from re-running some general purpose optimization passes.
238   if (Builder.OptLevel > 0) {
239     PM.add(createEarlyCSEPass());
240     PM.add(createReassociatePass());
241     PM.add(createLICMPass());
242     PM.add(createGVNPass());
243     PM.add(createInstructionCombiningPass());
244     PM.add(createDeadStoreEliminationPass());
245   }
246 }
247 
248 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
249                                    legacy::PassManagerBase &PM) {
250   PM.add(createThreadSanitizerPass());
251 }
252 
253 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
254                                      legacy::PassManagerBase &PM) {
255   const PassManagerBuilderWrapper &BuilderWrapper =
256       static_cast<const PassManagerBuilderWrapper&>(Builder);
257   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
258   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
259 }
260 
261 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
262                                        legacy::PassManagerBase &PM) {
263   const PassManagerBuilderWrapper &BuilderWrapper =
264       static_cast<const PassManagerBuilderWrapper&>(Builder);
265   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
266   EfficiencySanitizerOptions Opts;
267   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
268     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
269   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
270     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
271   PM.add(createEfficiencySanitizerPass(Opts));
272 }
273 
274 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
275                                          const CodeGenOptions &CodeGenOpts) {
276   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
277   if (!CodeGenOpts.SimplifyLibCalls)
278     TLII->disableAllFunctions();
279   else {
280     // Disable individual libc/libm calls in TargetLibraryInfo.
281     LibFunc::Func F;
282     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
283       if (TLII->getLibFunc(FuncName, F))
284         TLII->setUnavailable(F);
285   }
286 
287   switch (CodeGenOpts.getVecLib()) {
288   case CodeGenOptions::Accelerate:
289     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
290     break;
291   default:
292     break;
293   }
294   return TLII;
295 }
296 
297 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
298                                   legacy::PassManager *MPM) {
299   llvm::SymbolRewriter::RewriteDescriptorList DL;
300 
301   llvm::SymbolRewriter::RewriteMapParser MapParser;
302   for (const auto &MapFile : Opts.RewriteMapFiles)
303     MapParser.parse(MapFile, &DL);
304 
305   MPM->add(createRewriteSymbolsPass(DL));
306 }
307 
308 void EmitAssemblyHelper::CreatePasses(ModuleSummaryIndex *ModuleSummary) {
309   if (CodeGenOpts.DisableLLVMPasses)
310     return;
311 
312   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
313   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
314 
315   // Handle disabling of LLVM optimization, where we want to preserve the
316   // internal module before any optimization.
317   if (CodeGenOpts.DisableLLVMOpts) {
318     OptLevel = 0;
319     Inlining = CodeGenOpts.NoInlining;
320   }
321 
322   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
323 
324   // Figure out TargetLibraryInfo.
325   Triple TargetTriple(TheModule->getTargetTriple());
326   PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
327 
328   switch (Inlining) {
329   case CodeGenOptions::NoInlining:
330     break;
331   case CodeGenOptions::NormalInlining: {
332     PMBuilder.Inliner =
333         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
334     break;
335   }
336   case CodeGenOptions::OnlyAlwaysInlining:
337     // Respect always_inline.
338     if (OptLevel == 0)
339       // Do not insert lifetime intrinsics at -O0.
340       PMBuilder.Inliner = createAlwaysInlinerPass(false);
341     else
342       PMBuilder.Inliner = createAlwaysInlinerPass();
343     break;
344   }
345 
346   PMBuilder.OptLevel = OptLevel;
347   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
348   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
349   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
350   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
351 
352   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
353   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
354   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
355   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
356   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
357   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
358 
359   legacy::PassManager *MPM = getPerModulePasses();
360 
361   // If we are performing a ThinLTO importing compile, invoke the LTO
362   // pipeline and pass down the in-memory module summary index.
363   if (ModuleSummary) {
364     PMBuilder.ModuleSummary = ModuleSummary;
365     PMBuilder.populateThinLTOPassManager(*MPM);
366     return;
367   }
368 
369   // Add target-specific passes that need to run as early as possible.
370   if (TM)
371     PMBuilder.addExtension(
372         PassManagerBuilder::EP_EarlyAsPossible,
373         [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
374           TM->addEarlyAsPossiblePasses(PM);
375         });
376 
377   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
378                          addAddDiscriminatorsPass);
379 
380   // In ObjC ARC mode, add the main ARC optimization passes.
381   if (LangOpts.ObjCAutoRefCount) {
382     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
383                            addObjCARCExpandPass);
384     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
385                            addObjCARCAPElimPass);
386     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
387                            addObjCARCOptPass);
388   }
389 
390   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
391     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
392                            addBoundsCheckingPass);
393     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
394                            addBoundsCheckingPass);
395   }
396 
397   if (CodeGenOpts.SanitizeCoverageType ||
398       CodeGenOpts.SanitizeCoverageIndirectCalls ||
399       CodeGenOpts.SanitizeCoverageTraceCmp) {
400     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
401                            addSanitizerCoveragePass);
402     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
403                            addSanitizerCoveragePass);
404   }
405 
406   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
407     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
408                            addAddressSanitizerPasses);
409     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
410                            addAddressSanitizerPasses);
411   }
412 
413   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
414     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
415                            addKernelAddressSanitizerPasses);
416     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
417                            addKernelAddressSanitizerPasses);
418   }
419 
420   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
421     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
422                            addMemorySanitizerPass);
423     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
424                            addMemorySanitizerPass);
425   }
426 
427   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
428     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
429                            addThreadSanitizerPass);
430     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
431                            addThreadSanitizerPass);
432   }
433 
434   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
435     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
436                            addDataFlowSanitizerPass);
437     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
438                            addDataFlowSanitizerPass);
439   }
440 
441   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
442     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
443                            addEfficiencySanitizerPass);
444     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
445                            addEfficiencySanitizerPass);
446   }
447 
448   // Set up the per-function pass manager.
449   legacy::FunctionPassManager *FPM = getPerFunctionPasses();
450   if (CodeGenOpts.VerifyModule)
451     FPM->add(createVerifierPass());
452 
453   // Set up the per-module pass manager.
454   if (!CodeGenOpts.RewriteMapFiles.empty())
455     addSymbolRewriterPass(CodeGenOpts, MPM);
456 
457   if (!CodeGenOpts.DisableGCov &&
458       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
459     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
460     // LLVM's -default-gcov-version flag is set to something invalid.
461     GCOVOptions Options;
462     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
463     Options.EmitData = CodeGenOpts.EmitGcovArcs;
464     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
465     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
466     Options.NoRedZone = CodeGenOpts.DisableRedZone;
467     Options.FunctionNamesInData =
468         !CodeGenOpts.CoverageNoFunctionNamesInData;
469     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
470     MPM->add(createGCOVProfilerPass(Options));
471     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
472       MPM->add(createStripSymbolsPass(true));
473   }
474 
475   if (CodeGenOpts.hasProfileClangInstr()) {
476     InstrProfOptions Options;
477     Options.NoRedZone = CodeGenOpts.DisableRedZone;
478     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
479     MPM->add(createInstrProfilingLegacyPass(Options));
480   }
481   if (CodeGenOpts.hasProfileIRInstr()) {
482     if (!CodeGenOpts.InstrProfileOutput.empty())
483       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
484     else
485       PMBuilder.PGOInstrGen = "default.profraw";
486   }
487   if (CodeGenOpts.hasProfileIRUse())
488     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
489 
490   if (!CodeGenOpts.SampleProfileFile.empty()) {
491     MPM->add(createPruneEHPass());
492     MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
493     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
494                            addInstructionCombiningPass);
495   }
496 
497   PMBuilder.populateFunctionPassManager(*FPM);
498   PMBuilder.populateModulePassManager(*MPM);
499 }
500 
501 void EmitAssemblyHelper::setCommandLineOpts() {
502   SmallVector<const char *, 16> BackendArgs;
503   BackendArgs.push_back("clang"); // Fake program name.
504   if (!CodeGenOpts.DebugPass.empty()) {
505     BackendArgs.push_back("-debug-pass");
506     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
507   }
508   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
509     BackendArgs.push_back("-limit-float-precision");
510     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
511   }
512   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
513     BackendArgs.push_back(BackendOption.c_str());
514   BackendArgs.push_back(nullptr);
515   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
516                                     BackendArgs.data());
517 }
518 
519 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
520   // Create the TargetMachine for generating code.
521   std::string Error;
522   std::string Triple = TheModule->getTargetTriple();
523   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
524   if (!TheTarget) {
525     if (MustCreateTM)
526       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
527     return nullptr;
528   }
529 
530   unsigned CodeModel =
531     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
532       .Case("small", llvm::CodeModel::Small)
533       .Case("kernel", llvm::CodeModel::Kernel)
534       .Case("medium", llvm::CodeModel::Medium)
535       .Case("large", llvm::CodeModel::Large)
536       .Case("default", llvm::CodeModel::Default)
537       .Default(~0u);
538   assert(CodeModel != ~0u && "invalid code model!");
539   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
540 
541   std::string FeaturesStr =
542       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
543 
544   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
545   llvm::Optional<llvm::Reloc::Model> RM;
546   if (CodeGenOpts.RelocationModel == "static") {
547     RM = llvm::Reloc::Static;
548   } else if (CodeGenOpts.RelocationModel == "pic") {
549     RM = llvm::Reloc::PIC_;
550   } else {
551     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
552            "Invalid PIC model!");
553     RM = llvm::Reloc::DynamicNoPIC;
554   }
555 
556   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
557   switch (CodeGenOpts.OptimizationLevel) {
558   default: break;
559   case 0: OptLevel = CodeGenOpt::None; break;
560   case 3: OptLevel = CodeGenOpt::Aggressive; break;
561   }
562 
563   llvm::TargetOptions Options;
564 
565   if (!TargetOpts.Reciprocals.empty())
566     Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
567 
568   Options.ThreadModel =
569     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
570       .Case("posix", llvm::ThreadModel::POSIX)
571       .Case("single", llvm::ThreadModel::Single);
572 
573   // Set float ABI type.
574   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
575           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
576          "Invalid Floating Point ABI!");
577   Options.FloatABIType =
578       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
579           .Case("soft", llvm::FloatABI::Soft)
580           .Case("softfp", llvm::FloatABI::Soft)
581           .Case("hard", llvm::FloatABI::Hard)
582           .Default(llvm::FloatABI::Default);
583 
584   // Set FP fusion mode.
585   switch (CodeGenOpts.getFPContractMode()) {
586   case CodeGenOptions::FPC_Off:
587     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
588     break;
589   case CodeGenOptions::FPC_On:
590     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
591     break;
592   case CodeGenOptions::FPC_Fast:
593     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
594     break;
595   }
596 
597   Options.UseInitArray = CodeGenOpts.UseInitArray;
598   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
599   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
600   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
601 
602   // Set EABI version.
603   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
604                             .Case("4", llvm::EABI::EABI4)
605                             .Case("5", llvm::EABI::EABI5)
606                             .Case("gnu", llvm::EABI::GNU)
607                             .Default(llvm::EABI::Default);
608 
609   if (LangOpts.SjLjExceptions)
610     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
611 
612   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
613   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
614   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
615   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
616   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
617   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
618   Options.FunctionSections = CodeGenOpts.FunctionSections;
619   Options.DataSections = CodeGenOpts.DataSections;
620   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
621   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
622   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
623 
624   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
625   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
626   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
627   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
628   Options.MCOptions.MCIncrementalLinkerCompatible =
629       CodeGenOpts.IncrementalLinkerCompatible;
630   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
631   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
632   Options.MCOptions.ABIName = TargetOpts.ABI;
633 
634   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
635                                                      FeaturesStr, Options,
636                                                      RM, CM, OptLevel);
637 
638   return TM;
639 }
640 
641 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
642                                        raw_pwrite_stream &OS) {
643 
644   // Create the code generator passes.
645   legacy::PassManager *PM = getCodeGenPasses();
646 
647   // Add LibraryInfo.
648   llvm::Triple TargetTriple(TheModule->getTargetTriple());
649   std::unique_ptr<TargetLibraryInfoImpl> TLII(
650       createTLII(TargetTriple, CodeGenOpts));
651   PM->add(new TargetLibraryInfoWrapperPass(*TLII));
652 
653   // Normal mode, emit a .s or .o file by running the code generator. Note,
654   // this also adds codegenerator level optimization passes.
655   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
656   if (Action == Backend_EmitObj)
657     CGFT = TargetMachine::CGFT_ObjectFile;
658   else if (Action == Backend_EmitMCNull)
659     CGFT = TargetMachine::CGFT_Null;
660   else
661     assert(Action == Backend_EmitAssembly && "Invalid action!");
662 
663   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
664   // "codegen" passes so that it isn't run multiple times when there is
665   // inlining happening.
666   if (CodeGenOpts.OptimizationLevel > 0)
667     PM->add(createObjCARCContractPass());
668 
669   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
670                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
671     Diags.Report(diag::err_fe_unable_to_interface_with_target);
672     return false;
673   }
674 
675   return true;
676 }
677 
678 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
679                                       raw_pwrite_stream *OS) {
680   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
681 
682   setCommandLineOpts();
683 
684   bool UsesCodeGen = (Action != Backend_EmitNothing &&
685                       Action != Backend_EmitBC &&
686                       Action != Backend_EmitLL);
687   if (!TM)
688     TM.reset(CreateTargetMachine(UsesCodeGen));
689 
690   if (UsesCodeGen && !TM)
691     return;
692   if (TM)
693     TheModule->setDataLayout(TM->createDataLayout());
694 
695   // If we are performing a ThinLTO importing compile, load the function
696   // index into memory and pass it into CreatePasses, which will add it
697   // to the PassManagerBuilder and invoke LTO passes.
698   std::unique_ptr<ModuleSummaryIndex> ModuleSummary;
699   if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
700     ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
701         llvm::getModuleSummaryIndexForFile(
702             CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) {
703               TheModule->getContext().diagnose(DI);
704             });
705     if (std::error_code EC = IndexOrErr.getError()) {
706       std::string Error = EC.message();
707       errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile
708              << "': " << Error << "\n";
709       return;
710     }
711     ModuleSummary = std::move(IndexOrErr.get());
712     assert(ModuleSummary && "Expected non-empty module summary index");
713   }
714 
715   CreatePasses(ModuleSummary.get());
716 
717   switch (Action) {
718   case Backend_EmitNothing:
719     break;
720 
721   case Backend_EmitBC:
722     getPerModulePasses()->add(createBitcodeWriterPass(
723         *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex,
724         CodeGenOpts.EmitSummaryIndex));
725     break;
726 
727   case Backend_EmitLL:
728     getPerModulePasses()->add(
729         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
730     break;
731 
732   default:
733     if (!AddEmitPasses(Action, *OS))
734       return;
735   }
736 
737   // Before executing passes, print the final values of the LLVM options.
738   cl::PrintOptionValues();
739 
740   // Run passes. For now we do all passes at once, but eventually we
741   // would like to have the option of streaming code generation.
742 
743   if (PerFunctionPasses) {
744     PrettyStackTraceString CrashInfo("Per-function optimization");
745 
746     PerFunctionPasses->doInitialization();
747     for (Function &F : *TheModule)
748       if (!F.isDeclaration())
749         PerFunctionPasses->run(F);
750     PerFunctionPasses->doFinalization();
751   }
752 
753   if (PerModulePasses) {
754     PrettyStackTraceString CrashInfo("Per-module optimization passes");
755     PerModulePasses->run(*TheModule);
756   }
757 
758   if (CodeGenPasses) {
759     PrettyStackTraceString CrashInfo("Code generation");
760     CodeGenPasses->run(*TheModule);
761   }
762 }
763 
764 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
765                               const CodeGenOptions &CGOpts,
766                               const clang::TargetOptions &TOpts,
767                               const LangOptions &LOpts, const llvm::DataLayout &TDesc,
768                               Module *M, BackendAction Action,
769                               raw_pwrite_stream *OS) {
770   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
771 
772   AsmHelper.EmitAssembly(Action, OS);
773 
774   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
775   // DataLayout.
776   if (AsmHelper.TM) {
777     std::string DLDesc = M->getDataLayout().getStringRepresentation();
778     if (DLDesc != TDesc.getStringRepresentation()) {
779       unsigned DiagID = Diags.getCustomDiagID(
780           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
781                                     "expected target description '%1'");
782       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
783     }
784   }
785 }
786 
787 static const char* getSectionNameForBitcode(const Triple &T) {
788   switch (T.getObjectFormat()) {
789   case Triple::MachO:
790     return "__LLVM,__bitcode";
791   case Triple::COFF:
792   case Triple::ELF:
793   case Triple::UnknownObjectFormat:
794     return ".llvmbc";
795   }
796   llvm_unreachable("Unimplemented ObjectFormatType");
797 }
798 
799 static const char* getSectionNameForCommandline(const Triple &T) {
800   switch (T.getObjectFormat()) {
801   case Triple::MachO:
802     return "__LLVM,__cmdline";
803   case Triple::COFF:
804   case Triple::ELF:
805   case Triple::UnknownObjectFormat:
806     return ".llvmcmd";
807   }
808   llvm_unreachable("Unimplemented ObjectFormatType");
809 }
810 
811 // With -fembed-bitcode, save a copy of the llvm IR as data in the
812 // __LLVM,__bitcode section.
813 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
814                          llvm::MemoryBufferRef Buf) {
815   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
816     return;
817 
818   // Save llvm.compiler.used and remote it.
819   SmallVector<Constant*, 2> UsedArray;
820   SmallSet<GlobalValue*, 4> UsedGlobals;
821   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
822   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
823   for (auto *GV : UsedGlobals) {
824     if (GV->getName() != "llvm.embedded.module" &&
825         GV->getName() != "llvm.cmdline")
826       UsedArray.push_back(
827           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
828   }
829   if (Used)
830     Used->eraseFromParent();
831 
832   // Embed the bitcode for the llvm module.
833   std::string Data;
834   ArrayRef<uint8_t> ModuleData;
835   Triple T(M->getTargetTriple());
836   // Create a constant that contains the bitcode.
837   // In case of embedding a marker, ignore the input Buf and use the empty
838   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
839   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
840     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
841                    (const unsigned char *)Buf.getBufferEnd())) {
842       // If the input is LLVM Assembly, bitcode is produced by serializing
843       // the module. Use-lists order need to be perserved in this case.
844       llvm::raw_string_ostream OS(Data);
845       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
846       ModuleData =
847           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
848     } else
849       // If the input is LLVM bitcode, write the input byte stream directly.
850       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
851                                      Buf.getBufferSize());
852   }
853   llvm::Constant *ModuleConstant =
854       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
855   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
856       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
857       ModuleConstant);
858   GV->setSection(getSectionNameForBitcode(T));
859   UsedArray.push_back(
860       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
861   if (llvm::GlobalVariable *Old =
862           M->getGlobalVariable("llvm.embedded.module", true)) {
863     assert(Old->hasOneUse() &&
864            "llvm.embedded.module can only be used once in llvm.compiler.used");
865     GV->takeName(Old);
866     Old->eraseFromParent();
867   } else {
868     GV->setName("llvm.embedded.module");
869   }
870 
871   // Skip if only bitcode needs to be embedded.
872   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
873     // Embed command-line options.
874     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
875                               CGOpts.CmdArgs.size());
876     llvm::Constant *CmdConstant =
877       llvm::ConstantDataArray::get(M->getContext(), CmdData);
878     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
879                                   llvm::GlobalValue::PrivateLinkage,
880                                   CmdConstant);
881     GV->setSection(getSectionNameForCommandline(T));
882     UsedArray.push_back(
883         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
884     if (llvm::GlobalVariable *Old =
885             M->getGlobalVariable("llvm.cmdline", true)) {
886       assert(Old->hasOneUse() &&
887              "llvm.cmdline can only be used once in llvm.compiler.used");
888       GV->takeName(Old);
889       Old->eraseFromParent();
890     } else {
891       GV->setName("llvm.cmdline");
892     }
893   }
894 
895   if (UsedArray.empty())
896     return;
897 
898   // Recreate llvm.compiler.used.
899   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
900   auto *NewUsed = new GlobalVariable(
901       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
902       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
903   NewUsed->setSection("llvm.metadata");
904 }
905