blob: 66092f0d988011214b1bcf32af5251f524244c81 [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"
Evan Cheng693769c2011-06-29 01:14:32 +000021#include "llvm/MC/SubtargetFeature.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/FormattedStream.h"
24#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner33c09d52011-05-21 20:40:11 +000025#include "llvm/Support/PassManagerBuilder.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000026#include "llvm/Support/Timer.h"
27#include "llvm/Support/raw_ostream.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000028#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;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000113 PMBuilder.OptLevel = OptLevel;
114 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Andrew Trick6445d622011-04-05 18:49:32 +0000115
Chris Lattner9ca02e52011-05-21 23:50:44 +0000116 PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
117 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
118 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Chris Lattner33c09d52011-05-21 20:40:11 +0000119
120 // Figure out TargetLibraryInfo.
Bill Wendling3621b312011-05-17 23:06:23 +0000121 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattner9ca02e52011-05-21 23:50:44 +0000122 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000123 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattner9ca02e52011-05-21 23:50:44 +0000124 PMBuilder.LibraryInfo->disableAllFunctions();
Chris Lattner33c09d52011-05-21 20:40:11 +0000125
Daniel Dunbar897c6762010-06-07 23:20:08 +0000126 switch (Inlining) {
127 case CodeGenOptions::NoInlining: break;
128 case CodeGenOptions::NormalInlining: {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000129 // FIXME: Derive these constants in a principled fashion.
130 unsigned Threshold = 225;
Chris Lattner33c09d52011-05-21 20:40:11 +0000131 if (CodeGenOpts.OptimizeSize == 1) // -Os
Daniel Dunbar897c6762010-06-07 23:20:08 +0000132 Threshold = 75;
Chris Lattner33c09d52011-05-21 20:40:11 +0000133 else if (CodeGenOpts.OptimizeSize == 2) // -Oz
Bob Wilsona0fa2032011-04-29 22:49:50 +0000134 Threshold = 25;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000135 else if (OptLevel > 2)
136 Threshold = 275;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000137 PMBuilder.Inliner = createFunctionInliningPass(Threshold);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000138 break;
139 }
140 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner33c09d52011-05-21 20:40:11 +0000141 // Respect always_inline.
Chris Lattner9ca02e52011-05-21 23:50:44 +0000142 PMBuilder.Inliner = createAlwaysInlinerPass();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000143 break;
144 }
145
Chris Lattner33c09d52011-05-21 20:40:11 +0000146
147 // Set up the per-function pass manager.
148 FunctionPassManager *FPM = getPerFunctionPasses();
149 if (CodeGenOpts.VerifyModule)
150 FPM->add(createVerifierPass());
151 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trick6445d622011-04-05 18:49:32 +0000152
Chris Lattner33c09d52011-05-21 20:40:11 +0000153 // Set up the per-module pass manager.
154 PassManager *MPM = getPerModulePasses();
Chris Lattnerdf619762011-02-18 22:20:38 +0000155
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000156 if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
157 MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
Bill Wendling3621b312011-05-17 23:06:23 +0000158 CodeGenOpts.EmitGcovArcs,
159 TargetTriple.isMacOSX()));
160
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000161 if (!CodeGenOpts.DebugInfo)
162 MPM->add(createStripSymbolsPass(true));
163 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000164
165
166 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000167}
168
169bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
170 formatted_raw_ostream &OS) {
171 // Create the TargetMachine for generating code.
172 std::string Error;
173 std::string Triple = TheModule->getTargetTriple();
174 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
175 if (!TheTarget) {
176 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
177 return false;
178 }
179
180 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
181 // being gross, this is also totally broken if we ever care about
182 // concurrency.
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000183
184 // Set frame pointer elimination mode.
185 if (!CodeGenOpts.DisableFPElim) {
186 llvm::NoFramePointerElim = false;
187 llvm::NoFramePointerElimNonLeaf = false;
188 } else if (CodeGenOpts.OmitLeafFramePointer) {
189 llvm::NoFramePointerElim = false;
190 llvm::NoFramePointerElimNonLeaf = true;
191 } else {
192 llvm::NoFramePointerElim = true;
193 llvm::NoFramePointerElimNonLeaf = true;
194 }
195
196 // Set float ABI type.
Sandeep Patel34c1af82011-04-05 00:23:47 +0000197 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
Daniel Dunbar897c6762010-06-07 23:20:08 +0000198 llvm::FloatABIType = llvm::FloatABI::Soft;
199 else if (CodeGenOpts.FloatABI == "hard")
200 llvm::FloatABIType = llvm::FloatABI::Hard;
201 else {
202 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
203 llvm::FloatABIType = llvm::FloatABI::Default;
204 }
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000205
Peter Collingbourne4400cb82010-12-04 01:51:33 +0000206 llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
Peter Collingbourne5d729a32010-12-04 01:51:05 +0000207 llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
208 llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000209 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
Peter Collingbourne5f67e132010-12-04 01:51:14 +0000210 llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000211 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000212
213 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
214
215 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
216 TargetMachine::setDataSections (CodeGenOpts.DataSections);
217
218 // FIXME: Parse this earlier.
219 if (CodeGenOpts.RelocationModel == "static") {
220 TargetMachine::setRelocationModel(llvm::Reloc::Static);
221 } else if (CodeGenOpts.RelocationModel == "pic") {
222 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
223 } else {
224 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
225 "Invalid PIC model!");
226 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
227 }
228 // FIXME: Parse this earlier.
229 if (CodeGenOpts.CodeModel == "small") {
230 TargetMachine::setCodeModel(llvm::CodeModel::Small);
231 } else if (CodeGenOpts.CodeModel == "kernel") {
232 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
233 } else if (CodeGenOpts.CodeModel == "medium") {
234 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
235 } else if (CodeGenOpts.CodeModel == "large") {
236 TargetMachine::setCodeModel(llvm::CodeModel::Large);
237 } else {
238 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
239 TargetMachine::setCodeModel(llvm::CodeModel::Default);
240 }
241
242 std::vector<const char *> BackendArgs;
243 BackendArgs.push_back("clang"); // Fake program name.
244 if (!CodeGenOpts.DebugPass.empty()) {
245 BackendArgs.push_back("-debug-pass");
246 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
247 }
248 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
249 BackendArgs.push_back("-limit-float-precision");
250 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
251 }
252 if (llvm::TimePassesIsEnabled)
253 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000254 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
255 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000256 BackendArgs.push_back(0);
257 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
258 const_cast<char **>(&BackendArgs[0]));
259
260 std::string FeaturesStr;
261 if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
262 SubtargetFeatures Features;
263 Features.setCPU(TargetOpts.CPU);
264 for (std::vector<std::string>::const_iterator
265 it = TargetOpts.Features.begin(),
266 ie = TargetOpts.Features.end(); it != ie; ++it)
267 Features.AddFeature(*it);
268 FeaturesStr = Features.getString();
269 }
270 TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
271
272 if (CodeGenOpts.RelaxAll)
273 TM->setMCRelaxAll(true);
Daniel Dunbar96932322011-03-28 22:49:28 +0000274 if (CodeGenOpts.SaveTempLabels)
275 TM->setMCSaveTempLabels(true);
Rafael Espindolaf24a1512011-04-30 18:35:43 +0000276 if (CodeGenOpts.NoDwarf2CFIAsm)
277 TM->setMCUseCFI(false);
Nick Lewyckyc3b90142011-06-21 00:14:18 +0000278 if (CodeGenOpts.NoExecStack)
279 TM->setMCNoExecStack(true);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000280
281 // Create the code generator passes.
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000282 PassManager *PM = getCodeGenPasses();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000283 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
284
285 switch (CodeGenOpts.OptimizationLevel) {
286 default: break;
287 case 0: OptLevel = CodeGenOpt::None; break;
288 case 3: OptLevel = CodeGenOpt::Aggressive; break;
289 }
290
291 // Normal mode, emit a .s or .o file by running the code generator. Note,
292 // this also adds codegenerator level optimization passes.
293 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
294 if (Action == Backend_EmitObj)
295 CGFT = TargetMachine::CGFT_ObjectFile;
296 else if (Action == Backend_EmitMCNull)
297 CGFT = TargetMachine::CGFT_Null;
298 else
299 assert(Action == Backend_EmitAssembly && "Invalid action!");
300 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
301 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
302 Diags.Report(diag::err_fe_unable_to_interface_with_target);
303 return false;
304 }
305
306 return true;
307}
308
309void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
310 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
311 llvm::formatted_raw_ostream FormattedOS;
312
313 CreatePasses();
314 switch (Action) {
315 case Backend_EmitNothing:
316 break;
317
318 case Backend_EmitBC:
319 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
320 break;
321
322 case Backend_EmitLL:
323 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
324 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
325 break;
326
327 default:
328 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
329 if (!AddEmitPasses(Action, FormattedOS))
330 return;
331 }
332
Andrew Trick92b5d942011-04-05 18:56:55 +0000333 // Before executing passes, print the final values of the LLVM options.
334 cl::PrintOptionValues();
335
Daniel Dunbar897c6762010-06-07 23:20:08 +0000336 // Run passes. For now we do all passes at once, but eventually we
337 // would like to have the option of streaming code generation.
338
339 if (PerFunctionPasses) {
340 PrettyStackTraceString CrashInfo("Per-function optimization");
341
342 PerFunctionPasses->doInitialization();
343 for (Module::iterator I = TheModule->begin(),
344 E = TheModule->end(); I != E; ++I)
345 if (!I->isDeclaration())
346 PerFunctionPasses->run(*I);
347 PerFunctionPasses->doFinalization();
348 }
349
350 if (PerModulePasses) {
351 PrettyStackTraceString CrashInfo("Per-module optimization passes");
352 PerModulePasses->run(*TheModule);
353 }
354
355 if (CodeGenPasses) {
356 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000357 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000358 }
359}
360
361void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
362 const TargetOptions &TOpts, Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000363 BackendAction Action, raw_ostream *OS) {
364 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000365
366 AsmHelper.EmitAssembly(Action, OS);
367}