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