blob: dd372b195de9cdefe0e2feac68236710c3fa7d2f [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"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000017#include "clang/Driver/CompileOptions.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000018#include "llvm/Module.h"
19#include "llvm/ModuleProvider.h"
20#include "llvm/PassManager.h"
21#include "llvm/ADT/OwningPtr.h"
22#include "llvm/Assembly/PrintModulePass.h"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000023#include "llvm/Analysis/CallGraph.h"
24#include "llvm/Analysis/Verifier.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000025#include "llvm/Bitcode/ReaderWriter.h"
26#include "llvm/CodeGen/RegAllocRegistry.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
28#include "llvm/CodeGen/ScheduleDAG.h"
29#include "llvm/Support/raw_ostream.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000030#include "llvm/Support/Compiler.h"
31#include "llvm/System/Path.h"
32#include "llvm/System/Program.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetMachineRegistry.h"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000036#include "llvm/Transforms/Scalar.h"
37#include "llvm/Transforms/IPO.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000038#include <fstream> // FIXME: Remove
39
40using namespace clang;
41using namespace llvm;
42
43namespace {
44 class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
45 BackendAction Action;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000046 CompileOptions CompileOpts;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000047 const std::string &InputFile;
48 std::string OutputFile;
49 llvm::OwningPtr<CodeGenerator> Gen;
50
51 llvm::Module *TheModule;
52 llvm::TargetData *TheTargetData;
53 llvm::raw_ostream *AsmOutStream;
54
55 mutable FunctionPassManager *CodeGenPasses;
56 mutable PassManager *PerModulePasses;
57 mutable FunctionPassManager *PerFunctionPasses;
58
59 FunctionPassManager *getCodeGenPasses() const;
60 PassManager *getPerModulePasses() const;
61 FunctionPassManager *getPerFunctionPasses() const;
62
63 void CreatePasses();
64
65 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
66 /// IR.
67 ///
68 /// \arg Fast - Whether "fast" native compilation should be
69 /// used. This implies local register allocation and fast
70 /// instruction selection.
71 /// \return True on success. On failure \arg Error will be set to
72 /// a user readable error message.
73 bool AddEmitPasses(bool Fast, std::string &Error);
74
75 void EmitAssembly();
76
77 public:
78 BackendConsumer(BackendAction action, Diagnostic &Diags,
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000079 const LangOptions &Features, const CompileOptions &compopts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +000080 const std::string& infile, const std::string& outfile,
81 bool GenerateDebugInfo) :
82 Action(action),
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000083 CompileOpts(compopts),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000084 InputFile(infile),
85 OutputFile(outfile),
86 Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
Daniel Dunbare5dbb072008-10-22 17:40:45 +000087 TheModule(0), TheTargetData(0), AsmOutStream(0),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000088 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
89
90 ~BackendConsumer() {
91 // FIXME: Move out of destructor.
92 EmitAssembly();
93
94 delete AsmOutStream;
95 delete TheTargetData;
96 delete TheModule;
97 delete CodeGenPasses;
98 delete PerModulePasses;
99 delete PerFunctionPasses;
100 }
101
102 virtual void InitializeTU(TranslationUnit& TU) {
103 Gen->InitializeTU(TU);
104
105 TheModule = Gen->GetModule();
106 TheTargetData =
107 new llvm::TargetData(TU.getContext().Target.getTargetDescription());
108 }
109
110 virtual void HandleTopLevelDecl(Decl *D) {
111 Gen->HandleTopLevelDecl(D);
112 }
113
114 virtual void HandleTranslationUnit(TranslationUnit& TU) {
115 Gen->HandleTranslationUnit(TU);
116 }
117
118 virtual void HandleTagDeclDefinition(TagDecl *D) {
119 Gen->HandleTagDeclDefinition(D);
120 }
121 };
122}
123
124FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
125 if (!CodeGenPasses) {
126 CodeGenPasses =
127 new FunctionPassManager(new ExistingModuleProvider(TheModule));
128 CodeGenPasses->add(new TargetData(*TheTargetData));
129 }
130
131 return CodeGenPasses;
132}
133
134PassManager *BackendConsumer::getPerModulePasses() const {
135 if (!PerModulePasses) {
136 PerModulePasses = new PassManager();
137 PerModulePasses->add(new TargetData(*TheTargetData));
138 }
139
140 return PerModulePasses;
141}
142
143FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
144 if (!PerFunctionPasses) {
145 PerFunctionPasses =
146 new FunctionPassManager(new ExistingModuleProvider(TheModule));
147 PerFunctionPasses->add(new TargetData(*TheTargetData));
148 }
149
150 return PerFunctionPasses;
151}
152
153bool BackendConsumer::AddEmitPasses(bool Fast, std::string &Error) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000154 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000155 AsmOutStream = new raw_stdout_ostream();
156 sys::Program::ChangeStdoutToBinary();
157 } else {
158 if (OutputFile.empty()) {
159 llvm::sys::Path Path(InputFile);
160 Path.eraseSuffix();
161 if (Action == Backend_EmitBC) {
162 Path.appendSuffix("bc");
163 } else if (Action == Backend_EmitLL) {
164 Path.appendSuffix("ll");
165 } else {
166 Path.appendSuffix("s");
167 }
168 OutputFile = Path.toString();
169 }
170
Daniel Dunbare5dbb072008-10-22 17:40:45 +0000171 // FIXME: Should be binary.
172 AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), Error);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000173 if (!Error.empty())
174 return false;
175 }
176
177 if (Action == Backend_EmitBC) {
Daniel Dunbare5dbb072008-10-22 17:40:45 +0000178 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000179 } else if (Action == Backend_EmitLL) {
Daniel Dunbar092a7442008-10-22 03:28:13 +0000180 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000181 } else {
Daniel Dunbaraed93f22008-10-22 18:29:51 +0000182 // Create the TargetMachine for generating code.
183 const TargetMachineRegistry::entry *TME =
184 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
185 if (!TME) {
186 Error = std::string("Unable to get target machine: ") + Error;
187 return false;
188 }
189
190 // FIXME: Support features?
191 std::string FeatureStr;
192 TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
193
194 // Set register scheduler & allocation policy.
195 RegisterScheduler::setDefault(createDefaultScheduler);
196 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
197 createLinearScanRegisterAllocator);
198
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000199 // From llvm-gcc:
200 // If there are passes we have to run on the entire module, we do codegen
201 // as a separate "pass" after that happens.
202 // FIXME: This is disabled right now until bugs can be worked out. Reenable
203 // this for fast -O0 compiles!
204 FunctionPassManager *PM = getCodeGenPasses();
205
206 // Normal mode, emit a .s file by running the code generator.
207 // Note, this also adds codegenerator level optimization passes.
208 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
209 TargetMachine::AssemblyFile, Fast)) {
210 default:
211 case FileModel::Error:
212 Error = "Unable to interface with target machine!\n";
213 return false;
214 case FileModel::AsmFile:
215 break;
216 }
217
218 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
219 Error = "Unable to interface with target machine!\n";
220 return false;
221 }
222 }
223
224 return true;
225}
226
227void BackendConsumer::CreatePasses() {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000228 // In -O0 if checking is disabled, we don't even have per-function passes.
229 if (CompileOpts.VerifyModule)
230 getPerFunctionPasses()->add(createVerifierPass());
231
232 if (CompileOpts.OptimizationLevel > 0) {
233 FunctionPassManager *PM = getPerFunctionPasses();
234 PM->add(createCFGSimplificationPass());
235 if (CompileOpts.OptimizationLevel == 1)
236 PM->add(createPromoteMemoryToRegisterPass());
237 else
238 PM->add(createScalarReplAggregatesPass());
239 PM->add(createInstructionCombiningPass());
240 }
241
242 // For now we always create per module passes.
243 PassManager *PM = getPerModulePasses();
244 if (CompileOpts.OptimizationLevel > 0) {
245 if (CompileOpts.UnitAtATime)
246 PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
247 PM->add(createCFGSimplificationPass()); // Clean up disgusting code
248 PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
249 if (CompileOpts.UnitAtATime) {
250 PM->add(createGlobalOptimizerPass()); // Optimize out global vars
251 PM->add(createGlobalDCEPass()); // Remove unused fns and globs
252 PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
253 PM->add(createDeadArgEliminationPass()); // Dead argument elimination
254 }
255 PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
256 PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
257 if (CompileOpts.UnitAtATime) {
258 PM->add(createPruneEHPass()); // Remove dead EH info
259 PM->add(createAddReadAttrsPass()); // Set readonly/readnone attrs
260 }
261 if (CompileOpts.InlineFunctions)
262 PM->add(createFunctionInliningPass()); // Inline small functions
263 else
264 PM->add(createAlwaysInlinerPass()); // Respect always_inline
265 if (CompileOpts.OptimizationLevel > 2)
266 PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
267 if (CompileOpts.SimplifyLibCalls)
268 PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
269 PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
270 PM->add(createJumpThreadingPass()); // Thread jumps.
271 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
272 PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
273 PM->add(createInstructionCombiningPass()); // Combine silly seq's
274 PM->add(createCondPropagationPass()); // Propagate conditionals
275 PM->add(createTailCallEliminationPass()); // Eliminate tail calls
276 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
277 PM->add(createReassociatePass()); // Reassociate expressions
278 PM->add(createLoopRotatePass()); // Rotate Loop
279 PM->add(createLICMPass()); // Hoist loop invariants
280 PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
281 PM->add(createLoopIndexSplitPass()); // Split loop index
282 PM->add(createInstructionCombiningPass());
283 PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
284 PM->add(createLoopDeletionPass()); // Delete dead loops
285 if (CompileOpts.UnrollLoops)
286 PM->add(createLoopUnrollPass()); // Unroll small loops
287 PM->add(createInstructionCombiningPass()); // Clean up after the unroller
288 PM->add(createGVNPass()); // Remove redundancies
289 PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
290 PM->add(createSCCPPass()); // Constant prop with SCCP
291
292 // Run instcombine after redundancy elimination to exploit opportunities
293 // opened up by them.
294 PM->add(createInstructionCombiningPass());
295 PM->add(createCondPropagationPass()); // Propagate conditionals
296 PM->add(createDeadStoreEliminationPass()); // Delete dead stores
297 PM->add(createAggressiveDCEPass()); // Delete dead instructions
298 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
299
300 if (CompileOpts.UnitAtATime) {
301 PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
302 PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
303 }
304
305 if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
306 PM->add(createConstantMergePass()); // Merge dup global constants
307 } else {
308 PerModulePasses->add(createAlwaysInlinerPass());
309 }
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000310}
311
312/// EmitAssembly - Handle interaction with LLVM backend to generate
313/// actual machine code.
314void BackendConsumer::EmitAssembly() {
315 // Silently ignore if we weren't initialized for some reason.
316 if (!TheModule || !TheTargetData)
317 return;
318
319 bool Optimize = false; // FIXME
320
321 // Make sure IR generation is happy with the module.
322 // FIXME: Release this.
323 Module *M = Gen->ReleaseModule();
324 if (!M) {
325 TheModule = 0;
326 return;
327 }
328
329 assert(TheModule == M && "Unexpected module change during IR generation");
330
331 CreatePasses();
332
333 std::string Error;
334 if (!AddEmitPasses(!Optimize, Error)) {
335 // FIXME: Don't fail this way.
336 llvm::cerr << "ERROR: " << Error << "\n";
337 ::exit(1);
338 }
339
340 // Run passes. For now we do all passes at once, but eventually we
341 // would like to have the option of streaming code generation.
342
343 if (PerFunctionPasses) {
344 PerFunctionPasses->doInitialization();
345 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
346 if (!I->isDeclaration())
347 PerFunctionPasses->run(*I);
348 PerFunctionPasses->doFinalization();
349 }
350
351 if (PerModulePasses)
352 PerModulePasses->run(*M);
353
354 if (CodeGenPasses) {
355 CodeGenPasses->doInitialization();
356 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
357 if (!I->isDeclaration())
358 CodeGenPasses->run(*I);
359 CodeGenPasses->doFinalization();
360 }
361}
362
363ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
364 Diagnostic &Diags,
365 const LangOptions &Features,
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000366 const CompileOptions &CompileOpts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000367 const std::string& InFile,
368 const std::string& OutFile,
369 bool GenerateDebugInfo) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000370 return new BackendConsumer(Action, Diags, Features, CompileOpts,
371 InFile, OutFile, GenerateDebugInfo);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000372}