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