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