blob: 92b298b7a336db9e6f07656d7a5acf844f7dede1 [file] [log] [blame]
Daniel Dunbar897c6762010-06-07 23:20:08 +00001//===--- 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
Daniel Dunbar9b414d32010-06-15 17:48:49 +000010#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
12#include "clang/Basic/TargetOptions.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000013#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000014#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"
Chris Lattner33c09d52011-05-21 20:40:11 +000024#include "llvm/Support/PassManagerBuilder.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000025#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"
Nick Lewyckye8ba8d72011-04-21 23:44:07 +000032#include "llvm/Transforms/Instrumentation.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000033using namespace clang;
34using namespace llvm;
35
36namespace {
37
38class EmitAssemblyHelper {
39 Diagnostic &Diags;
40 const CodeGenOptions &CodeGenOpts;
41 const TargetOptions &TargetOpts;
42 Module *TheModule;
Daniel Dunbar897c6762010-06-07 23:20:08 +000043
44 Timer CodeGenerationTime;
45
Daniel Dunbardb2f2372010-09-17 07:35:16 +000046 mutable PassManager *CodeGenPasses;
Daniel Dunbar897c6762010-06-07 23:20:08 +000047 mutable PassManager *PerModulePasses;
48 mutable FunctionPassManager *PerFunctionPasses;
49
50private:
Daniel Dunbardb2f2372010-09-17 07:35:16 +000051 PassManager *getCodeGenPasses() const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000052 if (!CodeGenPasses) {
Daniel Dunbardb2f2372010-09-17 07:35:16 +000053 CodeGenPasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000054 CodeGenPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000055 }
56 return CodeGenPasses;
57 }
58
59 PassManager *getPerModulePasses() const {
60 if (!PerModulePasses) {
61 PerModulePasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000062 PerModulePasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000063 }
64 return PerModulePasses;
65 }
66
67 FunctionPassManager *getPerFunctionPasses() const {
68 if (!PerFunctionPasses) {
69 PerFunctionPasses = new FunctionPassManager(TheModule);
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000070 PerFunctionPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000071 }
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
82public:
83 EmitAssemblyHelper(Diagnostic &_Diags,
84 const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000085 Module *M)
Daniel Dunbar897c6762010-06-07 23:20:08 +000086 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000087 TheModule(M), CodeGenerationTime("Code Generation Time"),
Daniel Dunbar897c6762010-06-07 23:20:08 +000088 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
101void 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 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000111
112 PassManagerBuilder PMBuilder;
113 PMBuilder.setOptimizationLevel(OptLevel);
114 PMBuilder.setSizeLevel(CodeGenOpts.OptimizeSize);
Andrew Trick6445d622011-04-05 18:49:32 +0000115
Chris Lattner33c09d52011-05-21 20:40:11 +0000116 if (!CodeGenOpts.SimplifyLibCalls) PMBuilder.disableSimplifyLibCalls();
117 if (!CodeGenOpts.UnitAtATime) PMBuilder.disableUnitAtATime();
118 if (!CodeGenOpts.UnrollLoops) PMBuilder.disableUnrollLoops();
119
120 // Figure out TargetLibraryInfo.
Bill Wendling3621b312011-05-17 23:06:23 +0000121 Triple TargetTriple(TheModule->getTargetTriple());
122 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000123 if (!CodeGenOpts.SimplifyLibCalls)
124 TLI->disableAllFunctions();
Chris Lattner33c09d52011-05-21 20:40:11 +0000125 PMBuilder.setLibraryInfo(TLI);
126
127
Daniel Dunbar897c6762010-06-07 23:20:08 +0000128 switch (Inlining) {
129 case CodeGenOptions::NoInlining: break;
130 case CodeGenOptions::NormalInlining: {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000131 // FIXME: Derive these constants in a principled fashion.
132 unsigned Threshold = 225;
Chris Lattner33c09d52011-05-21 20:40:11 +0000133 if (CodeGenOpts.OptimizeSize == 1) // -Os
Daniel Dunbar897c6762010-06-07 23:20:08 +0000134 Threshold = 75;
Chris Lattner33c09d52011-05-21 20:40:11 +0000135 else if (CodeGenOpts.OptimizeSize == 2) // -Oz
Bob Wilsona0fa2032011-04-29 22:49:50 +0000136 Threshold = 25;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000137 else if (OptLevel > 2)
138 Threshold = 275;
Chris Lattner33c09d52011-05-21 20:40:11 +0000139 PMBuilder.setInliner(createFunctionInliningPass(Threshold));
Daniel Dunbar897c6762010-06-07 23:20:08 +0000140 break;
141 }
142 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner33c09d52011-05-21 20:40:11 +0000143 // Respect always_inline.
144 PMBuilder.setInliner(createAlwaysInlinerPass());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000145 break;
146 }
147
Chris Lattner33c09d52011-05-21 20:40:11 +0000148
149 // Set up the per-function pass manager.
150 FunctionPassManager *FPM = getPerFunctionPasses();
151 if (CodeGenOpts.VerifyModule)
152 FPM->add(createVerifierPass());
153 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trick6445d622011-04-05 18:49:32 +0000154
Chris Lattner33c09d52011-05-21 20:40:11 +0000155 // Set up the per-module pass manager.
156 PassManager *MPM = getPerModulePasses();
Chris Lattnerdf619762011-02-18 22:20:38 +0000157
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000158 if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
159 MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
Bill Wendling3621b312011-05-17 23:06:23 +0000160 CodeGenOpts.EmitGcovArcs,
161 TargetTriple.isMacOSX()));
162
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000163 if (!CodeGenOpts.DebugInfo)
164 MPM->add(createStripSymbolsPass(true));
165 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000166
167
168 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000169}
170
171bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
172 formatted_raw_ostream &OS) {
173 // Create the TargetMachine for generating code.
174 std::string Error;
175 std::string Triple = TheModule->getTargetTriple();
176 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
177 if (!TheTarget) {
178 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
179 return false;
180 }
181
182 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
183 // being gross, this is also totally broken if we ever care about
184 // concurrency.
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000185
186 // Set frame pointer elimination mode.
187 if (!CodeGenOpts.DisableFPElim) {
188 llvm::NoFramePointerElim = false;
189 llvm::NoFramePointerElimNonLeaf = false;
190 } else if (CodeGenOpts.OmitLeafFramePointer) {
191 llvm::NoFramePointerElim = false;
192 llvm::NoFramePointerElimNonLeaf = true;
193 } else {
194 llvm::NoFramePointerElim = true;
195 llvm::NoFramePointerElimNonLeaf = true;
196 }
197
198 // Set float ABI type.
Sandeep Patel34c1af82011-04-05 00:23:47 +0000199 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
Daniel Dunbar897c6762010-06-07 23:20:08 +0000200 llvm::FloatABIType = llvm::FloatABI::Soft;
201 else if (CodeGenOpts.FloatABI == "hard")
202 llvm::FloatABIType = llvm::FloatABI::Hard;
203 else {
204 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
205 llvm::FloatABIType = llvm::FloatABI::Default;
206 }
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000207
Peter Collingbourne4400cb82010-12-04 01:51:33 +0000208 llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
Peter Collingbourne5d729a32010-12-04 01:51:05 +0000209 llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
210 llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000211 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
Peter Collingbourne5f67e132010-12-04 01:51:14 +0000212 llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000213 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
214 UnwindTablesMandatory = CodeGenOpts.UnwindTables;
215
216 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
217
218 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
219 TargetMachine::setDataSections (CodeGenOpts.DataSections);
220
221 // FIXME: Parse this earlier.
222 if (CodeGenOpts.RelocationModel == "static") {
223 TargetMachine::setRelocationModel(llvm::Reloc::Static);
224 } else if (CodeGenOpts.RelocationModel == "pic") {
225 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
226 } else {
227 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
228 "Invalid PIC model!");
229 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
230 }
231 // FIXME: Parse this earlier.
232 if (CodeGenOpts.CodeModel == "small") {
233 TargetMachine::setCodeModel(llvm::CodeModel::Small);
234 } else if (CodeGenOpts.CodeModel == "kernel") {
235 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
236 } else if (CodeGenOpts.CodeModel == "medium") {
237 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
238 } else if (CodeGenOpts.CodeModel == "large") {
239 TargetMachine::setCodeModel(llvm::CodeModel::Large);
240 } else {
241 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
242 TargetMachine::setCodeModel(llvm::CodeModel::Default);
243 }
244
245 std::vector<const char *> BackendArgs;
246 BackendArgs.push_back("clang"); // Fake program name.
247 if (!CodeGenOpts.DebugPass.empty()) {
248 BackendArgs.push_back("-debug-pass");
249 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
250 }
251 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
252 BackendArgs.push_back("-limit-float-precision");
253 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
254 }
255 if (llvm::TimePassesIsEnabled)
256 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000257 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
258 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000259 BackendArgs.push_back(0);
260 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
261 const_cast<char **>(&BackendArgs[0]));
262
263 std::string FeaturesStr;
264 if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
265 SubtargetFeatures Features;
266 Features.setCPU(TargetOpts.CPU);
267 for (std::vector<std::string>::const_iterator
268 it = TargetOpts.Features.begin(),
269 ie = TargetOpts.Features.end(); it != ie; ++it)
270 Features.AddFeature(*it);
271 FeaturesStr = Features.getString();
272 }
273 TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
274
275 if (CodeGenOpts.RelaxAll)
276 TM->setMCRelaxAll(true);
Daniel Dunbar96932322011-03-28 22:49:28 +0000277 if (CodeGenOpts.SaveTempLabels)
278 TM->setMCSaveTempLabels(true);
Rafael Espindolaf24a1512011-04-30 18:35:43 +0000279 if (CodeGenOpts.NoDwarf2CFIAsm)
280 TM->setMCUseCFI(false);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000281
282 // Create the code generator passes.
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000283 PassManager *PM = getCodeGenPasses();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000284 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
285
286 switch (CodeGenOpts.OptimizationLevel) {
287 default: break;
288 case 0: OptLevel = CodeGenOpt::None; break;
289 case 3: OptLevel = CodeGenOpt::Aggressive; break;
290 }
291
292 // Normal mode, emit a .s or .o file by running the code generator. Note,
293 // this also adds codegenerator level optimization passes.
294 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
295 if (Action == Backend_EmitObj)
296 CGFT = TargetMachine::CGFT_ObjectFile;
297 else if (Action == Backend_EmitMCNull)
298 CGFT = TargetMachine::CGFT_Null;
299 else
300 assert(Action == Backend_EmitAssembly && "Invalid action!");
301 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
302 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
303 Diags.Report(diag::err_fe_unable_to_interface_with_target);
304 return false;
305 }
306
307 return true;
308}
309
310void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
311 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
312 llvm::formatted_raw_ostream FormattedOS;
313
314 CreatePasses();
315 switch (Action) {
316 case Backend_EmitNothing:
317 break;
318
319 case Backend_EmitBC:
320 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
321 break;
322
323 case Backend_EmitLL:
324 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
325 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
326 break;
327
328 default:
329 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
330 if (!AddEmitPasses(Action, FormattedOS))
331 return;
332 }
333
Andrew Trick92b5d942011-04-05 18:56:55 +0000334 // Before executing passes, print the final values of the LLVM options.
335 cl::PrintOptionValues();
336
Daniel Dunbar897c6762010-06-07 23:20:08 +0000337 // Run passes. For now we do all passes at once, but eventually we
338 // would like to have the option of streaming code generation.
339
340 if (PerFunctionPasses) {
341 PrettyStackTraceString CrashInfo("Per-function optimization");
342
343 PerFunctionPasses->doInitialization();
344 for (Module::iterator I = TheModule->begin(),
345 E = TheModule->end(); I != E; ++I)
346 if (!I->isDeclaration())
347 PerFunctionPasses->run(*I);
348 PerFunctionPasses->doFinalization();
349 }
350
351 if (PerModulePasses) {
352 PrettyStackTraceString CrashInfo("Per-module optimization passes");
353 PerModulePasses->run(*TheModule);
354 }
355
356 if (CodeGenPasses) {
357 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000358 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000359 }
360}
361
362void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
363 const TargetOptions &TOpts, Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000364 BackendAction Action, raw_ostream *OS) {
365 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000366
367 AsmHelper.EmitAssembly(Action, OS);
368}