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