blob: a751041b98941cecbfab6f6f7564a7b576e63c53 [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"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000011#include "clang/AST/ASTContext.h"
12#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/TranslationUnit.h"
14#include "clang/Basic/TargetInfo.h"
15#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000016#include "clang/Driver/CompileOptions.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000017#include "llvm/Module.h"
18#include "llvm/ModuleProvider.h"
19#include "llvm/PassManager.h"
20#include "llvm/ADT/OwningPtr.h"
21#include "llvm/Assembly/PrintModulePass.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000022#include "llvm/Analysis/CallGraph.h"
23#include "llvm/Analysis/Verifier.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000024#include "llvm/Bitcode/ReaderWriter.h"
25#include "llvm/CodeGen/RegAllocRegistry.h"
26#include "llvm/CodeGen/SchedulerRegistry.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000027#include "llvm/Support/raw_ostream.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000028#include "llvm/Support/Compiler.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000029#include "llvm/Support/Timer.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000030#include "llvm/System/Path.h"
31#include "llvm/System/Program.h"
Daniel Dunbara034ba82009-02-17 19:47:34 +000032#include "llvm/Target/SubtargetFeature.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000033#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 +000038using 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
Chris Lattner6f114eb2009-02-18 01:37:30 +000049 Timer LLVMIRGeneration;
50 Timer CodeGenerationTime;
51
Daniel Dunbard69bacc2008-10-21 23:49:24 +000052 llvm::OwningPtr<CodeGenerator> Gen;
53
54 llvm::Module *TheModule;
55 llvm::TargetData *TheTargetData;
56 llvm::raw_ostream *AsmOutStream;
57
Nuno Lopesdd492672008-10-24 22:51:00 +000058 mutable llvm::ModuleProvider *ModuleProvider;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000059 mutable FunctionPassManager *CodeGenPasses;
60 mutable PassManager *PerModulePasses;
61 mutable FunctionPassManager *PerFunctionPasses;
62
63 FunctionPassManager *getCodeGenPasses() const;
64 PassManager *getPerModulePasses() const;
65 FunctionPassManager *getPerFunctionPasses() const;
66
67 void CreatePasses();
68
69 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
70 /// IR.
71 ///
Daniel Dunbard69bacc2008-10-21 23:49:24 +000072 /// \return True on success. On failure \arg Error will be set to
73 /// a user readable error message.
Daniel Dunbar4c877cc2008-10-23 05:59:43 +000074 bool AddEmitPasses(std::string &Error);
Daniel Dunbard69bacc2008-10-21 23:49:24 +000075
76 void EmitAssembly();
77
78 public:
79 BackendConsumer(BackendAction action, Diagnostic &Diags,
Daniel Dunbara034ba82009-02-17 19:47:34 +000080 const LangOptions &langopts, const CompileOptions &compopts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +000081 const std::string& infile, const std::string& outfile,
Daniel Dunbar90f41302008-10-29 08:50:02 +000082 bool debug) :
Daniel Dunbard69bacc2008-10-21 23:49:24 +000083 Action(action),
Daniel Dunbar70f92432008-10-23 05:50:47 +000084 CompileOpts(compopts),
Daniel Dunbard69bacc2008-10-21 23:49:24 +000085 InputFile(infile),
86 OutputFile(outfile),
Daniel Dunbar90f41302008-10-29 08:50:02 +000087 GenerateDebugInfo(debug),
Chris Lattner6f114eb2009-02-18 01:37:30 +000088 LLVMIRGeneration("LLVM IR Generation Time"),
89 CodeGenerationTime("Code Generation Time"),
Daniel Dunbara034ba82009-02-17 19:47:34 +000090 Gen(CreateLLVMCodeGen(Diags, langopts, InputFile, GenerateDebugInfo)),
Nuno Lopesdd492672008-10-24 22:51:00 +000091 TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),
Chris Lattner44502662009-02-18 01:23:44 +000092 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {
93
Chris Lattner6f114eb2009-02-18 01:37:30 +000094 // Enable -time-passes if -ftime-report is enabled.
Chris Lattner44502662009-02-18 01:23:44 +000095 llvm::TimePassesIsEnabled = CompileOpts.TimePasses;
96 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +000097
98 ~BackendConsumer() {
Daniel Dunbard69bacc2008-10-21 23:49:24 +000099 delete AsmOutStream;
100 delete TheTargetData;
Nuno Lopesdd492672008-10-24 22:51:00 +0000101 delete ModuleProvider;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000102 delete CodeGenPasses;
103 delete PerModulePasses;
104 delete PerFunctionPasses;
105 }
106
107 virtual void InitializeTU(TranslationUnit& TU) {
Chris Lattner6f114eb2009-02-18 01:37:30 +0000108
109 if (CompileOpts.TimePasses)
110 LLVMIRGeneration.startTimer();
111
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000112 Gen->InitializeTU(TU);
113
114 TheModule = Gen->GetModule();
Nuno Lopes7d43a312008-10-24 23:27:18 +0000115 ModuleProvider = new ExistingModuleProvider(TheModule);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000116 TheTargetData =
117 new llvm::TargetData(TU.getContext().Target.getTargetDescription());
Chris Lattner6f114eb2009-02-18 01:37:30 +0000118
119 if (CompileOpts.TimePasses)
120 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000121 }
122
123 virtual void HandleTopLevelDecl(Decl *D) {
Chris Lattner6f114eb2009-02-18 01:37:30 +0000124 if (CompileOpts.TimePasses)
125 LLVMIRGeneration.startTimer();
126
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000127 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +0000128
129 if (CompileOpts.TimePasses)
130 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000131 }
132
133 virtual void HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattner6f114eb2009-02-18 01:37:30 +0000134 if (CompileOpts.TimePasses)
135 LLVMIRGeneration.startTimer();
136
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000137 Gen->HandleTranslationUnit(TU);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000138
Chris Lattner6f114eb2009-02-18 01:37:30 +0000139 if (CompileOpts.TimePasses)
140 LLVMIRGeneration.stopTimer();
141
142 // EmitAssembly times itself.
143 EmitAssembly();
144
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000145 // Force a flush here in case we never get released.
146 if (AsmOutStream)
147 AsmOutStream->flush();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000148 }
149
150 virtual void HandleTagDeclDefinition(TagDecl *D) {
151 Gen->HandleTagDeclDefinition(D);
152 }
153 };
154}
155
156FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
157 if (!CodeGenPasses) {
Nuno Lopesdd492672008-10-24 22:51:00 +0000158 CodeGenPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000159 CodeGenPasses->add(new TargetData(*TheTargetData));
160 }
161
162 return CodeGenPasses;
163}
164
165PassManager *BackendConsumer::getPerModulePasses() const {
166 if (!PerModulePasses) {
167 PerModulePasses = new PassManager();
168 PerModulePasses->add(new TargetData(*TheTargetData));
169 }
170
171 return PerModulePasses;
172}
173
174FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
175 if (!PerFunctionPasses) {
Nuno Lopes7d43a312008-10-24 23:27:18 +0000176 PerFunctionPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000177 PerFunctionPasses->add(new TargetData(*TheTargetData));
178 }
179
180 return PerFunctionPasses;
181}
182
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000183bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000184 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000185 AsmOutStream = new raw_stdout_ostream();
186 sys::Program::ChangeStdoutToBinary();
187 } else {
188 if (OutputFile.empty()) {
189 llvm::sys::Path Path(InputFile);
190 Path.eraseSuffix();
191 if (Action == Backend_EmitBC) {
192 Path.appendSuffix("bc");
193 } else if (Action == Backend_EmitLL) {
194 Path.appendSuffix("ll");
195 } else {
196 Path.appendSuffix("s");
197 }
198 OutputFile = Path.toString();
199 }
200
Daniel Dunbar26fb2722008-11-13 05:09:21 +0000201 AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000202 if (!Error.empty())
203 return false;
204 }
205
206 if (Action == Backend_EmitBC) {
Daniel Dunbared2cb282008-10-22 17:40:45 +0000207 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000208 } else if (Action == Backend_EmitLL) {
Daniel Dunbar11292b02008-10-22 03:28:13 +0000209 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000210 } else {
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000211 bool Fast = CompileOpts.OptimizationLevel == 0;
212
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000213 // Create the TargetMachine for generating code.
214 const TargetMachineRegistry::entry *TME =
215 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
216 if (!TME) {
217 Error = std::string("Unable to get target machine: ") + Error;
218 return false;
219 }
Daniel Dunbara034ba82009-02-17 19:47:34 +0000220
221 std::string FeaturesStr;
222 if (CompileOpts.CPU.size() || CompileOpts.Features.size()) {
223 SubtargetFeatures Features;
224 Features.setCPU(CompileOpts.CPU);
225 for (std::vector<std::string>::iterator
226 it = CompileOpts.Features.begin(),
227 ie = CompileOpts.Features.end(); it != ie; ++it)
228 Features.AddFeature(*it);
229 FeaturesStr = Features.getString();
230 }
231 TargetMachine *TM = TME->CtorFn(*TheModule, FeaturesStr);
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000232
233 // Set register scheduler & allocation policy.
234 RegisterScheduler::setDefault(createDefaultScheduler);
235 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
236 createLinearScanRegisterAllocator);
237
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000238 // From llvm-gcc:
239 // If there are passes we have to run on the entire module, we do codegen
240 // as a separate "pass" after that happens.
241 // FIXME: This is disabled right now until bugs can be worked out. Reenable
242 // this for fast -O0 compiles!
243 FunctionPassManager *PM = getCodeGenPasses();
244
245 // Normal mode, emit a .s file by running the code generator.
246 // Note, this also adds codegenerator level optimization passes.
247 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
248 TargetMachine::AssemblyFile, Fast)) {
249 default:
250 case FileModel::Error:
251 Error = "Unable to interface with target machine!\n";
252 return false;
253 case FileModel::AsmFile:
254 break;
255 }
256
257 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
258 Error = "Unable to interface with target machine!\n";
259 return false;
260 }
261 }
262
263 return true;
264}
265
266void BackendConsumer::CreatePasses() {
Daniel Dunbar70f92432008-10-23 05:50:47 +0000267 // In -O0 if checking is disabled, we don't even have per-function passes.
268 if (CompileOpts.VerifyModule)
269 getPerFunctionPasses()->add(createVerifierPass());
270
271 if (CompileOpts.OptimizationLevel > 0) {
272 FunctionPassManager *PM = getPerFunctionPasses();
273 PM->add(createCFGSimplificationPass());
274 if (CompileOpts.OptimizationLevel == 1)
275 PM->add(createPromoteMemoryToRegisterPass());
276 else
277 PM->add(createScalarReplAggregatesPass());
278 PM->add(createInstructionCombiningPass());
279 }
280
281 // For now we always create per module passes.
282 PassManager *PM = getPerModulePasses();
283 if (CompileOpts.OptimizationLevel > 0) {
284 if (CompileOpts.UnitAtATime)
285 PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
286 PM->add(createCFGSimplificationPass()); // Clean up disgusting code
287 PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
288 if (CompileOpts.UnitAtATime) {
289 PM->add(createGlobalOptimizerPass()); // Optimize out global vars
290 PM->add(createGlobalDCEPass()); // Remove unused fns and globs
291 PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
292 PM->add(createDeadArgEliminationPass()); // Dead argument elimination
293 }
294 PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
295 PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
296 if (CompileOpts.UnitAtATime) {
297 PM->add(createPruneEHPass()); // Remove dead EH info
Bill Wendling5c5a7ee2008-12-31 19:51:31 +0000298 PM->add(createFunctionAttrsPass()); // Set readonly/readnone attrs
Daniel Dunbar70f92432008-10-23 05:50:47 +0000299 }
300 if (CompileOpts.InlineFunctions)
301 PM->add(createFunctionInliningPass()); // Inline small functions
302 else
303 PM->add(createAlwaysInlinerPass()); // Respect always_inline
304 if (CompileOpts.OptimizationLevel > 2)
305 PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
306 if (CompileOpts.SimplifyLibCalls)
307 PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
308 PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
309 PM->add(createJumpThreadingPass()); // Thread jumps.
310 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
311 PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
312 PM->add(createInstructionCombiningPass()); // Combine silly seq's
313 PM->add(createCondPropagationPass()); // Propagate conditionals
314 PM->add(createTailCallEliminationPass()); // Eliminate tail calls
315 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
316 PM->add(createReassociatePass()); // Reassociate expressions
317 PM->add(createLoopRotatePass()); // Rotate Loop
318 PM->add(createLICMPass()); // Hoist loop invariants
319 PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
Devang Patel59db7602008-11-26 05:01:52 +0000320// PM->add(createLoopIndexSplitPass()); // Split loop index
Daniel Dunbar70f92432008-10-23 05:50:47 +0000321 PM->add(createInstructionCombiningPass());
322 PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
323 PM->add(createLoopDeletionPass()); // Delete dead loops
324 if (CompileOpts.UnrollLoops)
325 PM->add(createLoopUnrollPass()); // Unroll small loops
326 PM->add(createInstructionCombiningPass()); // Clean up after the unroller
327 PM->add(createGVNPass()); // Remove redundancies
328 PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
329 PM->add(createSCCPPass()); // Constant prop with SCCP
330
331 // Run instcombine after redundancy elimination to exploit opportunities
332 // opened up by them.
333 PM->add(createInstructionCombiningPass());
334 PM->add(createCondPropagationPass()); // Propagate conditionals
335 PM->add(createDeadStoreEliminationPass()); // Delete dead stores
336 PM->add(createAggressiveDCEPass()); // Delete dead instructions
337 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
338
339 if (CompileOpts.UnitAtATime) {
340 PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
341 PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
342 }
343
344 if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
345 PM->add(createConstantMergePass()); // Merge dup global constants
346 } else {
Daniel Dunbarb087ae92008-11-13 05:29:02 +0000347 PM->add(createAlwaysInlinerPass());
Daniel Dunbar70f92432008-10-23 05:50:47 +0000348 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000349}
350
351/// EmitAssembly - Handle interaction with LLVM backend to generate
352/// actual machine code.
353void BackendConsumer::EmitAssembly() {
354 // Silently ignore if we weren't initialized for some reason.
355 if (!TheModule || !TheTargetData)
356 return;
Chris Lattner6f114eb2009-02-18 01:37:30 +0000357
358 TimeRegion Region(CodeGenerationTime);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000359
Daniel Dunbard611bac2008-10-27 20:40:41 +0000360 // Make sure IR generation is happy with the module. This is
361 // released by the module provider.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000362 Module *M = Gen->ReleaseModule();
363 if (!M) {
Daniel Dunbard611bac2008-10-27 20:40:41 +0000364 // The module has been released by IR gen on failures, do not
365 // double free.
366 ModuleProvider->releaseModule();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000367 TheModule = 0;
368 return;
369 }
370
371 assert(TheModule == M && "Unexpected module change during IR generation");
372
373 CreatePasses();
374
375 std::string Error;
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000376 if (!AddEmitPasses(Error)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000377 // FIXME: Don't fail this way.
378 llvm::cerr << "ERROR: " << Error << "\n";
379 ::exit(1);
380 }
381
382 // Run passes. For now we do all passes at once, but eventually we
383 // would like to have the option of streaming code generation.
384
385 if (PerFunctionPasses) {
386 PerFunctionPasses->doInitialization();
387 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
388 if (!I->isDeclaration())
389 PerFunctionPasses->run(*I);
390 PerFunctionPasses->doFinalization();
391 }
392
393 if (PerModulePasses)
394 PerModulePasses->run(*M);
395
396 if (CodeGenPasses) {
397 CodeGenPasses->doInitialization();
398 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
399 if (!I->isDeclaration())
400 CodeGenPasses->run(*I);
401 CodeGenPasses->doFinalization();
402 }
403}
404
405ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
406 Diagnostic &Diags,
Daniel Dunbara034ba82009-02-17 19:47:34 +0000407 const LangOptions &LangOpts,
Daniel Dunbar70f92432008-10-23 05:50:47 +0000408 const CompileOptions &CompileOpts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000409 const std::string& InFile,
410 const std::string& OutFile,
411 bool GenerateDebugInfo) {
Chris Lattner05e7c6d2009-02-12 01:50:58 +0000412 // FIXME: If optimizing, disable all debug info generation. The LLVM
413 // optimizer and backend is not ready to handle it when optimizations
414 // are enabled.
415 if (CompileOpts.OptimizationLevel > 0)
416 GenerateDebugInfo = false;
Daniel Dunbara034ba82009-02-17 19:47:34 +0000417
418 return new BackendConsumer(Action, Diags, LangOpts, CompileOpts,
Daniel Dunbar70f92432008-10-23 05:50:47 +0000419 InFile, OutFile, GenerateDebugInfo);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000420}