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