blob: 85f42db81f5989fab3454cf3e2bfa8fe125dc35b [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"
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000013#include "clang/Basic/LangOptions.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000014#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000015#include "clang/Frontend/FrontendDiagnostic.h"
16#include "llvm/Module.h"
17#include "llvm/PassManager.h"
18#include "llvm/Assembly/PrintModulePass.h"
19#include "llvm/Bitcode/ReaderWriter.h"
20#include "llvm/CodeGen/RegAllocRegistry.h"
21#include "llvm/CodeGen/SchedulerRegistry.h"
Evan Cheng693769c2011-06-29 01:14:32 +000022#include "llvm/MC/SubtargetFeature.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000023#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/FormattedStream.h"
25#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner33c09d52011-05-21 20:40:11 +000026#include "llvm/Support/PassManagerBuilder.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000027#include "llvm/Support/Timer.h"
28#include "llvm/Support/raw_ostream.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000029#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetOptions.h"
32#include "llvm/Target/TargetRegistry.h"
Nick Lewyckye8ba8d72011-04-21 23:44:07 +000033#include "llvm/Transforms/Instrumentation.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000034using namespace clang;
35using namespace llvm;
36
37namespace {
38
39class EmitAssemblyHelper {
40 Diagnostic &Diags;
41 const CodeGenOptions &CodeGenOpts;
42 const TargetOptions &TargetOpts;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000043 const LangOptions &LangOpts;
Daniel Dunbar897c6762010-06-07 23:20:08 +000044 Module *TheModule;
Daniel Dunbar897c6762010-06-07 23:20:08 +000045
46 Timer CodeGenerationTime;
47
Daniel Dunbardb2f2372010-09-17 07:35:16 +000048 mutable PassManager *CodeGenPasses;
Daniel Dunbar897c6762010-06-07 23:20:08 +000049 mutable PassManager *PerModulePasses;
50 mutable FunctionPassManager *PerFunctionPasses;
51
52private:
Daniel Dunbardb2f2372010-09-17 07:35:16 +000053 PassManager *getCodeGenPasses() const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000054 if (!CodeGenPasses) {
Daniel Dunbardb2f2372010-09-17 07:35:16 +000055 CodeGenPasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000056 CodeGenPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000057 }
58 return CodeGenPasses;
59 }
60
61 PassManager *getPerModulePasses() const {
62 if (!PerModulePasses) {
63 PerModulePasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000064 PerModulePasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000065 }
66 return PerModulePasses;
67 }
68
69 FunctionPassManager *getPerFunctionPasses() const {
70 if (!PerFunctionPasses) {
71 PerFunctionPasses = new FunctionPassManager(TheModule);
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000072 PerFunctionPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000073 }
74 return PerFunctionPasses;
75 }
76
77 void CreatePasses();
78
79 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
80 ///
81 /// \return True on success.
82 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
83
84public:
85 EmitAssemblyHelper(Diagnostic &_Diags,
86 const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000087 const LangOptions &LOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000088 Module *M)
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000089 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000090 TheModule(M), CodeGenerationTime("Code Generation Time"),
Daniel Dunbar897c6762010-06-07 23:20:08 +000091 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
92
93 ~EmitAssemblyHelper() {
94 delete CodeGenPasses;
95 delete PerModulePasses;
96 delete PerFunctionPasses;
97 }
98
99 void EmitAssembly(BackendAction Action, raw_ostream *OS);
100};
101
102}
103
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000104static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
105 if (Builder.OptLevel > 0)
106 PM.add(createObjCARCExpandPass());
107}
108
109static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
110 if (Builder.OptLevel > 0)
111 PM.add(createObjCARCOptPass());
112}
113
Daniel Dunbar897c6762010-06-07 23:20:08 +0000114void EmitAssemblyHelper::CreatePasses() {
115 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
116 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
117
118 // Handle disabling of LLVM optimization, where we want to preserve the
119 // internal module before any optimization.
120 if (CodeGenOpts.DisableLLVMOpts) {
121 OptLevel = 0;
122 Inlining = CodeGenOpts.NoInlining;
123 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000124
125 PassManagerBuilder PMBuilder;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000126 PMBuilder.OptLevel = OptLevel;
127 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Andrew Trick6445d622011-04-05 18:49:32 +0000128
Chris Lattner9ca02e52011-05-21 23:50:44 +0000129 PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
130 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
131 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000132
133 // In ObjC ARC mode, add the main ARC optimization passes.
134 if (LangOpts.ObjCAutoRefCount) {
135 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
136 addObjCARCExpandPass);
137 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
138 addObjCARCOptPass);
139 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000140
141 // Figure out TargetLibraryInfo.
Bill Wendling3621b312011-05-17 23:06:23 +0000142 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattner9ca02e52011-05-21 23:50:44 +0000143 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000144 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattner9ca02e52011-05-21 23:50:44 +0000145 PMBuilder.LibraryInfo->disableAllFunctions();
Chris Lattner33c09d52011-05-21 20:40:11 +0000146
Daniel Dunbar897c6762010-06-07 23:20:08 +0000147 switch (Inlining) {
148 case CodeGenOptions::NoInlining: break;
149 case CodeGenOptions::NormalInlining: {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000150 // FIXME: Derive these constants in a principled fashion.
151 unsigned Threshold = 225;
Chris Lattner33c09d52011-05-21 20:40:11 +0000152 if (CodeGenOpts.OptimizeSize == 1) // -Os
Daniel Dunbar897c6762010-06-07 23:20:08 +0000153 Threshold = 75;
Chris Lattner33c09d52011-05-21 20:40:11 +0000154 else if (CodeGenOpts.OptimizeSize == 2) // -Oz
Bob Wilsona0fa2032011-04-29 22:49:50 +0000155 Threshold = 25;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000156 else if (OptLevel > 2)
157 Threshold = 275;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000158 PMBuilder.Inliner = createFunctionInliningPass(Threshold);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000159 break;
160 }
161 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner33c09d52011-05-21 20:40:11 +0000162 // Respect always_inline.
Chris Lattner9ca02e52011-05-21 23:50:44 +0000163 PMBuilder.Inliner = createAlwaysInlinerPass();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000164 break;
165 }
166
Chris Lattner33c09d52011-05-21 20:40:11 +0000167
168 // Set up the per-function pass manager.
169 FunctionPassManager *FPM = getPerFunctionPasses();
170 if (CodeGenOpts.VerifyModule)
171 FPM->add(createVerifierPass());
172 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trick6445d622011-04-05 18:49:32 +0000173
Chris Lattner33c09d52011-05-21 20:40:11 +0000174 // Set up the per-module pass manager.
175 PassManager *MPM = getPerModulePasses();
Chris Lattnerdf619762011-02-18 22:20:38 +0000176
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000177 if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
178 MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
Bill Wendling3621b312011-05-17 23:06:23 +0000179 CodeGenOpts.EmitGcovArcs,
180 TargetTriple.isMacOSX()));
181
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000182 if (!CodeGenOpts.DebugInfo)
183 MPM->add(createStripSymbolsPass(true));
184 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000185
186
187 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000188}
189
190bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
191 formatted_raw_ostream &OS) {
192 // Create the TargetMachine for generating code.
193 std::string Error;
194 std::string Triple = TheModule->getTargetTriple();
195 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
196 if (!TheTarget) {
197 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
198 return false;
199 }
200
201 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
202 // being gross, this is also totally broken if we ever care about
203 // concurrency.
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000204
205 // Set frame pointer elimination mode.
206 if (!CodeGenOpts.DisableFPElim) {
207 llvm::NoFramePointerElim = false;
208 llvm::NoFramePointerElimNonLeaf = false;
209 } else if (CodeGenOpts.OmitLeafFramePointer) {
210 llvm::NoFramePointerElim = false;
211 llvm::NoFramePointerElimNonLeaf = true;
212 } else {
213 llvm::NoFramePointerElim = true;
214 llvm::NoFramePointerElimNonLeaf = true;
215 }
216
217 // Set float ABI type.
Sandeep Patel34c1af82011-04-05 00:23:47 +0000218 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
Daniel Dunbar897c6762010-06-07 23:20:08 +0000219 llvm::FloatABIType = llvm::FloatABI::Soft;
220 else if (CodeGenOpts.FloatABI == "hard")
221 llvm::FloatABIType = llvm::FloatABI::Hard;
222 else {
223 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
224 llvm::FloatABIType = llvm::FloatABI::Default;
225 }
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000226
Peter Collingbourne4400cb82010-12-04 01:51:33 +0000227 llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
Peter Collingbourne5d729a32010-12-04 01:51:05 +0000228 llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
229 llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000230 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
Peter Collingbourne5f67e132010-12-04 01:51:14 +0000231 llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000232 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000233
234 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
235
236 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
237 TargetMachine::setDataSections (CodeGenOpts.DataSections);
238
239 // FIXME: Parse this earlier.
240 if (CodeGenOpts.RelocationModel == "static") {
241 TargetMachine::setRelocationModel(llvm::Reloc::Static);
242 } else if (CodeGenOpts.RelocationModel == "pic") {
243 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
244 } else {
245 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
246 "Invalid PIC model!");
247 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
248 }
249 // FIXME: Parse this earlier.
250 if (CodeGenOpts.CodeModel == "small") {
251 TargetMachine::setCodeModel(llvm::CodeModel::Small);
252 } else if (CodeGenOpts.CodeModel == "kernel") {
253 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
254 } else if (CodeGenOpts.CodeModel == "medium") {
255 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
256 } else if (CodeGenOpts.CodeModel == "large") {
257 TargetMachine::setCodeModel(llvm::CodeModel::Large);
258 } else {
259 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
260 TargetMachine::setCodeModel(llvm::CodeModel::Default);
261 }
262
263 std::vector<const char *> BackendArgs;
264 BackendArgs.push_back("clang"); // Fake program name.
265 if (!CodeGenOpts.DebugPass.empty()) {
266 BackendArgs.push_back("-debug-pass");
267 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
268 }
269 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
270 BackendArgs.push_back("-limit-float-precision");
271 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
272 }
273 if (llvm::TimePassesIsEnabled)
274 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000275 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
276 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000277 BackendArgs.push_back(0);
278 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
279 const_cast<char **>(&BackendArgs[0]));
280
281 std::string FeaturesStr;
Evan Cheng368691e2011-06-30 02:06:32 +0000282 if (TargetOpts.Features.size()) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000283 SubtargetFeatures Features;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000284 for (std::vector<std::string>::const_iterator
285 it = TargetOpts.Features.begin(),
286 ie = TargetOpts.Features.end(); it != ie; ++it)
287 Features.AddFeature(*it);
288 FeaturesStr = Features.getString();
289 }
Evan Cheng368691e2011-06-30 02:06:32 +0000290 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
291 FeaturesStr);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000292
293 if (CodeGenOpts.RelaxAll)
294 TM->setMCRelaxAll(true);
Daniel Dunbar96932322011-03-28 22:49:28 +0000295 if (CodeGenOpts.SaveTempLabels)
296 TM->setMCSaveTempLabels(true);
Rafael Espindolaf24a1512011-04-30 18:35:43 +0000297 if (CodeGenOpts.NoDwarf2CFIAsm)
298 TM->setMCUseCFI(false);
Nick Lewyckyc3b90142011-06-21 00:14:18 +0000299 if (CodeGenOpts.NoExecStack)
300 TM->setMCNoExecStack(true);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000301
302 // Create the code generator passes.
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000303 PassManager *PM = getCodeGenPasses();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000304 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
305
306 switch (CodeGenOpts.OptimizationLevel) {
307 default: break;
308 case 0: OptLevel = CodeGenOpt::None; break;
309 case 3: OptLevel = CodeGenOpt::Aggressive; break;
310 }
311
312 // Normal mode, emit a .s or .o file by running the code generator. Note,
313 // this also adds codegenerator level optimization passes.
314 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
315 if (Action == Backend_EmitObj)
316 CGFT = TargetMachine::CGFT_ObjectFile;
317 else if (Action == Backend_EmitMCNull)
318 CGFT = TargetMachine::CGFT_Null;
319 else
320 assert(Action == Backend_EmitAssembly && "Invalid action!");
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000321
322 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
323 // "codegen" passes so that it isn't run multiple times when there is
324 // inlining happening.
325 if (LangOpts.ObjCAutoRefCount)
326 PM->add(createObjCARCContractPass());
327
Daniel Dunbar897c6762010-06-07 23:20:08 +0000328 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
329 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
330 Diags.Report(diag::err_fe_unable_to_interface_with_target);
331 return false;
332 }
333
334 return true;
335}
336
337void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
338 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
339 llvm::formatted_raw_ostream FormattedOS;
340
341 CreatePasses();
342 switch (Action) {
343 case Backend_EmitNothing:
344 break;
345
346 case Backend_EmitBC:
347 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
348 break;
349
350 case Backend_EmitLL:
351 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
352 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
353 break;
354
355 default:
356 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
357 if (!AddEmitPasses(Action, FormattedOS))
358 return;
359 }
360
Andrew Trick92b5d942011-04-05 18:56:55 +0000361 // Before executing passes, print the final values of the LLVM options.
362 cl::PrintOptionValues();
363
Daniel Dunbar897c6762010-06-07 23:20:08 +0000364 // Run passes. For now we do all passes at once, but eventually we
365 // would like to have the option of streaming code generation.
366
367 if (PerFunctionPasses) {
368 PrettyStackTraceString CrashInfo("Per-function optimization");
369
370 PerFunctionPasses->doInitialization();
371 for (Module::iterator I = TheModule->begin(),
372 E = TheModule->end(); I != E; ++I)
373 if (!I->isDeclaration())
374 PerFunctionPasses->run(*I);
375 PerFunctionPasses->doFinalization();
376 }
377
378 if (PerModulePasses) {
379 PrettyStackTraceString CrashInfo("Per-module optimization passes");
380 PerModulePasses->run(*TheModule);
381 }
382
383 if (CodeGenPasses) {
384 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000385 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000386 }
387}
388
389void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000390 const TargetOptions &TOpts,
391 const LangOptions &LOpts,
392 Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000393 BackendAction Action, raw_ostream *OS) {
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000394 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000395
396 AsmHelper.EmitAssembly(Action, OS);
397}