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