blob: 32dbbf21a46b74ea8b0cf870a4fe23d5ccbd4542 [file] [log] [blame]
Daniel Dunbar85e44e22008-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
10#include "ASTConsumers.h"
11
12#include "clang/AST/ASTContext.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/TranslationUnit.h"
15#include "clang/Basic/TargetInfo.h"
16#include "clang/CodeGen/ModuleBuilder.h"
17#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"
22#include "llvm/Bitcode/ReaderWriter.h"
23#include "llvm/CodeGen/RegAllocRegistry.h"
24#include "llvm/CodeGen/SchedulerRegistry.h"
25#include "llvm/CodeGen/ScheduleDAG.h"
26#include "llvm/Support/raw_ostream.h"
27#include "llvm/Support/Streams.h"
28#include "llvm/Support/Compiler.h"
29#include "llvm/System/Path.h"
30#include "llvm/System/Program.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetMachineRegistry.h"
34#include <fstream> // FIXME: Remove
35
36using namespace clang;
37using namespace llvm;
38
39namespace {
40 class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
41 BackendAction Action;
42 const std::string &InputFile;
43 std::string OutputFile;
44 llvm::OwningPtr<CodeGenerator> Gen;
45
46 llvm::Module *TheModule;
47 llvm::TargetData *TheTargetData;
48 llvm::raw_ostream *AsmOutStream;
49
50 mutable FunctionPassManager *CodeGenPasses;
51 mutable PassManager *PerModulePasses;
52 mutable FunctionPassManager *PerFunctionPasses;
53
54 FunctionPassManager *getCodeGenPasses() const;
55 PassManager *getPerModulePasses() const;
56 FunctionPassManager *getPerFunctionPasses() const;
57
58 void CreatePasses();
59
60 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
61 /// IR.
62 ///
63 /// \arg Fast - Whether "fast" native compilation should be
64 /// used. This implies local register allocation and fast
65 /// instruction selection.
66 /// \return True on success. On failure \arg Error will be set to
67 /// a user readable error message.
68 bool AddEmitPasses(bool Fast, std::string &Error);
69
70 void EmitAssembly();
71
72 public:
73 BackendConsumer(BackendAction action, Diagnostic &Diags,
74 const LangOptions &Features,
75 const std::string& infile, const std::string& outfile,
76 bool GenerateDebugInfo) :
77 Action(action),
78 InputFile(infile),
79 OutputFile(outfile),
80 Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
81 TheModule(0), TheTargetData(0), AsmOutStream(0),
82 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
83
84 ~BackendConsumer() {
85 // FIXME: Move out of destructor.
86 EmitAssembly();
87
88 delete AsmOutStream;
89 delete TheTargetData;
90 delete TheModule;
91 delete CodeGenPasses;
92 delete PerModulePasses;
93 delete PerFunctionPasses;
94 }
95
96 virtual void InitializeTU(TranslationUnit& TU) {
97 Gen->InitializeTU(TU);
98
99 TheModule = Gen->GetModule();
100 TheTargetData =
101 new llvm::TargetData(TU.getContext().Target.getTargetDescription());
102 }
103
104 virtual void HandleTopLevelDecl(Decl *D) {
105 Gen->HandleTopLevelDecl(D);
106 }
107
108 virtual void HandleTranslationUnit(TranslationUnit& TU) {
109 Gen->HandleTranslationUnit(TU);
110 }
111
112 virtual void HandleTagDeclDefinition(TagDecl *D) {
113 Gen->HandleTagDeclDefinition(D);
114 }
115 };
116}
117
118FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
119 if (!CodeGenPasses) {
120 CodeGenPasses =
121 new FunctionPassManager(new ExistingModuleProvider(TheModule));
122 CodeGenPasses->add(new TargetData(*TheTargetData));
123 }
124
125 return CodeGenPasses;
126}
127
128PassManager *BackendConsumer::getPerModulePasses() const {
129 if (!PerModulePasses) {
130 PerModulePasses = new PassManager();
131 PerModulePasses->add(new TargetData(*TheTargetData));
132 }
133
134 return PerModulePasses;
135}
136
137FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
138 if (!PerFunctionPasses) {
139 PerFunctionPasses =
140 new FunctionPassManager(new ExistingModuleProvider(TheModule));
141 PerFunctionPasses->add(new TargetData(*TheTargetData));
142 }
143
144 return PerFunctionPasses;
145}
146
147bool BackendConsumer::AddEmitPasses(bool Fast, std::string &Error) {
148 // Create the TargetMachine for generating code.
149 const TargetMachineRegistry::entry *TME =
150 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
151 if (!TME) {
152 Error = std::string("Unable to get target machine: ") + Error;
153 return false;
154 }
155
156 // FIXME: Support features?
157 std::string FeatureStr;
158 TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
159
160 // Set register scheduler & allocation policy.
161 RegisterScheduler::setDefault(createDefaultScheduler);
162 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
163 createLinearScanRegisterAllocator);
164
165 // This is ridiculous.
166 // FIXME: These aren't being release for now. I'm just going to fix
167 // things to use raw_ostream instead.
168 std::ostream *AsmStdOutStream = 0;
169 OStream *AsmLLVMOutStream = 0;
170 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
171 AsmStdOutStream = llvm::cout.stream();
172 AsmLLVMOutStream = &llvm::cout;
173 AsmOutStream = new raw_stdout_ostream();
174 sys::Program::ChangeStdoutToBinary();
175 } else {
176 if (OutputFile.empty()) {
177 llvm::sys::Path Path(InputFile);
178 Path.eraseSuffix();
179 if (Action == Backend_EmitBC) {
180 Path.appendSuffix("bc");
181 } else if (Action == Backend_EmitLL) {
182 Path.appendSuffix("ll");
183 } else {
184 Path.appendSuffix("s");
185 }
186 OutputFile = Path.toString();
187 }
188
189 // FIXME: raw_fd_ostream should specify its non-error condition
190 // better.
191 Error = "";
192 AsmStdOutStream = new std::ofstream(OutputFile.c_str(),
193 (std::ios_base::binary |
194 std::ios_base::out));
195 AsmLLVMOutStream = new OStream(AsmStdOutStream);
196 AsmOutStream = new raw_os_ostream(*AsmStdOutStream);
197 if (!Error.empty())
198 return false;
199 }
200
201 if (Action == Backend_EmitBC) {
202 getPerModulePasses()->add(CreateBitcodeWriterPass(*AsmStdOutStream));
203 } else if (Action == Backend_EmitLL) {
204 getPerModulePasses()->add(createPrintModulePass(AsmLLVMOutStream));
205 } else {
206 // From llvm-gcc:
207 // If there are passes we have to run on the entire module, we do codegen
208 // as a separate "pass" after that happens.
209 // FIXME: This is disabled right now until bugs can be worked out. Reenable
210 // this for fast -O0 compiles!
211 FunctionPassManager *PM = getCodeGenPasses();
212
213 // Normal mode, emit a .s file by running the code generator.
214 // Note, this also adds codegenerator level optimization passes.
215 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
216 TargetMachine::AssemblyFile, Fast)) {
217 default:
218 case FileModel::Error:
219 Error = "Unable to interface with target machine!\n";
220 return false;
221 case FileModel::AsmFile:
222 break;
223 }
224
225 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
226 Error = "Unable to interface with target machine!\n";
227 return false;
228 }
229 }
230
231 return true;
232}
233
234void BackendConsumer::CreatePasses() {
235
236}
237
238/// EmitAssembly - Handle interaction with LLVM backend to generate
239/// actual machine code.
240void BackendConsumer::EmitAssembly() {
241 // Silently ignore if we weren't initialized for some reason.
242 if (!TheModule || !TheTargetData)
243 return;
244
245 bool Optimize = false; // FIXME
246
247 // Make sure IR generation is happy with the module.
248 // FIXME: Release this.
249 Module *M = Gen->ReleaseModule();
250 if (!M) {
251 TheModule = 0;
252 return;
253 }
254
255 assert(TheModule == M && "Unexpected module change during IR generation");
256
257 CreatePasses();
258
259 std::string Error;
260 if (!AddEmitPasses(!Optimize, Error)) {
261 // FIXME: Don't fail this way.
262 llvm::cerr << "ERROR: " << Error << "\n";
263 ::exit(1);
264 }
265
266 // Run passes. For now we do all passes at once, but eventually we
267 // would like to have the option of streaming code generation.
268
269 if (PerFunctionPasses) {
270 PerFunctionPasses->doInitialization();
271 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
272 if (!I->isDeclaration())
273 PerFunctionPasses->run(*I);
274 PerFunctionPasses->doFinalization();
275 }
276
277 if (PerModulePasses)
278 PerModulePasses->run(*M);
279
280 if (CodeGenPasses) {
281 CodeGenPasses->doInitialization();
282 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
283 if (!I->isDeclaration())
284 CodeGenPasses->run(*I);
285 CodeGenPasses->doFinalization();
286 }
287}
288
289ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
290 Diagnostic &Diags,
291 const LangOptions &Features,
292 const std::string& InFile,
293 const std::string& OutFile,
294 bool GenerateDebugInfo) {
295 return new BackendConsumer(Action, Diags, Features, InFile, OutFile,
296 GenerateDebugInfo);
297}