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