blob: 328f08087b02d69e62ff5cd301accf60d78e8b9a [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
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 Dunbar70f92432008-10-23 05:50:47 +000017#include "clang/Driver/CompileOptions.h"
Daniel Dunbard69bacc2008-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 Dunbar70f92432008-10-23 05:50:47 +000023#include "llvm/Analysis/CallGraph.h"
24#include "llvm/Analysis/Verifier.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000025#include "llvm/Bitcode/ReaderWriter.h"
26#include "llvm/CodeGen/RegAllocRegistry.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000028#include "llvm/Support/raw_ostream.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000029#include "llvm/Support/Compiler.h"
30#include "llvm/System/Path.h"
31#include "llvm/System/Program.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetMachineRegistry.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000035#include "llvm/Transforms/Scalar.h"
36#include "llvm/Transforms/IPO.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000037
38using namespace clang;
39using namespace llvm;
40
41namespace {
42 class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
43 BackendAction Action;
Daniel Dunbar70f92432008-10-23 05:50:47 +000044 CompileOptions CompileOpts;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000045 const std::string &InputFile;
46 std::string OutputFile;
Daniel Dunbar90f41302008-10-29 08:50:02 +000047 bool GenerateDebugInfo;
48
Daniel Dunbard69bacc2008-10-21 23:49:24 +000049 llvm::OwningPtr<CodeGenerator> Gen;
50
51 llvm::Module *TheModule;
52 llvm::TargetData *TheTargetData;
53 llvm::raw_ostream *AsmOutStream;
54
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 Dunbar70f92432008-10-23 05:50:47 +000077 const LangOptions &Features, const CompileOptions &compopts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +000078 const std::string& infile, const std::string& outfile,
Daniel Dunbar90f41302008-10-29 08:50:02 +000079 bool debug) :
Daniel Dunbard69bacc2008-10-21 23:49:24 +000080 Action(action),
Daniel Dunbar70f92432008-10-23 05:50:47 +000081 CompileOpts(compopts),
Daniel Dunbard69bacc2008-10-21 23:49:24 +000082 InputFile(infile),
83 OutputFile(outfile),
Daniel Dunbar90f41302008-10-29 08:50:02 +000084 GenerateDebugInfo(debug),
Daniel Dunbard69bacc2008-10-21 23:49:24 +000085 Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
Nuno Lopesdd492672008-10-24 22:51:00 +000086 TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),
Daniel Dunbard69bacc2008-10-21 23:49:24 +000087 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
88
89 ~BackendConsumer() {
Daniel Dunbard69bacc2008-10-21 23:49:24 +000090 delete AsmOutStream;
91 delete TheTargetData;
Nuno Lopesdd492672008-10-24 22:51:00 +000092 delete ModuleProvider;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000093 delete CodeGenPasses;
94 delete PerModulePasses;
95 delete PerFunctionPasses;
96 }
97
98 virtual void InitializeTU(TranslationUnit& TU) {
99 Gen->InitializeTU(TU);
100
101 TheModule = Gen->GetModule();
Nuno Lopes7d43a312008-10-24 23:27:18 +0000102 ModuleProvider = new ExistingModuleProvider(TheModule);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000103 TheTargetData =
104 new llvm::TargetData(TU.getContext().Target.getTargetDescription());
105 }
106
107 virtual void HandleTopLevelDecl(Decl *D) {
108 Gen->HandleTopLevelDecl(D);
109 }
110
111 virtual void HandleTranslationUnit(TranslationUnit& TU) {
112 Gen->HandleTranslationUnit(TU);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000113
114 EmitAssembly();
115 // Force a flush here in case we never get released.
116 if (AsmOutStream)
117 AsmOutStream->flush();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000118 }
119
120 virtual void HandleTagDeclDefinition(TagDecl *D) {
121 Gen->HandleTagDeclDefinition(D);
122 }
123 };
124}
125
126FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
127 if (!CodeGenPasses) {
Nuno Lopesdd492672008-10-24 22:51:00 +0000128 CodeGenPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000129 CodeGenPasses->add(new TargetData(*TheTargetData));
130 }
131
132 return CodeGenPasses;
133}
134
135PassManager *BackendConsumer::getPerModulePasses() const {
136 if (!PerModulePasses) {
137 PerModulePasses = new PassManager();
138 PerModulePasses->add(new TargetData(*TheTargetData));
139 }
140
141 return PerModulePasses;
142}
143
144FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
145 if (!PerFunctionPasses) {
Nuno Lopes7d43a312008-10-24 23:27:18 +0000146 PerFunctionPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000147 PerFunctionPasses->add(new TargetData(*TheTargetData));
148 }
149
150 return PerFunctionPasses;
151}
152
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000153bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000154 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
Daniel Dunbard69bacc2008-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 Dunbar26fb2722008-11-13 05:09:21 +0000171 AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000172 if (!Error.empty())
173 return false;
174 }
175
176 if (Action == Backend_EmitBC) {
Daniel Dunbared2cb282008-10-22 17:40:45 +0000177 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000178 } else if (Action == Backend_EmitLL) {
Daniel Dunbar11292b02008-10-22 03:28:13 +0000179 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000180 } else {
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000181 bool Fast = CompileOpts.OptimizationLevel == 0;
182
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000183 // Create the TargetMachine for generating code.
184 const TargetMachineRegistry::entry *TME =
185 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
186 if (!TME) {
187 Error = std::string("Unable to get target machine: ") + Error;
188 return false;
189 }
190
191 // FIXME: Support features?
192 std::string FeatureStr;
193 TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
194
195 // Set register scheduler & allocation policy.
196 RegisterScheduler::setDefault(createDefaultScheduler);
197 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
198 createLinearScanRegisterAllocator);
199
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000200 // From llvm-gcc:
201 // If there are passes we have to run on the entire module, we do codegen
202 // as a separate "pass" after that happens.
203 // FIXME: This is disabled right now until bugs can be worked out. Reenable
204 // this for fast -O0 compiles!
205 FunctionPassManager *PM = getCodeGenPasses();
206
207 // Normal mode, emit a .s file by running the code generator.
208 // Note, this also adds codegenerator level optimization passes.
209 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
210 TargetMachine::AssemblyFile, Fast)) {
211 default:
212 case FileModel::Error:
213 Error = "Unable to interface with target machine!\n";
214 return false;
215 case FileModel::AsmFile:
216 break;
217 }
218
219 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
220 Error = "Unable to interface with target machine!\n";
221 return false;
222 }
223 }
224
225 return true;
226}
227
228void BackendConsumer::CreatePasses() {
Daniel Dunbar70f92432008-10-23 05:50:47 +0000229 // In -O0 if checking is disabled, we don't even have per-function passes.
230 if (CompileOpts.VerifyModule)
231 getPerFunctionPasses()->add(createVerifierPass());
232
233 if (CompileOpts.OptimizationLevel > 0) {
234 FunctionPassManager *PM = getPerFunctionPasses();
235 PM->add(createCFGSimplificationPass());
236 if (CompileOpts.OptimizationLevel == 1)
237 PM->add(createPromoteMemoryToRegisterPass());
238 else
239 PM->add(createScalarReplAggregatesPass());
240 PM->add(createInstructionCombiningPass());
241 }
242
243 // For now we always create per module passes.
244 PassManager *PM = getPerModulePasses();
245 if (CompileOpts.OptimizationLevel > 0) {
246 if (CompileOpts.UnitAtATime)
247 PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
248 PM->add(createCFGSimplificationPass()); // Clean up disgusting code
249 PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
250 if (CompileOpts.UnitAtATime) {
251 PM->add(createGlobalOptimizerPass()); // Optimize out global vars
252 PM->add(createGlobalDCEPass()); // Remove unused fns and globs
253 PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
254 PM->add(createDeadArgEliminationPass()); // Dead argument elimination
255 }
256 PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
257 PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
258 if (CompileOpts.UnitAtATime) {
259 PM->add(createPruneEHPass()); // Remove dead EH info
Bill Wendling5c5a7ee2008-12-31 19:51:31 +0000260 PM->add(createFunctionAttrsPass()); // Set readonly/readnone attrs
Daniel Dunbar70f92432008-10-23 05:50:47 +0000261 }
262 if (CompileOpts.InlineFunctions)
263 PM->add(createFunctionInliningPass()); // Inline small functions
264 else
265 PM->add(createAlwaysInlinerPass()); // Respect always_inline
266 if (CompileOpts.OptimizationLevel > 2)
267 PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
268 if (CompileOpts.SimplifyLibCalls)
269 PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
270 PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
271 PM->add(createJumpThreadingPass()); // Thread jumps.
272 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
273 PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
274 PM->add(createInstructionCombiningPass()); // Combine silly seq's
275 PM->add(createCondPropagationPass()); // Propagate conditionals
276 PM->add(createTailCallEliminationPass()); // Eliminate tail calls
277 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
278 PM->add(createReassociatePass()); // Reassociate expressions
279 PM->add(createLoopRotatePass()); // Rotate Loop
280 PM->add(createLICMPass()); // Hoist loop invariants
281 PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
Devang Patel59db7602008-11-26 05:01:52 +0000282// PM->add(createLoopIndexSplitPass()); // Split loop index
Daniel Dunbar70f92432008-10-23 05:50:47 +0000283 PM->add(createInstructionCombiningPass());
284 PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
285 PM->add(createLoopDeletionPass()); // Delete dead loops
286 if (CompileOpts.UnrollLoops)
287 PM->add(createLoopUnrollPass()); // Unroll small loops
288 PM->add(createInstructionCombiningPass()); // Clean up after the unroller
289 PM->add(createGVNPass()); // Remove redundancies
290 PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
291 PM->add(createSCCPPass()); // Constant prop with SCCP
292
293 // Run instcombine after redundancy elimination to exploit opportunities
294 // opened up by them.
295 PM->add(createInstructionCombiningPass());
296 PM->add(createCondPropagationPass()); // Propagate conditionals
297 PM->add(createDeadStoreEliminationPass()); // Delete dead stores
298 PM->add(createAggressiveDCEPass()); // Delete dead instructions
299 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
300
301 if (CompileOpts.UnitAtATime) {
302 PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
303 PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
304 }
305
306 if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
307 PM->add(createConstantMergePass()); // Merge dup global constants
308 } else {
Daniel Dunbarb087ae92008-11-13 05:29:02 +0000309 PM->add(createAlwaysInlinerPass());
Daniel Dunbar70f92432008-10-23 05:50:47 +0000310 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000311}
312
313/// EmitAssembly - Handle interaction with LLVM backend to generate
314/// actual machine code.
315void BackendConsumer::EmitAssembly() {
316 // Silently ignore if we weren't initialized for some reason.
317 if (!TheModule || !TheTargetData)
318 return;
319
Daniel Dunbard611bac2008-10-27 20:40:41 +0000320 // Make sure IR generation is happy with the module. This is
321 // released by the module provider.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000322 Module *M = Gen->ReleaseModule();
323 if (!M) {
Daniel Dunbard611bac2008-10-27 20:40:41 +0000324 // The module has been released by IR gen on failures, do not
325 // double free.
326 ModuleProvider->releaseModule();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000327 TheModule = 0;
328 return;
329 }
330
331 assert(TheModule == M && "Unexpected module change during IR generation");
332
333 CreatePasses();
334
335 std::string Error;
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000336 if (!AddEmitPasses(Error)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000337 // FIXME: Don't fail this way.
338 llvm::cerr << "ERROR: " << Error << "\n";
339 ::exit(1);
340 }
341
342 // Run passes. For now we do all passes at once, but eventually we
343 // would like to have the option of streaming code generation.
344
345 if (PerFunctionPasses) {
346 PerFunctionPasses->doInitialization();
347 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
348 if (!I->isDeclaration())
349 PerFunctionPasses->run(*I);
350 PerFunctionPasses->doFinalization();
351 }
352
353 if (PerModulePasses)
354 PerModulePasses->run(*M);
355
356 if (CodeGenPasses) {
357 CodeGenPasses->doInitialization();
358 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
359 if (!I->isDeclaration())
360 CodeGenPasses->run(*I);
361 CodeGenPasses->doFinalization();
362 }
363}
364
365ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
366 Diagnostic &Diags,
367 const LangOptions &Features,
Daniel Dunbar70f92432008-10-23 05:50:47 +0000368 const CompileOptions &CompileOpts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000369 const std::string& InFile,
370 const std::string& OutFile,
371 bool GenerateDebugInfo) {
Daniel Dunbar70f92432008-10-23 05:50:47 +0000372 return new BackendConsumer(Action, Diags, Features, CompileOpts,
373 InFile, OutFile, GenerateDebugInfo);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000374}