blob: 9f36b2a1a1ee3559d1ff20926f0da9de582a9bd9 [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;
Daniel Dunbar092a7442008-10-22 03:28:13 +000049 std::ostream *AsmStdOutStream;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000050
51 mutable FunctionPassManager *CodeGenPasses;
52 mutable PassManager *PerModulePasses;
53 mutable FunctionPassManager *PerFunctionPasses;
54
55 FunctionPassManager *getCodeGenPasses() const;
56 PassManager *getPerModulePasses() const;
57 FunctionPassManager *getPerFunctionPasses() const;
58
59 void CreatePasses();
60
61 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
62 /// IR.
63 ///
64 /// \arg Fast - Whether "fast" native compilation should be
65 /// used. This implies local register allocation and fast
66 /// instruction selection.
67 /// \return True on success. On failure \arg Error will be set to
68 /// a user readable error message.
69 bool AddEmitPasses(bool Fast, std::string &Error);
70
71 void EmitAssembly();
72
73 public:
74 BackendConsumer(BackendAction action, Diagnostic &Diags,
75 const LangOptions &Features,
76 const std::string& infile, const std::string& outfile,
77 bool GenerateDebugInfo) :
78 Action(action),
79 InputFile(infile),
80 OutputFile(outfile),
81 Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
Daniel Dunbar092a7442008-10-22 03:28:13 +000082 TheModule(0), TheTargetData(0),
83 AsmOutStream(0), AsmStdOutStream(0),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000084 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
85
86 ~BackendConsumer() {
87 // FIXME: Move out of destructor.
88 EmitAssembly();
89
Daniel Dunbar092a7442008-10-22 03:28:13 +000090 if (AsmStdOutStream != llvm::cout.stream())
91 delete AsmStdOutStream;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000092 delete AsmOutStream;
93 delete TheTargetData;
94 delete TheModule;
95 delete CodeGenPasses;
96 delete PerModulePasses;
97 delete PerFunctionPasses;
98 }
99
100 virtual void InitializeTU(TranslationUnit& TU) {
101 Gen->InitializeTU(TU);
102
103 TheModule = Gen->GetModule();
104 TheTargetData =
105 new llvm::TargetData(TU.getContext().Target.getTargetDescription());
106 }
107
108 virtual void HandleTopLevelDecl(Decl *D) {
109 Gen->HandleTopLevelDecl(D);
110 }
111
112 virtual void HandleTranslationUnit(TranslationUnit& TU) {
113 Gen->HandleTranslationUnit(TU);
114 }
115
116 virtual void HandleTagDeclDefinition(TagDecl *D) {
117 Gen->HandleTagDeclDefinition(D);
118 }
119 };
120}
121
122FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
123 if (!CodeGenPasses) {
124 CodeGenPasses =
125 new FunctionPassManager(new ExistingModuleProvider(TheModule));
126 CodeGenPasses->add(new TargetData(*TheTargetData));
127 }
128
129 return CodeGenPasses;
130}
131
132PassManager *BackendConsumer::getPerModulePasses() const {
133 if (!PerModulePasses) {
134 PerModulePasses = new PassManager();
135 PerModulePasses->add(new TargetData(*TheTargetData));
136 }
137
138 return PerModulePasses;
139}
140
141FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
142 if (!PerFunctionPasses) {
143 PerFunctionPasses =
144 new FunctionPassManager(new ExistingModuleProvider(TheModule));
145 PerFunctionPasses->add(new TargetData(*TheTargetData));
146 }
147
148 return PerFunctionPasses;
149}
150
151bool BackendConsumer::AddEmitPasses(bool Fast, std::string &Error) {
152 // Create the TargetMachine for generating code.
153 const TargetMachineRegistry::entry *TME =
154 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
155 if (!TME) {
156 Error = std::string("Unable to get target machine: ") + Error;
157 return false;
158 }
159
160 // FIXME: Support features?
161 std::string FeatureStr;
162 TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
163
164 // Set register scheduler & allocation policy.
165 RegisterScheduler::setDefault(createDefaultScheduler);
166 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
167 createLinearScanRegisterAllocator);
168
169 // This is ridiculous.
170 // FIXME: These aren't being release for now. I'm just going to fix
171 // things to use raw_ostream instead.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000172 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
173 AsmStdOutStream = llvm::cout.stream();
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000174 AsmOutStream = new raw_stdout_ostream();
175 sys::Program::ChangeStdoutToBinary();
176 } else {
177 if (OutputFile.empty()) {
178 llvm::sys::Path Path(InputFile);
179 Path.eraseSuffix();
180 if (Action == Backend_EmitBC) {
181 Path.appendSuffix("bc");
182 } else if (Action == Backend_EmitLL) {
183 Path.appendSuffix("ll");
184 } else {
185 Path.appendSuffix("s");
186 }
187 OutputFile = Path.toString();
188 }
189
190 // FIXME: raw_fd_ostream should specify its non-error condition
191 // better.
192 Error = "";
193 AsmStdOutStream = new std::ofstream(OutputFile.c_str(),
194 (std::ios_base::binary |
195 std::ios_base::out));
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000196 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) {
Daniel Dunbar092a7442008-10-22 03:28:13 +0000204 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000205 } 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}