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