blob: f8cfa997e25c42d4f6c2cc701203c39061353f58 [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"
28#include "llvm/CodeGen/ScheduleDAG.h"
29#include "llvm/Support/raw_ostream.h"
Daniel Dunbard69bacc2008-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 Dunbar70f92432008-10-23 05:50:47 +000036#include "llvm/Transforms/Scalar.h"
37#include "llvm/Transforms/IPO.h"
Daniel Dunbard69bacc2008-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 Dunbar70f92432008-10-23 05:50:47 +000046 CompileOptions CompileOpts;
Daniel Dunbard69bacc2008-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 ///
Daniel Dunbard69bacc2008-10-21 23:49:24 +000068 /// \return True on success. On failure \arg Error will be set to
69 /// a user readable error message.
Daniel Dunbar4c877cc2008-10-23 05:59:43 +000070 bool AddEmitPasses(std::string &Error);
Daniel Dunbard69bacc2008-10-21 23:49:24 +000071
72 void EmitAssembly();
73
74 public:
75 BackendConsumer(BackendAction action, Diagnostic &Diags,
Daniel Dunbar70f92432008-10-23 05:50:47 +000076 const LangOptions &Features, const CompileOptions &compopts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +000077 const std::string& infile, const std::string& outfile,
78 bool GenerateDebugInfo) :
79 Action(action),
Daniel Dunbar70f92432008-10-23 05:50:47 +000080 CompileOpts(compopts),
Daniel Dunbard69bacc2008-10-21 23:49:24 +000081 InputFile(infile),
82 OutputFile(outfile),
83 Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
Daniel Dunbared2cb282008-10-22 17:40:45 +000084 TheModule(0), TheTargetData(0), AsmOutStream(0),
Daniel Dunbard69bacc2008-10-21 23:49:24 +000085 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
86
87 ~BackendConsumer() {
88 // FIXME: Move out of destructor.
89 EmitAssembly();
90
91 delete AsmOutStream;
92 delete TheTargetData;
93 delete TheModule;
94 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();
103 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);
113 }
114
115 virtual void HandleTagDeclDefinition(TagDecl *D) {
116 Gen->HandleTagDeclDefinition(D);
117 }
118 };
119}
120
121FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
122 if (!CodeGenPasses) {
123 CodeGenPasses =
124 new FunctionPassManager(new ExistingModuleProvider(TheModule));
125 CodeGenPasses->add(new TargetData(*TheTargetData));
126 }
127
128 return CodeGenPasses;
129}
130
131PassManager *BackendConsumer::getPerModulePasses() const {
132 if (!PerModulePasses) {
133 PerModulePasses = new PassManager();
134 PerModulePasses->add(new TargetData(*TheTargetData));
135 }
136
137 return PerModulePasses;
138}
139
140FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
141 if (!PerFunctionPasses) {
142 PerFunctionPasses =
143 new FunctionPassManager(new ExistingModuleProvider(TheModule));
144 PerFunctionPasses->add(new TargetData(*TheTargetData));
145 }
146
147 return PerFunctionPasses;
148}
149
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000150bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000151 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000152 AsmOutStream = new raw_stdout_ostream();
153 sys::Program::ChangeStdoutToBinary();
154 } else {
155 if (OutputFile.empty()) {
156 llvm::sys::Path Path(InputFile);
157 Path.eraseSuffix();
158 if (Action == Backend_EmitBC) {
159 Path.appendSuffix("bc");
160 } else if (Action == Backend_EmitLL) {
161 Path.appendSuffix("ll");
162 } else {
163 Path.appendSuffix("s");
164 }
165 OutputFile = Path.toString();
166 }
167
Daniel Dunbared2cb282008-10-22 17:40:45 +0000168 // FIXME: Should be binary.
169 AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), Error);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000170 if (!Error.empty())
171 return false;
172 }
173
174 if (Action == Backend_EmitBC) {
Daniel Dunbared2cb282008-10-22 17:40:45 +0000175 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000176 } else if (Action == Backend_EmitLL) {
Daniel Dunbar11292b02008-10-22 03:28:13 +0000177 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000178 } else {
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000179 bool Fast = CompileOpts.OptimizationLevel == 0;
180
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000181 // Create the TargetMachine for generating code.
182 const TargetMachineRegistry::entry *TME =
183 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
184 if (!TME) {
185 Error = std::string("Unable to get target machine: ") + Error;
186 return false;
187 }
188
189 // FIXME: Support features?
190 std::string FeatureStr;
191 TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
192
193 // Set register scheduler & allocation policy.
194 RegisterScheduler::setDefault(createDefaultScheduler);
195 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
196 createLinearScanRegisterAllocator);
197
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000198 // From llvm-gcc:
199 // If there are passes we have to run on the entire module, we do codegen
200 // as a separate "pass" after that happens.
201 // FIXME: This is disabled right now until bugs can be worked out. Reenable
202 // this for fast -O0 compiles!
203 FunctionPassManager *PM = getCodeGenPasses();
204
205 // Normal mode, emit a .s file by running the code generator.
206 // Note, this also adds codegenerator level optimization passes.
207 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
208 TargetMachine::AssemblyFile, Fast)) {
209 default:
210 case FileModel::Error:
211 Error = "Unable to interface with target machine!\n";
212 return false;
213 case FileModel::AsmFile:
214 break;
215 }
216
217 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
218 Error = "Unable to interface with target machine!\n";
219 return false;
220 }
221 }
222
223 return true;
224}
225
226void BackendConsumer::CreatePasses() {
Daniel Dunbar70f92432008-10-23 05:50:47 +0000227 // In -O0 if checking is disabled, we don't even have per-function passes.
228 if (CompileOpts.VerifyModule)
229 getPerFunctionPasses()->add(createVerifierPass());
230
231 if (CompileOpts.OptimizationLevel > 0) {
232 FunctionPassManager *PM = getPerFunctionPasses();
233 PM->add(createCFGSimplificationPass());
234 if (CompileOpts.OptimizationLevel == 1)
235 PM->add(createPromoteMemoryToRegisterPass());
236 else
237 PM->add(createScalarReplAggregatesPass());
238 PM->add(createInstructionCombiningPass());
239 }
240
241 // For now we always create per module passes.
242 PassManager *PM = getPerModulePasses();
243 if (CompileOpts.OptimizationLevel > 0) {
244 if (CompileOpts.UnitAtATime)
245 PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
246 PM->add(createCFGSimplificationPass()); // Clean up disgusting code
247 PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
248 if (CompileOpts.UnitAtATime) {
249 PM->add(createGlobalOptimizerPass()); // Optimize out global vars
250 PM->add(createGlobalDCEPass()); // Remove unused fns and globs
251 PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
252 PM->add(createDeadArgEliminationPass()); // Dead argument elimination
253 }
254 PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
255 PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
256 if (CompileOpts.UnitAtATime) {
257 PM->add(createPruneEHPass()); // Remove dead EH info
258 PM->add(createAddReadAttrsPass()); // Set readonly/readnone attrs
259 }
260 if (CompileOpts.InlineFunctions)
261 PM->add(createFunctionInliningPass()); // Inline small functions
262 else
263 PM->add(createAlwaysInlinerPass()); // Respect always_inline
264 if (CompileOpts.OptimizationLevel > 2)
265 PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
266 if (CompileOpts.SimplifyLibCalls)
267 PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
268 PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
269 PM->add(createJumpThreadingPass()); // Thread jumps.
270 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
271 PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
272 PM->add(createInstructionCombiningPass()); // Combine silly seq's
273 PM->add(createCondPropagationPass()); // Propagate conditionals
274 PM->add(createTailCallEliminationPass()); // Eliminate tail calls
275 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
276 PM->add(createReassociatePass()); // Reassociate expressions
277 PM->add(createLoopRotatePass()); // Rotate Loop
278 PM->add(createLICMPass()); // Hoist loop invariants
279 PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
280 PM->add(createLoopIndexSplitPass()); // Split loop index
281 PM->add(createInstructionCombiningPass());
282 PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
283 PM->add(createLoopDeletionPass()); // Delete dead loops
284 if (CompileOpts.UnrollLoops)
285 PM->add(createLoopUnrollPass()); // Unroll small loops
286 PM->add(createInstructionCombiningPass()); // Clean up after the unroller
287 PM->add(createGVNPass()); // Remove redundancies
288 PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
289 PM->add(createSCCPPass()); // Constant prop with SCCP
290
291 // Run instcombine after redundancy elimination to exploit opportunities
292 // opened up by them.
293 PM->add(createInstructionCombiningPass());
294 PM->add(createCondPropagationPass()); // Propagate conditionals
295 PM->add(createDeadStoreEliminationPass()); // Delete dead stores
296 PM->add(createAggressiveDCEPass()); // Delete dead instructions
297 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
298
299 if (CompileOpts.UnitAtATime) {
300 PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
301 PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
302 }
303
304 if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
305 PM->add(createConstantMergePass()); // Merge dup global constants
306 } else {
307 PerModulePasses->add(createAlwaysInlinerPass());
308 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000309}
310
311/// EmitAssembly - Handle interaction with LLVM backend to generate
312/// actual machine code.
313void BackendConsumer::EmitAssembly() {
314 // Silently ignore if we weren't initialized for some reason.
315 if (!TheModule || !TheTargetData)
316 return;
317
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000318 // Make sure IR generation is happy with the module.
319 // FIXME: Release this.
320 Module *M = Gen->ReleaseModule();
321 if (!M) {
322 TheModule = 0;
323 return;
324 }
325
326 assert(TheModule == M && "Unexpected module change during IR generation");
327
328 CreatePasses();
329
330 std::string Error;
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000331 if (!AddEmitPasses(Error)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000332 // FIXME: Don't fail this way.
333 llvm::cerr << "ERROR: " << Error << "\n";
334 ::exit(1);
335 }
336
337 // Run passes. For now we do all passes at once, but eventually we
338 // would like to have the option of streaming code generation.
339
340 if (PerFunctionPasses) {
341 PerFunctionPasses->doInitialization();
342 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
343 if (!I->isDeclaration())
344 PerFunctionPasses->run(*I);
345 PerFunctionPasses->doFinalization();
346 }
347
348 if (PerModulePasses)
349 PerModulePasses->run(*M);
350
351 if (CodeGenPasses) {
352 CodeGenPasses->doInitialization();
353 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
354 if (!I->isDeclaration())
355 CodeGenPasses->run(*I);
356 CodeGenPasses->doFinalization();
357 }
358}
359
360ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
361 Diagnostic &Diags,
362 const LangOptions &Features,
Daniel Dunbar70f92432008-10-23 05:50:47 +0000363 const CompileOptions &CompileOpts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000364 const std::string& InFile,
365 const std::string& OutFile,
366 bool GenerateDebugInfo) {
Daniel Dunbar70f92432008-10-23 05:50:47 +0000367 return new BackendConsumer(Action, Diags, Features, CompileOpts,
368 InFile, OutFile, GenerateDebugInfo);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000369}