blob: 51613994ca97b8396aec03ec55e05208802ae197 [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
39using namespace clang;
40using namespace llvm;
41
42namespace {
43 class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
44 BackendAction Action;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000045 CompileOptions CompileOpts;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000046 const std::string &InputFile;
47 std::string OutputFile;
Daniel Dunbar1a27a192008-10-29 08:50:02 +000048 bool GenerateDebugInfo;
49
Daniel Dunbar85e44e22008-10-21 23:49:24 +000050 llvm::OwningPtr<CodeGenerator> Gen;
51
52 llvm::Module *TheModule;
53 llvm::TargetData *TheTargetData;
54 llvm::raw_ostream *AsmOutStream;
55
Nuno Lopes74d92782008-10-24 22:51:00 +000056 mutable llvm::ModuleProvider *ModuleProvider;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000057 mutable FunctionPassManager *CodeGenPasses;
58 mutable PassManager *PerModulePasses;
59 mutable FunctionPassManager *PerFunctionPasses;
60
61 FunctionPassManager *getCodeGenPasses() const;
62 PassManager *getPerModulePasses() const;
63 FunctionPassManager *getPerFunctionPasses() const;
64
65 void CreatePasses();
66
67 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
68 /// IR.
69 ///
Daniel Dunbar85e44e22008-10-21 23:49:24 +000070 /// \return True on success. On failure \arg Error will be set to
71 /// a user readable error message.
Daniel Dunbar655d5092008-10-23 05:59:43 +000072 bool AddEmitPasses(std::string &Error);
Daniel Dunbar85e44e22008-10-21 23:49:24 +000073
74 void EmitAssembly();
75
76 public:
77 BackendConsumer(BackendAction action, Diagnostic &Diags,
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000078 const LangOptions &Features, const CompileOptions &compopts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +000079 const std::string& infile, const std::string& outfile,
Daniel Dunbar1a27a192008-10-29 08:50:02 +000080 bool debug) :
Daniel Dunbar85e44e22008-10-21 23:49:24 +000081 Action(action),
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000082 CompileOpts(compopts),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000083 InputFile(infile),
84 OutputFile(outfile),
Daniel Dunbar1a27a192008-10-29 08:50:02 +000085 GenerateDebugInfo(debug),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000086 Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
Nuno Lopes74d92782008-10-24 22:51:00 +000087 TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000088 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
89
90 ~BackendConsumer() {
Daniel Dunbar85e44e22008-10-21 23:49:24 +000091 delete AsmOutStream;
92 delete TheTargetData;
Nuno Lopes74d92782008-10-24 22:51:00 +000093 delete ModuleProvider;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000094 delete CodeGenPasses;
95 delete PerModulePasses;
96 delete PerFunctionPasses;
97 }
98
99 virtual void InitializeTU(TranslationUnit& TU) {
100 Gen->InitializeTU(TU);
101
102 TheModule = Gen->GetModule();
Nuno Lopesd41e2b12008-10-24 23:27:18 +0000103 ModuleProvider = new ExistingModuleProvider(TheModule);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000104 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);
Daniel Dunbar622d6d02008-11-11 06:35:39 +0000114
115 EmitAssembly();
116 // Force a flush here in case we never get released.
117 if (AsmOutStream)
118 AsmOutStream->flush();
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000119 }
120
121 virtual void HandleTagDeclDefinition(TagDecl *D) {
122 Gen->HandleTagDeclDefinition(D);
123 }
124 };
125}
126
127FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
128 if (!CodeGenPasses) {
Nuno Lopes74d92782008-10-24 22:51:00 +0000129 CodeGenPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000130 CodeGenPasses->add(new TargetData(*TheTargetData));
131 }
132
133 return CodeGenPasses;
134}
135
136PassManager *BackendConsumer::getPerModulePasses() const {
137 if (!PerModulePasses) {
138 PerModulePasses = new PassManager();
139 PerModulePasses->add(new TargetData(*TheTargetData));
140 }
141
142 return PerModulePasses;
143}
144
145FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
146 if (!PerFunctionPasses) {
Nuno Lopesd41e2b12008-10-24 23:27:18 +0000147 PerFunctionPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000148 PerFunctionPasses->add(new TargetData(*TheTargetData));
149 }
150
151 return PerFunctionPasses;
152}
153
Daniel Dunbar655d5092008-10-23 05:59:43 +0000154bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000155 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000156 AsmOutStream = new raw_stdout_ostream();
157 sys::Program::ChangeStdoutToBinary();
158 } else {
159 if (OutputFile.empty()) {
160 llvm::sys::Path Path(InputFile);
161 Path.eraseSuffix();
162 if (Action == Backend_EmitBC) {
163 Path.appendSuffix("bc");
164 } else if (Action == Backend_EmitLL) {
165 Path.appendSuffix("ll");
166 } else {
167 Path.appendSuffix("s");
168 }
169 OutputFile = Path.toString();
170 }
171
Daniel Dunbar8fc9ba62008-11-13 05:09:21 +0000172 AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, 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 Dunbar655d5092008-10-23 05:59:43 +0000182 bool Fast = CompileOpts.OptimizationLevel == 0;
183
Daniel Dunbaraed93f22008-10-22 18:29:51 +0000184 // Create the TargetMachine for generating code.
185 const TargetMachineRegistry::entry *TME =
186 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
187 if (!TME) {
188 Error = std::string("Unable to get target machine: ") + Error;
189 return false;
190 }
191
192 // FIXME: Support features?
193 std::string FeatureStr;
194 TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
195
196 // Set register scheduler & allocation policy.
197 RegisterScheduler::setDefault(createDefaultScheduler);
198 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
199 createLinearScanRegisterAllocator);
200
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000201 // From llvm-gcc:
202 // If there are passes we have to run on the entire module, we do codegen
203 // as a separate "pass" after that happens.
204 // FIXME: This is disabled right now until bugs can be worked out. Reenable
205 // this for fast -O0 compiles!
206 FunctionPassManager *PM = getCodeGenPasses();
207
208 // Normal mode, emit a .s file by running the code generator.
209 // Note, this also adds codegenerator level optimization passes.
210 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
211 TargetMachine::AssemblyFile, Fast)) {
212 default:
213 case FileModel::Error:
214 Error = "Unable to interface with target machine!\n";
215 return false;
216 case FileModel::AsmFile:
217 break;
218 }
219
220 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
221 Error = "Unable to interface with target machine!\n";
222 return false;
223 }
224 }
225
226 return true;
227}
228
229void BackendConsumer::CreatePasses() {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000230 // In -O0 if checking is disabled, we don't even have per-function passes.
231 if (CompileOpts.VerifyModule)
232 getPerFunctionPasses()->add(createVerifierPass());
233
234 if (CompileOpts.OptimizationLevel > 0) {
235 FunctionPassManager *PM = getPerFunctionPasses();
236 PM->add(createCFGSimplificationPass());
237 if (CompileOpts.OptimizationLevel == 1)
238 PM->add(createPromoteMemoryToRegisterPass());
239 else
240 PM->add(createScalarReplAggregatesPass());
241 PM->add(createInstructionCombiningPass());
242 }
243
244 // For now we always create per module passes.
245 PassManager *PM = getPerModulePasses();
246 if (CompileOpts.OptimizationLevel > 0) {
247 if (CompileOpts.UnitAtATime)
248 PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
249 PM->add(createCFGSimplificationPass()); // Clean up disgusting code
250 PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
251 if (CompileOpts.UnitAtATime) {
252 PM->add(createGlobalOptimizerPass()); // Optimize out global vars
253 PM->add(createGlobalDCEPass()); // Remove unused fns and globs
254 PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
255 PM->add(createDeadArgEliminationPass()); // Dead argument elimination
256 }
257 PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
258 PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
259 if (CompileOpts.UnitAtATime) {
260 PM->add(createPruneEHPass()); // Remove dead EH info
261 PM->add(createAddReadAttrsPass()); // Set readonly/readnone attrs
262 }
263 if (CompileOpts.InlineFunctions)
264 PM->add(createFunctionInliningPass()); // Inline small functions
265 else
266 PM->add(createAlwaysInlinerPass()); // Respect always_inline
267 if (CompileOpts.OptimizationLevel > 2)
268 PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
269 if (CompileOpts.SimplifyLibCalls)
270 PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
271 PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
272 PM->add(createJumpThreadingPass()); // Thread jumps.
273 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
274 PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
275 PM->add(createInstructionCombiningPass()); // Combine silly seq's
276 PM->add(createCondPropagationPass()); // Propagate conditionals
277 PM->add(createTailCallEliminationPass()); // Eliminate tail calls
278 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
279 PM->add(createReassociatePass()); // Reassociate expressions
280 PM->add(createLoopRotatePass()); // Rotate Loop
281 PM->add(createLICMPass()); // Hoist loop invariants
282 PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
283 PM->add(createLoopIndexSplitPass()); // Split loop index
284 PM->add(createInstructionCombiningPass());
285 PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
286 PM->add(createLoopDeletionPass()); // Delete dead loops
287 if (CompileOpts.UnrollLoops)
288 PM->add(createLoopUnrollPass()); // Unroll small loops
289 PM->add(createInstructionCombiningPass()); // Clean up after the unroller
290 PM->add(createGVNPass()); // Remove redundancies
291 PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
292 PM->add(createSCCPPass()); // Constant prop with SCCP
293
294 // Run instcombine after redundancy elimination to exploit opportunities
295 // opened up by them.
296 PM->add(createInstructionCombiningPass());
297 PM->add(createCondPropagationPass()); // Propagate conditionals
298 PM->add(createDeadStoreEliminationPass()); // Delete dead stores
299 PM->add(createAggressiveDCEPass()); // Delete dead instructions
300 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
301
302 if (CompileOpts.UnitAtATime) {
303 PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
304 PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
305 }
306
307 if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
308 PM->add(createConstantMergePass()); // Merge dup global constants
309 } else {
Daniel Dunbar160cb622008-11-13 05:29:02 +0000310 PM->add(createAlwaysInlinerPass());
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000311 }
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000312}
313
314/// EmitAssembly - Handle interaction with LLVM backend to generate
315/// actual machine code.
316void BackendConsumer::EmitAssembly() {
317 // Silently ignore if we weren't initialized for some reason.
318 if (!TheModule || !TheTargetData)
319 return;
320
Daniel Dunbarbc147792008-10-27 20:40:41 +0000321 // Make sure IR generation is happy with the module. This is
322 // released by the module provider.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000323 Module *M = Gen->ReleaseModule();
324 if (!M) {
Daniel Dunbarbc147792008-10-27 20:40:41 +0000325 // The module has been released by IR gen on failures, do not
326 // double free.
327 ModuleProvider->releaseModule();
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000328 TheModule = 0;
329 return;
330 }
331
332 assert(TheModule == M && "Unexpected module change during IR generation");
333
334 CreatePasses();
335
336 std::string Error;
Daniel Dunbar655d5092008-10-23 05:59:43 +0000337 if (!AddEmitPasses(Error)) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000338 // FIXME: Don't fail this way.
339 llvm::cerr << "ERROR: " << Error << "\n";
340 ::exit(1);
341 }
342
343 // Run passes. For now we do all passes at once, but eventually we
344 // would like to have the option of streaming code generation.
345
346 if (PerFunctionPasses) {
347 PerFunctionPasses->doInitialization();
348 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
349 if (!I->isDeclaration())
350 PerFunctionPasses->run(*I);
351 PerFunctionPasses->doFinalization();
352 }
353
354 if (PerModulePasses)
355 PerModulePasses->run(*M);
356
357 if (CodeGenPasses) {
358 CodeGenPasses->doInitialization();
359 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
360 if (!I->isDeclaration())
361 CodeGenPasses->run(*I);
362 CodeGenPasses->doFinalization();
363 }
364}
365
366ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
367 Diagnostic &Diags,
368 const LangOptions &Features,
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000369 const CompileOptions &CompileOpts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000370 const std::string& InFile,
371 const std::string& OutFile,
372 bool GenerateDebugInfo) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000373 return new BackendConsumer(Action, Diags, Features, CompileOpts,
374 InFile, OutFile, GenerateDebugInfo);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000375}