blob: 2e6e29468c99f7960d81fd4f424227ffe35a2198 [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.
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000240 llvm::CodeModel::Model CM;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000241 if (CodeGenOpts.CodeModel == "small") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000242 CM = llvm::CodeModel::Small;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000243 } else if (CodeGenOpts.CodeModel == "kernel") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000244 CM = llvm::CodeModel::Kernel;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000245 } else if (CodeGenOpts.CodeModel == "medium") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000246 CM = llvm::CodeModel::Medium;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000247 } else if (CodeGenOpts.CodeModel == "large") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000248 CM = llvm::CodeModel::Large;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000249 } else {
250 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000251 CM = llvm::CodeModel::Default;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000252 }
253
254 std::vector<const char *> BackendArgs;
255 BackendArgs.push_back("clang"); // Fake program name.
256 if (!CodeGenOpts.DebugPass.empty()) {
257 BackendArgs.push_back("-debug-pass");
258 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
259 }
260 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
261 BackendArgs.push_back("-limit-float-precision");
262 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
263 }
264 if (llvm::TimePassesIsEnabled)
265 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000266 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
267 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000268 BackendArgs.push_back(0);
269 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
270 const_cast<char **>(&BackendArgs[0]));
271
272 std::string FeaturesStr;
Evan Cheng368691e2011-06-30 02:06:32 +0000273 if (TargetOpts.Features.size()) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000274 SubtargetFeatures Features;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000275 for (std::vector<std::string>::const_iterator
276 it = TargetOpts.Features.begin(),
277 ie = TargetOpts.Features.end(); it != ie; ++it)
278 Features.AddFeature(*it);
279 FeaturesStr = Features.getString();
280 }
Evan Cheng2860e302011-07-19 06:37:41 +0000281
282 llvm::Reloc::Model RM = llvm::Reloc::Default;
283 if (CodeGenOpts.RelocationModel == "static") {
284 RM = llvm::Reloc::Static;
285 } else if (CodeGenOpts.RelocationModel == "pic") {
286 RM = llvm::Reloc::PIC_;
287 } else {
288 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
289 "Invalid PIC model!");
290 RM = llvm::Reloc::DynamicNoPIC;
291 }
292
Evan Cheng368691e2011-06-30 02:06:32 +0000293 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000294 FeaturesStr, RM, CM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000295
296 if (CodeGenOpts.RelaxAll)
297 TM->setMCRelaxAll(true);
Daniel Dunbar96932322011-03-28 22:49:28 +0000298 if (CodeGenOpts.SaveTempLabels)
299 TM->setMCSaveTempLabels(true);
Rafael Espindolaf24a1512011-04-30 18:35:43 +0000300 if (CodeGenOpts.NoDwarf2CFIAsm)
301 TM->setMCUseCFI(false);
Nick Lewyckyc3b90142011-06-21 00:14:18 +0000302 if (CodeGenOpts.NoExecStack)
303 TM->setMCNoExecStack(true);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000304
305 // Create the code generator passes.
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000306 PassManager *PM = getCodeGenPasses();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000307 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
308
309 switch (CodeGenOpts.OptimizationLevel) {
310 default: break;
311 case 0: OptLevel = CodeGenOpt::None; break;
312 case 3: OptLevel = CodeGenOpt::Aggressive; break;
313 }
314
315 // Normal mode, emit a .s or .o file by running the code generator. Note,
316 // this also adds codegenerator level optimization passes.
317 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
318 if (Action == Backend_EmitObj)
319 CGFT = TargetMachine::CGFT_ObjectFile;
320 else if (Action == Backend_EmitMCNull)
321 CGFT = TargetMachine::CGFT_Null;
322 else
323 assert(Action == Backend_EmitAssembly && "Invalid action!");
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000324
325 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
326 // "codegen" passes so that it isn't run multiple times when there is
327 // inlining happening.
328 if (LangOpts.ObjCAutoRefCount)
329 PM->add(createObjCARCContractPass());
330
Daniel Dunbar897c6762010-06-07 23:20:08 +0000331 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
332 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
333 Diags.Report(diag::err_fe_unable_to_interface_with_target);
334 return false;
335 }
336
337 return true;
338}
339
340void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
341 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
342 llvm::formatted_raw_ostream FormattedOS;
343
344 CreatePasses();
345 switch (Action) {
346 case Backend_EmitNothing:
347 break;
348
349 case Backend_EmitBC:
350 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
351 break;
352
353 case Backend_EmitLL:
354 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
355 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
356 break;
357
358 default:
359 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
360 if (!AddEmitPasses(Action, FormattedOS))
361 return;
362 }
363
Andrew Trick92b5d942011-04-05 18:56:55 +0000364 // Before executing passes, print the final values of the LLVM options.
365 cl::PrintOptionValues();
366
Daniel Dunbar897c6762010-06-07 23:20:08 +0000367 // Run passes. For now we do all passes at once, but eventually we
368 // would like to have the option of streaming code generation.
369
370 if (PerFunctionPasses) {
371 PrettyStackTraceString CrashInfo("Per-function optimization");
372
373 PerFunctionPasses->doInitialization();
374 for (Module::iterator I = TheModule->begin(),
375 E = TheModule->end(); I != E; ++I)
376 if (!I->isDeclaration())
377 PerFunctionPasses->run(*I);
378 PerFunctionPasses->doFinalization();
379 }
380
381 if (PerModulePasses) {
382 PrettyStackTraceString CrashInfo("Per-module optimization passes");
383 PerModulePasses->run(*TheModule);
384 }
385
386 if (CodeGenPasses) {
387 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000388 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000389 }
390}
391
392void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000393 const TargetOptions &TOpts,
394 const LangOptions &LOpts,
395 Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000396 BackendAction Action, raw_ostream *OS) {
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000397 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000398
399 AsmHelper.EmitAssembly(Action, OS);
400}