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/TargetOptions.h"
13 #include "clang/Frontend/CodeGenOptions.h"
14 #include "clang/Frontend/FrontendDiagnostic.h"
15 #include "llvm/Module.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/FormattedStream.h"
23 #include "llvm/Support/PrettyStackTrace.h"
24 #include "llvm/Support/StandardPasses.h"
25 #include "llvm/Support/Timer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/SubtargetFeature.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLibraryInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetRegistry.h"
33 #include "llvm/Transforms/Instrumentation.h"
34 using namespace clang;
35 using namespace llvm;
36 
37 namespace {
38 
39 class EmitAssemblyHelper {
40   Diagnostic &Diags;
41   const CodeGenOptions &CodeGenOpts;
42   const TargetOptions &TargetOpts;
43   Module *TheModule;
44 
45   Timer CodeGenerationTime;
46 
47   mutable PassManager *CodeGenPasses;
48   mutable PassManager *PerModulePasses;
49   mutable FunctionPassManager *PerFunctionPasses;
50 
51 private:
52   PassManager *getCodeGenPasses() const {
53     if (!CodeGenPasses) {
54       CodeGenPasses = new PassManager();
55       CodeGenPasses->add(new TargetData(TheModule));
56     }
57     return CodeGenPasses;
58   }
59 
60   PassManager *getPerModulePasses() const {
61     if (!PerModulePasses) {
62       PerModulePasses = new PassManager();
63       PerModulePasses->add(new TargetData(TheModule));
64     }
65     return PerModulePasses;
66   }
67 
68   FunctionPassManager *getPerFunctionPasses() const {
69     if (!PerFunctionPasses) {
70       PerFunctionPasses = new FunctionPassManager(TheModule);
71       PerFunctionPasses->add(new TargetData(TheModule));
72     }
73     return PerFunctionPasses;
74   }
75 
76   void CreatePasses();
77 
78   /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
79   ///
80   /// \return True on success.
81   bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
82 
83 public:
84   EmitAssemblyHelper(Diagnostic &_Diags,
85                      const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
86                      Module *M)
87     : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts),
88       TheModule(M), CodeGenerationTime("Code Generation Time"),
89       CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
90 
91   ~EmitAssemblyHelper() {
92     delete CodeGenPasses;
93     delete PerModulePasses;
94     delete PerFunctionPasses;
95   }
96 
97   void EmitAssembly(BackendAction Action, raw_ostream *OS);
98 };
99 
100 }
101 
102 void EmitAssemblyHelper::CreatePasses() {
103   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
104   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
105 
106   // Handle disabling of LLVM optimization, where we want to preserve the
107   // internal module before any optimization.
108   if (CodeGenOpts.DisableLLVMOpts) {
109     OptLevel = 0;
110     Inlining = CodeGenOpts.NoInlining;
111   }
112 
113   FunctionPassManager *FPM = getPerFunctionPasses();
114 
115   TargetLibraryInfo *TLI =
116     new TargetLibraryInfo(Triple(TheModule->getTargetTriple()));
117   if (!CodeGenOpts.SimplifyLibCalls)
118     TLI->disableAllFunctions();
119   FPM->add(TLI);
120 
121   // In -O0 if checking is disabled, we don't even have per-function passes.
122   if (CodeGenOpts.VerifyModule)
123     FPM->add(createVerifierPass());
124 
125   // Assume that standard function passes aren't run for -O0.
126   if (OptLevel > 0)
127     llvm::createStandardFunctionPasses(FPM, OptLevel);
128 
129   llvm::Pass *InliningPass = 0;
130   switch (Inlining) {
131   case CodeGenOptions::NoInlining: break;
132   case CodeGenOptions::NormalInlining: {
133     // Set the inline threshold following llvm-gcc.
134     //
135     // FIXME: Derive these constants in a principled fashion.
136     unsigned Threshold = 225;
137     if (CodeGenOpts.OptimizeSize == 1) //-Os
138       Threshold = 75;
139     else if (CodeGenOpts.OptimizeSize == 2) //-Oz
140       Threshold = 25;
141     else if (OptLevel > 2)
142       Threshold = 275;
143     InliningPass = createFunctionInliningPass(Threshold);
144     break;
145   }
146   case CodeGenOptions::OnlyAlwaysInlining:
147     InliningPass = createAlwaysInlinerPass();         // Respect always_inline
148     break;
149   }
150 
151   PassManager *MPM = getPerModulePasses();
152 
153   TLI = new TargetLibraryInfo(Triple(TheModule->getTargetTriple()));
154   if (!CodeGenOpts.SimplifyLibCalls)
155     TLI->disableAllFunctions();
156   MPM->add(TLI);
157 
158   if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
159     MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
160                                     CodeGenOpts.EmitGcovArcs));
161     if (!CodeGenOpts.DebugInfo)
162       MPM->add(createStripSymbolsPass(true));
163   }
164 
165   // For now we always create per module passes.
166   llvm::createStandardModulePasses(MPM, OptLevel,
167                                    CodeGenOpts.OptimizeSize,
168                                    CodeGenOpts.UnitAtATime,
169                                    CodeGenOpts.UnrollLoops,
170                                    CodeGenOpts.SimplifyLibCalls,
171                                    /*HaveExceptions=*/true,
172                                    InliningPass);
173 }
174 
175 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
176                                        formatted_raw_ostream &OS) {
177   // Create the TargetMachine for generating code.
178   std::string Error;
179   std::string Triple = TheModule->getTargetTriple();
180   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
181   if (!TheTarget) {
182     Diags.Report(diag::err_fe_unable_to_create_target) << Error;
183     return false;
184   }
185 
186   // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
187   // being gross, this is also totally broken if we ever care about
188   // concurrency.
189 
190   // Set frame pointer elimination mode.
191   if (!CodeGenOpts.DisableFPElim) {
192     llvm::NoFramePointerElim = false;
193     llvm::NoFramePointerElimNonLeaf = false;
194   } else if (CodeGenOpts.OmitLeafFramePointer) {
195     llvm::NoFramePointerElim = false;
196     llvm::NoFramePointerElimNonLeaf = true;
197   } else {
198     llvm::NoFramePointerElim = true;
199     llvm::NoFramePointerElimNonLeaf = true;
200   }
201 
202   // Set float ABI type.
203   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
204     llvm::FloatABIType = llvm::FloatABI::Soft;
205   else if (CodeGenOpts.FloatABI == "hard")
206     llvm::FloatABIType = llvm::FloatABI::Hard;
207   else {
208     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
209     llvm::FloatABIType = llvm::FloatABI::Default;
210   }
211 
212   llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
213   llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
214   llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
215   NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
216   llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
217   llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
218   UnwindTablesMandatory = CodeGenOpts.UnwindTables;
219 
220   TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
221 
222   TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
223   TargetMachine::setDataSections    (CodeGenOpts.DataSections);
224 
225   // FIXME: Parse this earlier.
226   if (CodeGenOpts.RelocationModel == "static") {
227     TargetMachine::setRelocationModel(llvm::Reloc::Static);
228   } else if (CodeGenOpts.RelocationModel == "pic") {
229     TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
230   } else {
231     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
232            "Invalid PIC model!");
233     TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
234   }
235   // FIXME: Parse this earlier.
236   if (CodeGenOpts.CodeModel == "small") {
237     TargetMachine::setCodeModel(llvm::CodeModel::Small);
238   } else if (CodeGenOpts.CodeModel == "kernel") {
239     TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
240   } else if (CodeGenOpts.CodeModel == "medium") {
241     TargetMachine::setCodeModel(llvm::CodeModel::Medium);
242   } else if (CodeGenOpts.CodeModel == "large") {
243     TargetMachine::setCodeModel(llvm::CodeModel::Large);
244   } else {
245     assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
246     TargetMachine::setCodeModel(llvm::CodeModel::Default);
247   }
248 
249   std::vector<const char *> BackendArgs;
250   BackendArgs.push_back("clang"); // Fake program name.
251   if (!CodeGenOpts.DebugPass.empty()) {
252     BackendArgs.push_back("-debug-pass");
253     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
254   }
255   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
256     BackendArgs.push_back("-limit-float-precision");
257     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
258   }
259   if (llvm::TimePassesIsEnabled)
260     BackendArgs.push_back("-time-passes");
261   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
262     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
263   BackendArgs.push_back(0);
264   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
265                                     const_cast<char **>(&BackendArgs[0]));
266 
267   std::string FeaturesStr;
268   if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
269     SubtargetFeatures Features;
270     Features.setCPU(TargetOpts.CPU);
271     for (std::vector<std::string>::const_iterator
272            it = TargetOpts.Features.begin(),
273            ie = TargetOpts.Features.end(); it != ie; ++it)
274       Features.AddFeature(*it);
275     FeaturesStr = Features.getString();
276   }
277   TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
278 
279   if (CodeGenOpts.RelaxAll)
280     TM->setMCRelaxAll(true);
281   if (CodeGenOpts.SaveTempLabels)
282     TM->setMCSaveTempLabels(true);
283   if (CodeGenOpts.NoDwarf2CFIAsm)
284     TM->setMCUseCFI(false);
285 
286   // Create the code generator passes.
287   PassManager *PM = getCodeGenPasses();
288   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
289 
290   switch (CodeGenOpts.OptimizationLevel) {
291   default: break;
292   case 0: OptLevel = CodeGenOpt::None; break;
293   case 3: OptLevel = CodeGenOpt::Aggressive; break;
294   }
295 
296   // Normal mode, emit a .s or .o file by running the code generator. Note,
297   // this also adds codegenerator level optimization passes.
298   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
299   if (Action == Backend_EmitObj)
300     CGFT = TargetMachine::CGFT_ObjectFile;
301   else if (Action == Backend_EmitMCNull)
302     CGFT = TargetMachine::CGFT_Null;
303   else
304     assert(Action == Backend_EmitAssembly && "Invalid action!");
305   if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
306                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
307     Diags.Report(diag::err_fe_unable_to_interface_with_target);
308     return false;
309   }
310 
311   return true;
312 }
313 
314 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
315   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
316   llvm::formatted_raw_ostream FormattedOS;
317 
318   CreatePasses();
319   switch (Action) {
320   case Backend_EmitNothing:
321     break;
322 
323   case Backend_EmitBC:
324     getPerModulePasses()->add(createBitcodeWriterPass(*OS));
325     break;
326 
327   case Backend_EmitLL:
328     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
329     getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
330     break;
331 
332   default:
333     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
334     if (!AddEmitPasses(Action, FormattedOS))
335       return;
336   }
337 
338   // Before executing passes, print the final values of the LLVM options.
339   cl::PrintOptionValues();
340 
341   // Run passes. For now we do all passes at once, but eventually we
342   // would like to have the option of streaming code generation.
343 
344   if (PerFunctionPasses) {
345     PrettyStackTraceString CrashInfo("Per-function optimization");
346 
347     PerFunctionPasses->doInitialization();
348     for (Module::iterator I = TheModule->begin(),
349            E = TheModule->end(); I != E; ++I)
350       if (!I->isDeclaration())
351         PerFunctionPasses->run(*I);
352     PerFunctionPasses->doFinalization();
353   }
354 
355   if (PerModulePasses) {
356     PrettyStackTraceString CrashInfo("Per-module optimization passes");
357     PerModulePasses->run(*TheModule);
358   }
359 
360   if (CodeGenPasses) {
361     PrettyStackTraceString CrashInfo("Code generation");
362     CodeGenPasses->run(*TheModule);
363   }
364 }
365 
366 void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
367                               const TargetOptions &TOpts, Module *M,
368                               BackendAction Action, raw_ostream *OS) {
369   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M);
370 
371   AsmHelper.EmitAssembly(Action, OS);
372 }
373