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