blob: 6b7f9ae940cc23e572cfd871addc9a18a716bdc3 [file] [log] [blame]
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001//===--- Backend.cpp - Interface to LLVM backend technologies -------------===//
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
Eli Friedman39d7c4d2009-05-18 22:50:54 +000010#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000011#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000012#include "clang/Frontend/CompileOptions.h"
Chris Lattner682bf922009-03-29 16:50:03 +000013#include "clang/AST/ASTContext.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/DeclGroup.h"
16#include "clang/Basic/TargetInfo.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000017#include "llvm/Module.h"
18#include "llvm/ModuleProvider.h"
19#include "llvm/PassManager.h"
20#include "llvm/ADT/OwningPtr.h"
21#include "llvm/Assembly/PrintModulePass.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000022#include "llvm/Analysis/CallGraph.h"
23#include "llvm/Analysis/Verifier.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000024#include "llvm/Bitcode/ReaderWriter.h"
25#include "llvm/CodeGen/RegAllocRegistry.h"
26#include "llvm/CodeGen/SchedulerRegistry.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000027#include "llvm/Support/raw_ostream.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000028#include "llvm/Support/Compiler.h"
Daniel Dunbar10d861e2009-06-03 18:01:18 +000029#include "llvm/Support/StandardPasses.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000030#include "llvm/Support/Timer.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000031#include "llvm/System/Path.h"
32#include "llvm/System/Program.h"
Daniel Dunbara034ba82009-02-17 19:47:34 +000033#include "llvm/Target/SubtargetFeature.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000034#include "llvm/Target/TargetData.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetMachineRegistry.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000037using namespace clang;
38using namespace llvm;
39
40namespace {
Chris Lattner49f28ca2009-03-05 08:00:35 +000041 class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
Daniel Dunbard69bacc2008-10-21 23:49:24 +000042 BackendAction Action;
Daniel Dunbar70f92432008-10-23 05:50:47 +000043 CompileOptions CompileOpts;
Eli Friedman66d6f042009-05-18 22:20:00 +000044 llvm::raw_ostream *AsmOutStream;
Chris Lattner49f28ca2009-03-05 08:00:35 +000045 ASTContext *Context;
Daniel Dunbar90f41302008-10-29 08:50:02 +000046
Chris Lattner6f114eb2009-02-18 01:37:30 +000047 Timer LLVMIRGeneration;
48 Timer CodeGenerationTime;
49
Daniel Dunbard69bacc2008-10-21 23:49:24 +000050 llvm::OwningPtr<CodeGenerator> Gen;
51
52 llvm::Module *TheModule;
53 llvm::TargetData *TheTargetData;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000054
Nuno Lopesdd492672008-10-24 22:51:00 +000055 mutable llvm::ModuleProvider *ModuleProvider;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000056 mutable FunctionPassManager *CodeGenPasses;
57 mutable PassManager *PerModulePasses;
58 mutable FunctionPassManager *PerFunctionPasses;
59
60 FunctionPassManager *getCodeGenPasses() const;
61 PassManager *getPerModulePasses() const;
62 FunctionPassManager *getPerFunctionPasses() const;
63
64 void CreatePasses();
65
66 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
67 /// IR.
68 ///
Daniel Dunbard69bacc2008-10-21 23:49:24 +000069 /// \return True on success. On failure \arg Error will be set to
70 /// a user readable error message.
Daniel Dunbar4c877cc2008-10-23 05:59:43 +000071 bool AddEmitPasses(std::string &Error);
Daniel Dunbard69bacc2008-10-21 23:49:24 +000072
73 void EmitAssembly();
74
75 public:
76 BackendConsumer(BackendAction action, Diagnostic &Diags,
Daniel Dunbara034ba82009-02-17 19:47:34 +000077 const LangOptions &langopts, const CompileOptions &compopts,
Owen Anderson42253cc2009-07-01 17:00:06 +000078 const std::string &infile, llvm::raw_ostream* OS,
Owen Andersonc93f4982009-07-01 21:23:16 +000079 const LLVMContext& C) :
Daniel Dunbard69bacc2008-10-21 23:49:24 +000080 Action(action),
Daniel Dunbar70f92432008-10-23 05:50:47 +000081 CompileOpts(compopts),
Eli Friedman66d6f042009-05-18 22:20:00 +000082 AsmOutStream(OS),
Chris Lattner6f114eb2009-02-18 01:37:30 +000083 LLVMIRGeneration("LLVM IR Generation Time"),
84 CodeGenerationTime("Code Generation Time"),
Owen Anderson42253cc2009-07-01 17:00:06 +000085 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
Eli Friedman66d6f042009-05-18 22:20:00 +000086 TheModule(0), TheTargetData(0), ModuleProvider(0),
Chris Lattner44502662009-02-18 01:23:44 +000087 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {
88
Chris Lattner6f114eb2009-02-18 01:37:30 +000089 // Enable -time-passes if -ftime-report is enabled.
Chris Lattner44502662009-02-18 01:23:44 +000090 llvm::TimePassesIsEnabled = CompileOpts.TimePasses;
91 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +000092
93 ~BackendConsumer() {
Daniel Dunbard69bacc2008-10-21 23:49:24 +000094 delete TheTargetData;
Nuno Lopesdd492672008-10-24 22:51:00 +000095 delete ModuleProvider;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000096 delete CodeGenPasses;
97 delete PerModulePasses;
98 delete PerFunctionPasses;
99 }
100
Chris Lattner7bb0da02009-03-28 02:18:25 +0000101 virtual void Initialize(ASTContext &Ctx) {
102 Context = &Ctx;
Chris Lattner6f114eb2009-02-18 01:37:30 +0000103
104 if (CompileOpts.TimePasses)
105 LLVMIRGeneration.startTimer();
106
Chris Lattner7bb0da02009-03-28 02:18:25 +0000107 Gen->Initialize(Ctx);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000108
109 TheModule = Gen->GetModule();
Nuno Lopes7d43a312008-10-24 23:27:18 +0000110 ModuleProvider = new ExistingModuleProvider(TheModule);
Chris Lattner7bb0da02009-03-28 02:18:25 +0000111 TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription());
Chris Lattner6f114eb2009-02-18 01:37:30 +0000112
113 if (CompileOpts.TimePasses)
114 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000115 }
116
Chris Lattner682bf922009-03-29 16:50:03 +0000117 virtual void HandleTopLevelDecl(DeclGroupRef D) {
118 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattner49f28ca2009-03-05 08:00:35 +0000119 Context->getSourceManager(),
120 "LLVM IR generation of declaration");
Chris Lattner682bf922009-03-29 16:50:03 +0000121
Chris Lattner6f114eb2009-02-18 01:37:30 +0000122 if (CompileOpts.TimePasses)
123 LLVMIRGeneration.startTimer();
Chris Lattner682bf922009-03-29 16:50:03 +0000124
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000125 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +0000126
127 if (CompileOpts.TimePasses)
128 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000129 }
130
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000131 virtual void HandleTranslationUnit(ASTContext &C) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000132 {
Chris Lattner14f234e2009-03-06 06:46:31 +0000133 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Chris Lattner49f28ca2009-03-05 08:00:35 +0000134 if (CompileOpts.TimePasses)
135 LLVMIRGeneration.startTimer();
Chris Lattner6f114eb2009-02-18 01:37:30 +0000136
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000137 Gen->HandleTranslationUnit(C);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000138
Chris Lattner49f28ca2009-03-05 08:00:35 +0000139 if (CompileOpts.TimePasses)
140 LLVMIRGeneration.stopTimer();
141 }
Chris Lattner6f114eb2009-02-18 01:37:30 +0000142
Chris Lattner49f28ca2009-03-05 08:00:35 +0000143 // EmitAssembly times and registers crash info itself.
Chris Lattner6f114eb2009-02-18 01:37:30 +0000144 EmitAssembly();
145
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000146 // Force a flush here in case we never get released.
147 if (AsmOutStream)
148 AsmOutStream->flush();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000149 }
150
151 virtual void HandleTagDeclDefinition(TagDecl *D) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000152 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
153 Context->getSourceManager(),
154 "LLVM IR generation of declaration");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000155 Gen->HandleTagDeclDefinition(D);
156 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000157
158 virtual void CompleteTentativeDefinition(VarDecl *D) {
159 Gen->CompleteTentativeDefinition(D);
160 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000161 };
162}
163
164FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
165 if (!CodeGenPasses) {
Nuno Lopesdd492672008-10-24 22:51:00 +0000166 CodeGenPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000167 CodeGenPasses->add(new TargetData(*TheTargetData));
168 }
169
170 return CodeGenPasses;
171}
172
173PassManager *BackendConsumer::getPerModulePasses() const {
174 if (!PerModulePasses) {
175 PerModulePasses = new PassManager();
176 PerModulePasses->add(new TargetData(*TheTargetData));
177 }
178
179 return PerModulePasses;
180}
181
182FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
183 if (!PerFunctionPasses) {
Nuno Lopes7d43a312008-10-24 23:27:18 +0000184 PerFunctionPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000185 PerFunctionPasses->add(new TargetData(*TheTargetData));
186 }
187
188 return PerFunctionPasses;
189}
190
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000191bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbare8e26002009-02-26 22:39:37 +0000192 if (Action == Backend_EmitNothing)
193 return true;
194
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000195 if (Action == Backend_EmitBC) {
Daniel Dunbared2cb282008-10-22 17:40:45 +0000196 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000197 } else if (Action == Backend_EmitLL) {
Daniel Dunbar11292b02008-10-22 03:28:13 +0000198 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000199 } else {
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000200 bool Fast = CompileOpts.OptimizationLevel == 0;
201
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000202 // Create the TargetMachine for generating code.
203 const TargetMachineRegistry::entry *TME =
204 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
205 if (!TME) {
206 Error = std::string("Unable to get target machine: ") + Error;
207 return false;
208 }
Daniel Dunbara034ba82009-02-17 19:47:34 +0000209
210 std::string FeaturesStr;
211 if (CompileOpts.CPU.size() || CompileOpts.Features.size()) {
212 SubtargetFeatures Features;
213 Features.setCPU(CompileOpts.CPU);
214 for (std::vector<std::string>::iterator
215 it = CompileOpts.Features.begin(),
216 ie = CompileOpts.Features.end(); it != ie; ++it)
217 Features.AddFeature(*it);
218 FeaturesStr = Features.getString();
219 }
220 TargetMachine *TM = TME->CtorFn(*TheModule, FeaturesStr);
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000221
222 // Set register scheduler & allocation policy.
223 RegisterScheduler::setDefault(createDefaultScheduler);
224 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
225 createLinearScanRegisterAllocator);
226
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000227 // From llvm-gcc:
228 // If there are passes we have to run on the entire module, we do codegen
229 // as a separate "pass" after that happens.
230 // FIXME: This is disabled right now until bugs can be worked out. Reenable
231 // this for fast -O0 compiles!
232 FunctionPassManager *PM = getCodeGenPasses();
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000233 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
234
235 switch (CompileOpts.OptimizationLevel) {
236 default: break;
237 case 0: OptLevel = CodeGenOpt::None; break;
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000238 case 3: OptLevel = CodeGenOpt::Aggressive; break;
239 }
240
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000241 // Normal mode, emit a .s file by running the code generator.
242 // Note, this also adds codegenerator level optimization passes.
243 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000244 TargetMachine::AssemblyFile, OptLevel)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000245 default:
246 case FileModel::Error:
247 Error = "Unable to interface with target machine!\n";
248 return false;
249 case FileModel::AsmFile:
250 break;
251 }
252
Duncan Sands813a2bb2009-05-31 04:09:57 +0000253 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, (MachineCodeEmitter *)0,
254 OptLevel)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000255 Error = "Unable to interface with target machine!\n";
256 return false;
257 }
258 }
259
260 return true;
261}
262
263void BackendConsumer::CreatePasses() {
Daniel Dunbar70f92432008-10-23 05:50:47 +0000264 // In -O0 if checking is disabled, we don't even have per-function passes.
265 if (CompileOpts.VerifyModule)
266 getPerFunctionPasses()->add(createVerifierPass());
267
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000268 // Assume that standard function passes aren't run for -O0.
269 if (CompileOpts.OptimizationLevel > 0)
270 llvm::createStandardFunctionPasses(getPerFunctionPasses(),
271 CompileOpts.OptimizationLevel);
272
273 llvm::Pass *InliningPass = 0;
274 switch (CompileOpts.Inlining) {
275 case CompileOptions::NoInlining: break;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000276 case CompileOptions::NormalInlining: {
277 // Inline small functions
278 unsigned Threshold = (CompileOpts.OptimizeSize ||
279 CompileOpts.OptimizationLevel < 3) ? 50 : 200;
280 InliningPass = createFunctionInliningPass(Threshold);
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000281 break;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000282 }
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000283 case CompileOptions::OnlyAlwaysInlining:
284 InliningPass = createAlwaysInlinerPass(); // Respect always_inline
285 break;
Daniel Dunbar70f92432008-10-23 05:50:47 +0000286 }
287
288 // For now we always create per module passes.
289 PassManager *PM = getPerModulePasses();
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000290 llvm::createStandardModulePasses(PM, CompileOpts.OptimizationLevel,
291 CompileOpts.OptimizeSize,
292 CompileOpts.UnitAtATime,
293 CompileOpts.UnrollLoops,
294 CompileOpts.SimplifyLibCalls,
295 /*HaveExceptions=*/true,
296 InliningPass);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000297}
298
299/// EmitAssembly - Handle interaction with LLVM backend to generate
300/// actual machine code.
301void BackendConsumer::EmitAssembly() {
302 // Silently ignore if we weren't initialized for some reason.
303 if (!TheModule || !TheTargetData)
304 return;
Chris Lattner6f114eb2009-02-18 01:37:30 +0000305
Chris Lattner8b76c0d2009-02-18 18:22:50 +0000306 TimeRegion Region(CompileOpts.TimePasses ? &CodeGenerationTime : 0);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000307
Daniel Dunbard611bac2008-10-27 20:40:41 +0000308 // Make sure IR generation is happy with the module. This is
309 // released by the module provider.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000310 Module *M = Gen->ReleaseModule();
311 if (!M) {
Daniel Dunbard611bac2008-10-27 20:40:41 +0000312 // The module has been released by IR gen on failures, do not
313 // double free.
314 ModuleProvider->releaseModule();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000315 TheModule = 0;
316 return;
317 }
318
319 assert(TheModule == M && "Unexpected module change during IR generation");
320
321 CreatePasses();
322
323 std::string Error;
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000324 if (!AddEmitPasses(Error)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000325 // FIXME: Don't fail this way.
326 llvm::cerr << "ERROR: " << Error << "\n";
327 ::exit(1);
328 }
329
330 // Run passes. For now we do all passes at once, but eventually we
331 // would like to have the option of streaming code generation.
332
333 if (PerFunctionPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000334 PrettyStackTraceString CrashInfo("Per-function optimization");
Chris Lattner49f28ca2009-03-05 08:00:35 +0000335
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000336 PerFunctionPasses->doInitialization();
337 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
338 if (!I->isDeclaration())
339 PerFunctionPasses->run(*I);
340 PerFunctionPasses->doFinalization();
341 }
342
Chris Lattner49f28ca2009-03-05 08:00:35 +0000343 if (PerModulePasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000344 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000345 PerModulePasses->run(*M);
Chris Lattner49f28ca2009-03-05 08:00:35 +0000346 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000347
348 if (CodeGenPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000349 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000350 CodeGenPasses->doInitialization();
351 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
352 if (!I->isDeclaration())
353 CodeGenPasses->run(*I);
354 CodeGenPasses->doFinalization();
355 }
356}
357
358ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
359 Diagnostic &Diags,
Daniel Dunbara034ba82009-02-17 19:47:34 +0000360 const LangOptions &LangOpts,
Daniel Dunbar70f92432008-10-23 05:50:47 +0000361 const CompileOptions &CompileOpts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000362 const std::string& InFile,
Owen Anderson42253cc2009-07-01 17:00:06 +0000363 llvm::raw_ostream* OS,
Owen Andersonc93f4982009-07-01 21:23:16 +0000364 const LLVMContext& C) {
Owen Anderson42253cc2009-07-01 17:00:06 +0000365 return new BackendConsumer(Action, Diags, LangOpts, CompileOpts,
366 InFile, OS, C);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000367}