blob: d8f8625d67401df460d77d3fbbb693f71242023f [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,
Eli Friedman66d6f042009-05-18 22:20:00 +000078 const std::string &infile, llvm::raw_ostream* OS) :
Daniel Dunbard69bacc2008-10-21 23:49:24 +000079 Action(action),
Daniel Dunbar70f92432008-10-23 05:50:47 +000080 CompileOpts(compopts),
Eli Friedman66d6f042009-05-18 22:20:00 +000081 AsmOutStream(OS),
Chris Lattner6f114eb2009-02-18 01:37:30 +000082 LLVMIRGeneration("LLVM IR Generation Time"),
83 CodeGenerationTime("Code Generation Time"),
Eli Friedman66d6f042009-05-18 22:20:00 +000084 Gen(CreateLLVMCodeGen(Diags, infile, compopts)),
85 TheModule(0), TheTargetData(0), ModuleProvider(0),
Chris Lattner44502662009-02-18 01:23:44 +000086 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {
87
Chris Lattner6f114eb2009-02-18 01:37:30 +000088 // Enable -time-passes if -ftime-report is enabled.
Chris Lattner44502662009-02-18 01:23:44 +000089 llvm::TimePassesIsEnabled = CompileOpts.TimePasses;
90 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +000091
92 ~BackendConsumer() {
Daniel Dunbard69bacc2008-10-21 23:49:24 +000093 delete TheTargetData;
Nuno Lopesdd492672008-10-24 22:51:00 +000094 delete ModuleProvider;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000095 delete CodeGenPasses;
96 delete PerModulePasses;
97 delete PerFunctionPasses;
98 }
99
Chris Lattner7bb0da02009-03-28 02:18:25 +0000100 virtual void Initialize(ASTContext &Ctx) {
101 Context = &Ctx;
Chris Lattner6f114eb2009-02-18 01:37:30 +0000102
103 if (CompileOpts.TimePasses)
104 LLVMIRGeneration.startTimer();
105
Chris Lattner7bb0da02009-03-28 02:18:25 +0000106 Gen->Initialize(Ctx);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000107
108 TheModule = Gen->GetModule();
Nuno Lopes7d43a312008-10-24 23:27:18 +0000109 ModuleProvider = new ExistingModuleProvider(TheModule);
Chris Lattner7bb0da02009-03-28 02:18:25 +0000110 TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription());
Chris Lattner6f114eb2009-02-18 01:37:30 +0000111
112 if (CompileOpts.TimePasses)
113 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000114 }
115
Chris Lattner682bf922009-03-29 16:50:03 +0000116 virtual void HandleTopLevelDecl(DeclGroupRef D) {
117 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattner49f28ca2009-03-05 08:00:35 +0000118 Context->getSourceManager(),
119 "LLVM IR generation of declaration");
Chris Lattner682bf922009-03-29 16:50:03 +0000120
Chris Lattner6f114eb2009-02-18 01:37:30 +0000121 if (CompileOpts.TimePasses)
122 LLVMIRGeneration.startTimer();
Chris Lattner682bf922009-03-29 16:50:03 +0000123
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000124 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +0000125
126 if (CompileOpts.TimePasses)
127 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000128 }
129
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000130 virtual void HandleTranslationUnit(ASTContext &C) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000131 {
Chris Lattner14f234e2009-03-06 06:46:31 +0000132 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Chris Lattner49f28ca2009-03-05 08:00:35 +0000133 if (CompileOpts.TimePasses)
134 LLVMIRGeneration.startTimer();
Chris Lattner6f114eb2009-02-18 01:37:30 +0000135
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000136 Gen->HandleTranslationUnit(C);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000137
Chris Lattner49f28ca2009-03-05 08:00:35 +0000138 if (CompileOpts.TimePasses)
139 LLVMIRGeneration.stopTimer();
140 }
Chris Lattner6f114eb2009-02-18 01:37:30 +0000141
Chris Lattner49f28ca2009-03-05 08:00:35 +0000142 // EmitAssembly times and registers crash info itself.
Chris Lattner6f114eb2009-02-18 01:37:30 +0000143 EmitAssembly();
144
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000145 // Force a flush here in case we never get released.
146 if (AsmOutStream)
147 AsmOutStream->flush();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000148 }
149
150 virtual void HandleTagDeclDefinition(TagDecl *D) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000151 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
152 Context->getSourceManager(),
153 "LLVM IR generation of declaration");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000154 Gen->HandleTagDeclDefinition(D);
155 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000156
157 virtual void CompleteTentativeDefinition(VarDecl *D) {
158 Gen->CompleteTentativeDefinition(D);
159 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000160 };
161}
162
163FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
164 if (!CodeGenPasses) {
Nuno Lopesdd492672008-10-24 22:51:00 +0000165 CodeGenPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000166 CodeGenPasses->add(new TargetData(*TheTargetData));
167 }
168
169 return CodeGenPasses;
170}
171
172PassManager *BackendConsumer::getPerModulePasses() const {
173 if (!PerModulePasses) {
174 PerModulePasses = new PassManager();
175 PerModulePasses->add(new TargetData(*TheTargetData));
176 }
177
178 return PerModulePasses;
179}
180
181FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
182 if (!PerFunctionPasses) {
Nuno Lopes7d43a312008-10-24 23:27:18 +0000183 PerFunctionPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000184 PerFunctionPasses->add(new TargetData(*TheTargetData));
185 }
186
187 return PerFunctionPasses;
188}
189
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000190bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbare8e26002009-02-26 22:39:37 +0000191 if (Action == Backend_EmitNothing)
192 return true;
193
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000194 if (Action == Backend_EmitBC) {
Daniel Dunbared2cb282008-10-22 17:40:45 +0000195 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000196 } else if (Action == Backend_EmitLL) {
Daniel Dunbar11292b02008-10-22 03:28:13 +0000197 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000198 } else {
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000199 bool Fast = CompileOpts.OptimizationLevel == 0;
200
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000201 // Create the TargetMachine for generating code.
202 const TargetMachineRegistry::entry *TME =
203 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
204 if (!TME) {
205 Error = std::string("Unable to get target machine: ") + Error;
206 return false;
207 }
Daniel Dunbara034ba82009-02-17 19:47:34 +0000208
209 std::string FeaturesStr;
210 if (CompileOpts.CPU.size() || CompileOpts.Features.size()) {
211 SubtargetFeatures Features;
212 Features.setCPU(CompileOpts.CPU);
213 for (std::vector<std::string>::iterator
214 it = CompileOpts.Features.begin(),
215 ie = CompileOpts.Features.end(); it != ie; ++it)
216 Features.AddFeature(*it);
217 FeaturesStr = Features.getString();
218 }
219 TargetMachine *TM = TME->CtorFn(*TheModule, FeaturesStr);
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000220
221 // Set register scheduler & allocation policy.
222 RegisterScheduler::setDefault(createDefaultScheduler);
223 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
224 createLinearScanRegisterAllocator);
225
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000226 // From llvm-gcc:
227 // If there are passes we have to run on the entire module, we do codegen
228 // as a separate "pass" after that happens.
229 // FIXME: This is disabled right now until bugs can be worked out. Reenable
230 // this for fast -O0 compiles!
231 FunctionPassManager *PM = getCodeGenPasses();
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000232 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
233
234 switch (CompileOpts.OptimizationLevel) {
235 default: break;
236 case 0: OptLevel = CodeGenOpt::None; break;
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000237 case 3: OptLevel = CodeGenOpt::Aggressive; break;
238 }
239
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000240 // Normal mode, emit a .s file by running the code generator.
241 // Note, this also adds codegenerator level optimization passes.
242 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000243 TargetMachine::AssemblyFile, OptLevel)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000244 default:
245 case FileModel::Error:
246 Error = "Unable to interface with target machine!\n";
247 return false;
248 case FileModel::AsmFile:
249 break;
250 }
251
Duncan Sands813a2bb2009-05-31 04:09:57 +0000252 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, (MachineCodeEmitter *)0,
253 OptLevel)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000254 Error = "Unable to interface with target machine!\n";
255 return false;
256 }
257 }
258
259 return true;
260}
261
262void BackendConsumer::CreatePasses() {
Daniel Dunbar70f92432008-10-23 05:50:47 +0000263 // In -O0 if checking is disabled, we don't even have per-function passes.
264 if (CompileOpts.VerifyModule)
265 getPerFunctionPasses()->add(createVerifierPass());
266
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000267 // Assume that standard function passes aren't run for -O0.
268 if (CompileOpts.OptimizationLevel > 0)
269 llvm::createStandardFunctionPasses(getPerFunctionPasses(),
270 CompileOpts.OptimizationLevel);
271
272 llvm::Pass *InliningPass = 0;
273 switch (CompileOpts.Inlining) {
274 case CompileOptions::NoInlining: break;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000275 case CompileOptions::NormalInlining: {
276 // Inline small functions
277 unsigned Threshold = (CompileOpts.OptimizeSize ||
278 CompileOpts.OptimizationLevel < 3) ? 50 : 200;
279 InliningPass = createFunctionInliningPass(Threshold);
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000280 break;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000281 }
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000282 case CompileOptions::OnlyAlwaysInlining:
283 InliningPass = createAlwaysInlinerPass(); // Respect always_inline
284 break;
Daniel Dunbar70f92432008-10-23 05:50:47 +0000285 }
286
287 // For now we always create per module passes.
288 PassManager *PM = getPerModulePasses();
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000289 llvm::createStandardModulePasses(PM, CompileOpts.OptimizationLevel,
290 CompileOpts.OptimizeSize,
291 CompileOpts.UnitAtATime,
292 CompileOpts.UnrollLoops,
293 CompileOpts.SimplifyLibCalls,
294 /*HaveExceptions=*/true,
295 InliningPass);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000296}
297
298/// EmitAssembly - Handle interaction with LLVM backend to generate
299/// actual machine code.
300void BackendConsumer::EmitAssembly() {
301 // Silently ignore if we weren't initialized for some reason.
302 if (!TheModule || !TheTargetData)
303 return;
Chris Lattner6f114eb2009-02-18 01:37:30 +0000304
Chris Lattner8b76c0d2009-02-18 18:22:50 +0000305 TimeRegion Region(CompileOpts.TimePasses ? &CodeGenerationTime : 0);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000306
Daniel Dunbard611bac2008-10-27 20:40:41 +0000307 // Make sure IR generation is happy with the module. This is
308 // released by the module provider.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000309 Module *M = Gen->ReleaseModule();
310 if (!M) {
Daniel Dunbard611bac2008-10-27 20:40:41 +0000311 // The module has been released by IR gen on failures, do not
312 // double free.
313 ModuleProvider->releaseModule();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000314 TheModule = 0;
315 return;
316 }
317
318 assert(TheModule == M && "Unexpected module change during IR generation");
319
320 CreatePasses();
321
322 std::string Error;
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000323 if (!AddEmitPasses(Error)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000324 // FIXME: Don't fail this way.
325 llvm::cerr << "ERROR: " << Error << "\n";
326 ::exit(1);
327 }
328
329 // Run passes. For now we do all passes at once, but eventually we
330 // would like to have the option of streaming code generation.
331
332 if (PerFunctionPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000333 PrettyStackTraceString CrashInfo("Per-function optimization");
Chris Lattner49f28ca2009-03-05 08:00:35 +0000334
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000335 PerFunctionPasses->doInitialization();
336 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
337 if (!I->isDeclaration())
338 PerFunctionPasses->run(*I);
339 PerFunctionPasses->doFinalization();
340 }
341
Chris Lattner49f28ca2009-03-05 08:00:35 +0000342 if (PerModulePasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000343 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000344 PerModulePasses->run(*M);
Chris Lattner49f28ca2009-03-05 08:00:35 +0000345 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000346
347 if (CodeGenPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000348 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000349 CodeGenPasses->doInitialization();
350 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
351 if (!I->isDeclaration())
352 CodeGenPasses->run(*I);
353 CodeGenPasses->doFinalization();
354 }
355}
356
357ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
358 Diagnostic &Diags,
Daniel Dunbara034ba82009-02-17 19:47:34 +0000359 const LangOptions &LangOpts,
Daniel Dunbar70f92432008-10-23 05:50:47 +0000360 const CompileOptions &CompileOpts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000361 const std::string& InFile,
Eli Friedman66d6f042009-05-18 22:20:00 +0000362 llvm::raw_ostream* OS) {
363 return new BackendConsumer(Action, Diags, LangOpts, CompileOpts, InFile, OS);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000364}