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("codegen", "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.  This needs to be added to MPM and FPM
302   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
303   // are inserted before PMBuilder ones - they'd get the default-constructed
304   // TLI with an unknown target otherwise.
305   Triple TargetTriple(TheModule->getTargetTriple());
306   std::unique_ptr<TargetLibraryInfoImpl> TLII(
307       createTLII(TargetTriple, CodeGenOpts));
308 
309   switch (Inlining) {
310   case CodeGenOptions::NoInlining:
311     break;
312   case CodeGenOptions::NormalInlining:
313   case CodeGenOptions::OnlyHintInlining: {
314     PMBuilder.Inliner =
315         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
316     break;
317   }
318   case CodeGenOptions::OnlyAlwaysInlining:
319     // Respect always_inline.
320     if (OptLevel == 0)
321       // Do not insert lifetime intrinsics at -O0.
322       PMBuilder.Inliner = createAlwaysInlinerLegacyPass(false);
323     else
324       PMBuilder.Inliner = createAlwaysInlinerLegacyPass();
325     break;
326   }
327 
328   PMBuilder.OptLevel = OptLevel;
329   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
330   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
331   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
332   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
333 
334   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
335   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
336   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
337   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
338   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
339 
340   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
341 
342   // Add target-specific passes that need to run as early as possible.
343   if (TM)
344     PMBuilder.addExtension(
345         PassManagerBuilder::EP_EarlyAsPossible,
346         [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
347           TM->addEarlyAsPossiblePasses(PM);
348         });
349 
350   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
351                          addAddDiscriminatorsPass);
352 
353   // In ObjC ARC mode, add the main ARC optimization passes.
354   if (LangOpts.ObjCAutoRefCount) {
355     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
356                            addObjCARCExpandPass);
357     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
358                            addObjCARCAPElimPass);
359     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
360                            addObjCARCOptPass);
361   }
362 
363   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
364     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
365                            addBoundsCheckingPass);
366     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
367                            addBoundsCheckingPass);
368   }
369 
370   if (CodeGenOpts.SanitizeCoverageType ||
371       CodeGenOpts.SanitizeCoverageIndirectCalls ||
372       CodeGenOpts.SanitizeCoverageTraceCmp) {
373     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
374                            addSanitizerCoveragePass);
375     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
376                            addSanitizerCoveragePass);
377   }
378 
379   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
380     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
381                            addAddressSanitizerPasses);
382     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
383                            addAddressSanitizerPasses);
384   }
385 
386   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
387     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
388                            addKernelAddressSanitizerPasses);
389     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
390                            addKernelAddressSanitizerPasses);
391   }
392 
393   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
394     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
395                            addMemorySanitizerPass);
396     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
397                            addMemorySanitizerPass);
398   }
399 
400   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
401     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
402                            addThreadSanitizerPass);
403     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
404                            addThreadSanitizerPass);
405   }
406 
407   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
408     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
409                            addDataFlowSanitizerPass);
410     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
411                            addDataFlowSanitizerPass);
412   }
413 
414   if (LangOpts.CoroutinesTS)
415     addCoroutinePassesToExtensionPoints(PMBuilder);
416 
417   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
418     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
419                            addEfficiencySanitizerPass);
420     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
421                            addEfficiencySanitizerPass);
422   }
423 
424   // Set up the per-function pass manager.
425   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
426   if (CodeGenOpts.VerifyModule)
427     FPM.add(createVerifierPass());
428 
429   // Set up the per-module pass manager.
430   if (!CodeGenOpts.RewriteMapFiles.empty())
431     addSymbolRewriterPass(CodeGenOpts, &MPM);
432 
433   if (!CodeGenOpts.DisableGCov &&
434       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
435     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
436     // LLVM's -default-gcov-version flag is set to something invalid.
437     GCOVOptions Options;
438     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
439     Options.EmitData = CodeGenOpts.EmitGcovArcs;
440     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
441     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
442     Options.NoRedZone = CodeGenOpts.DisableRedZone;
443     Options.FunctionNamesInData =
444         !CodeGenOpts.CoverageNoFunctionNamesInData;
445     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
446     MPM.add(createGCOVProfilerPass(Options));
447     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
448       MPM.add(createStripSymbolsPass(true));
449   }
450 
451   if (CodeGenOpts.hasProfileClangInstr()) {
452     InstrProfOptions Options;
453     Options.NoRedZone = CodeGenOpts.DisableRedZone;
454     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
455     MPM.add(createInstrProfilingLegacyPass(Options));
456   }
457   if (CodeGenOpts.hasProfileIRInstr()) {
458     PMBuilder.EnablePGOInstrGen = true;
459     if (!CodeGenOpts.InstrProfileOutput.empty())
460       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
461     else
462       PMBuilder.PGOInstrGen = "default_%m.profraw";
463   }
464   if (CodeGenOpts.hasProfileIRUse())
465     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
466 
467   if (!CodeGenOpts.SampleProfileFile.empty()) {
468     MPM.add(createPruneEHPass());
469     MPM.add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
470   }
471 
472   PMBuilder.populateFunctionPassManager(FPM);
473   PMBuilder.populateModulePassManager(MPM);
474 }
475 
476 void EmitAssemblyHelper::setCommandLineOpts() {
477   SmallVector<const char *, 16> BackendArgs;
478   BackendArgs.push_back("clang"); // Fake program name.
479   if (!CodeGenOpts.DebugPass.empty()) {
480     BackendArgs.push_back("-debug-pass");
481     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
482   }
483   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
484     BackendArgs.push_back("-limit-float-precision");
485     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
486   }
487   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
488     BackendArgs.push_back(BackendOption.c_str());
489   BackendArgs.push_back(nullptr);
490   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
491                                     BackendArgs.data());
492 }
493 
494 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
495   // Create the TargetMachine for generating code.
496   std::string Error;
497   std::string Triple = TheModule->getTargetTriple();
498   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
499   if (!TheTarget) {
500     if (MustCreateTM)
501       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
502     return;
503   }
504 
505   unsigned CodeModel =
506     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
507       .Case("small", llvm::CodeModel::Small)
508       .Case("kernel", llvm::CodeModel::Kernel)
509       .Case("medium", llvm::CodeModel::Medium)
510       .Case("large", llvm::CodeModel::Large)
511       .Case("default", llvm::CodeModel::Default)
512       .Default(~0u);
513   assert(CodeModel != ~0u && "invalid code model!");
514   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
515 
516   std::string FeaturesStr =
517       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
518 
519   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
520   llvm::Optional<llvm::Reloc::Model> RM;
521   if (CodeGenOpts.RelocationModel == "static") {
522     RM = llvm::Reloc::Static;
523   } else if (CodeGenOpts.RelocationModel == "pic") {
524     RM = llvm::Reloc::PIC_;
525   } else if (CodeGenOpts.RelocationModel == "ropi") {
526     RM = llvm::Reloc::ROPI;
527   } else if (CodeGenOpts.RelocationModel == "rwpi") {
528     RM = llvm::Reloc::RWPI;
529   } else if (CodeGenOpts.RelocationModel == "ropi-rwpi") {
530     RM = llvm::Reloc::ROPI_RWPI;
531   } else {
532     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
533            "Invalid PIC model!");
534     RM = llvm::Reloc::DynamicNoPIC;
535   }
536 
537   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
538   switch (CodeGenOpts.OptimizationLevel) {
539   default: break;
540   case 0: OptLevel = CodeGenOpt::None; break;
541   case 3: OptLevel = CodeGenOpt::Aggressive; break;
542   }
543 
544   llvm::TargetOptions Options;
545 
546   Options.ThreadModel =
547     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
548       .Case("posix", llvm::ThreadModel::POSIX)
549       .Case("single", llvm::ThreadModel::Single);
550 
551   // Set float ABI type.
552   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
553           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
554          "Invalid Floating Point ABI!");
555   Options.FloatABIType =
556       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
557           .Case("soft", llvm::FloatABI::Soft)
558           .Case("softfp", llvm::FloatABI::Soft)
559           .Case("hard", llvm::FloatABI::Hard)
560           .Default(llvm::FloatABI::Default);
561 
562   // Set FP fusion mode.
563   switch (CodeGenOpts.getFPContractMode()) {
564   case CodeGenOptions::FPC_Off:
565     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
566     break;
567   case CodeGenOptions::FPC_On:
568     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
569     break;
570   case CodeGenOptions::FPC_Fast:
571     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
572     break;
573   }
574 
575   Options.UseInitArray = CodeGenOpts.UseInitArray;
576   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
577   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
578   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
579 
580   // Set EABI version.
581   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
582                             .Case("4", llvm::EABI::EABI4)
583                             .Case("5", llvm::EABI::EABI5)
584                             .Case("gnu", llvm::EABI::GNU)
585                             .Default(llvm::EABI::Default);
586 
587   if (LangOpts.SjLjExceptions)
588     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
589 
590   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
591   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
592   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
593   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
594   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
595   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
596   Options.FunctionSections = CodeGenOpts.FunctionSections;
597   Options.DataSections = CodeGenOpts.DataSections;
598   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
599   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
600   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
601 
602   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
603   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
604   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
605   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
606   Options.MCOptions.MCIncrementalLinkerCompatible =
607       CodeGenOpts.IncrementalLinkerCompatible;
608   Options.MCOptions.MCPIECopyRelocations =
609       CodeGenOpts.PIECopyRelocations;
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 static void runThinLTOBackend(const CodeGenOptions &CGOpts, Module *M,
731                               std::unique_ptr<raw_pwrite_stream> OS) {
732   // If we are performing a ThinLTO importing compile, load the function index
733   // into memory and pass it into thinBackend, which will run the function
734   // importer and invoke LTO passes.
735   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
736       llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
737   if (!IndexOrErr) {
738     logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
739                           "Error loading index file '" +
740                               CGOpts.ThinLTOIndexFile + "': ");
741     return;
742   }
743   std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
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   auto AddStream = [&](size_t Task) {
770     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
771   };
772   lto::Config Conf;
773   if (Error E = thinBackend(
774           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
775           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
776     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
777       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
778     });
779   }
780 }
781 
782 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
783                               const CodeGenOptions &CGOpts,
784                               const clang::TargetOptions &TOpts,
785                               const LangOptions &LOpts, const llvm::DataLayout &TDesc,
786                               Module *M, BackendAction Action,
787                               std::unique_ptr<raw_pwrite_stream> OS) {
788   if (!CGOpts.ThinLTOIndexFile.empty()) {
789     runThinLTOBackend(CGOpts, M, std::move(OS));
790     return;
791   }
792 
793   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
794 
795   AsmHelper.EmitAssembly(Action, std::move(OS));
796 
797   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
798   // DataLayout.
799   if (AsmHelper.TM) {
800     std::string DLDesc = M->getDataLayout().getStringRepresentation();
801     if (DLDesc != TDesc.getStringRepresentation()) {
802       unsigned DiagID = Diags.getCustomDiagID(
803           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
804                                     "expected target description '%1'");
805       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
806     }
807   }
808 }
809 
810 static const char* getSectionNameForBitcode(const Triple &T) {
811   switch (T.getObjectFormat()) {
812   case Triple::MachO:
813     return "__LLVM,__bitcode";
814   case Triple::COFF:
815   case Triple::ELF:
816   case Triple::UnknownObjectFormat:
817     return ".llvmbc";
818   }
819   llvm_unreachable("Unimplemented ObjectFormatType");
820 }
821 
822 static const char* getSectionNameForCommandline(const Triple &T) {
823   switch (T.getObjectFormat()) {
824   case Triple::MachO:
825     return "__LLVM,__cmdline";
826   case Triple::COFF:
827   case Triple::ELF:
828   case Triple::UnknownObjectFormat:
829     return ".llvmcmd";
830   }
831   llvm_unreachable("Unimplemented ObjectFormatType");
832 }
833 
834 // With -fembed-bitcode, save a copy of the llvm IR as data in the
835 // __LLVM,__bitcode section.
836 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
837                          llvm::MemoryBufferRef Buf) {
838   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
839     return;
840 
841   // Save llvm.compiler.used and remote it.
842   SmallVector<Constant*, 2> UsedArray;
843   SmallSet<GlobalValue*, 4> UsedGlobals;
844   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
845   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
846   for (auto *GV : UsedGlobals) {
847     if (GV->getName() != "llvm.embedded.module" &&
848         GV->getName() != "llvm.cmdline")
849       UsedArray.push_back(
850           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
851   }
852   if (Used)
853     Used->eraseFromParent();
854 
855   // Embed the bitcode for the llvm module.
856   std::string Data;
857   ArrayRef<uint8_t> ModuleData;
858   Triple T(M->getTargetTriple());
859   // Create a constant that contains the bitcode.
860   // In case of embedding a marker, ignore the input Buf and use the empty
861   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
862   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
863     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
864                    (const unsigned char *)Buf.getBufferEnd())) {
865       // If the input is LLVM Assembly, bitcode is produced by serializing
866       // the module. Use-lists order need to be perserved in this case.
867       llvm::raw_string_ostream OS(Data);
868       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
869       ModuleData =
870           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
871     } else
872       // If the input is LLVM bitcode, write the input byte stream directly.
873       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
874                                      Buf.getBufferSize());
875   }
876   llvm::Constant *ModuleConstant =
877       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
878   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
879       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
880       ModuleConstant);
881   GV->setSection(getSectionNameForBitcode(T));
882   UsedArray.push_back(
883       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
884   if (llvm::GlobalVariable *Old =
885           M->getGlobalVariable("llvm.embedded.module", true)) {
886     assert(Old->hasOneUse() &&
887            "llvm.embedded.module can only be used once in llvm.compiler.used");
888     GV->takeName(Old);
889     Old->eraseFromParent();
890   } else {
891     GV->setName("llvm.embedded.module");
892   }
893 
894   // Skip if only bitcode needs to be embedded.
895   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
896     // Embed command-line options.
897     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
898                               CGOpts.CmdArgs.size());
899     llvm::Constant *CmdConstant =
900       llvm::ConstantDataArray::get(M->getContext(), CmdData);
901     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
902                                   llvm::GlobalValue::PrivateLinkage,
903                                   CmdConstant);
904     GV->setSection(getSectionNameForCommandline(T));
905     UsedArray.push_back(
906         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
907     if (llvm::GlobalVariable *Old =
908             M->getGlobalVariable("llvm.cmdline", true)) {
909       assert(Old->hasOneUse() &&
910              "llvm.cmdline can only be used once in llvm.compiler.used");
911       GV->takeName(Old);
912       Old->eraseFromParent();
913     } else {
914       GV->setName("llvm.cmdline");
915     }
916   }
917 
918   if (UsedArray.empty())
919     return;
920 
921   // Recreate llvm.compiler.used.
922   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
923   auto *NewUsed = new GlobalVariable(
924       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
925       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
926   NewUsed->setSection("llvm.metadata");
927 }
928