Added the LAR (load segment access rights)
[llvm/avr.git] / tools / opt / opt.cpp
blobfe0e03649ddc911f4fcd4742ec62cf17c1ebc743
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
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 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/LLVMContext.h"
16 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Assembly/PrintModulePass.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/PassNameParser.h"
28 #include "llvm/System/Signals.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/PluginLoader.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/LinkAllVMCore.h"
38 #include <memory>
39 #include <algorithm>
40 using namespace llvm;
42 // The OptimizationList is automatically populated with registered Passes by the
43 // PassNameParser.
45 static cl::list<const PassInfo*, bool, PassNameParser>
46 PassList(cl::desc("Optimizations available:"));
48 // Other command line options...
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
52 cl::init("-"), cl::value_desc("filename"));
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Override output filename"),
56 cl::value_desc("filename"), cl::init("-"));
58 static cl::opt<bool>
59 Force("f", cl::desc("Enable binary output on terminals"));
61 static cl::opt<bool>
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
64 static cl::opt<bool>
65 NoOutput("disable-output",
66 cl::desc("Do not write result bitcode file"), cl::Hidden);
68 static cl::opt<bool>
69 OutputAssembly("S",
70 cl::desc("Write output as LLVM assembly"), cl::Hidden);
72 static cl::opt<bool>
73 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
75 static cl::opt<bool>
76 VerifyEach("verify-each", cl::desc("Verify after each transform"));
78 static cl::opt<bool>
79 StripDebug("strip-debug",
80 cl::desc("Strip debugger symbol info from translation unit"));
82 static cl::opt<bool>
83 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
85 static cl::opt<bool>
86 DisableOptimizations("disable-opt",
87 cl::desc("Do not run any optimization passes"));
89 static cl::opt<bool>
90 DisableInternalize("disable-internalize",
91 cl::desc("Do not mark all symbols as internal"));
93 static cl::opt<bool>
94 StandardCompileOpts("std-compile-opts",
95 cl::desc("Include the standard compile time optimizations"));
97 static cl::opt<bool>
98 StandardLinkOpts("std-link-opts",
99 cl::desc("Include the standard link time optimizations"));
101 static cl::opt<bool>
102 OptLevelO1("O1",
103 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
105 static cl::opt<bool>
106 OptLevelO2("O2",
107 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
109 static cl::opt<bool>
110 OptLevelO3("O3",
111 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
113 static cl::opt<bool>
114 UnitAtATime("funit-at-a-time",
115 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
116 cl::init(true));
118 static cl::opt<bool>
119 DisableSimplifyLibCalls("disable-simplify-libcalls",
120 cl::desc("Disable simplify-libcalls"));
122 static cl::opt<bool>
123 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
125 static cl::alias
126 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
128 static cl::opt<bool>
129 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
131 // ---------- Define Printers for module and function passes ------------
132 namespace {
134 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
135 static char ID;
136 const PassInfo *PassToPrint;
137 CallGraphSCCPassPrinter(const PassInfo *PI) :
138 CallGraphSCCPass(&ID), PassToPrint(PI) {}
140 virtual bool runOnSCC(std::vector<CallGraphNode *>&SCC) {
141 if (!Quiet) {
142 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
144 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
145 Function *F = SCC[i]->getFunction();
146 if (F) {
147 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
151 // Get and print pass...
152 return false;
155 virtual const char *getPassName() const { return "'Pass' Printer"; }
157 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.addRequiredID(PassToPrint);
159 AU.setPreservesAll();
163 char CallGraphSCCPassPrinter::ID = 0;
165 struct ModulePassPrinter : public ModulePass {
166 static char ID;
167 const PassInfo *PassToPrint;
168 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
169 PassToPrint(PI) {}
171 virtual bool runOnModule(Module &M) {
172 if (!Quiet) {
173 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
174 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
177 // Get and print pass...
178 return false;
181 virtual const char *getPassName() const { return "'Pass' Printer"; }
183 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
184 AU.addRequiredID(PassToPrint);
185 AU.setPreservesAll();
189 char ModulePassPrinter::ID = 0;
190 struct FunctionPassPrinter : public FunctionPass {
191 const PassInfo *PassToPrint;
192 static char ID;
193 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
194 PassToPrint(PI) {}
196 virtual bool runOnFunction(Function &F) {
197 if (!Quiet) {
198 outs() << "Printing analysis '" << PassToPrint->getPassName()
199 << "' for function '" << F.getName() << "':\n";
201 // Get and print pass...
202 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
203 return false;
206 virtual const char *getPassName() const { return "FunctionPass Printer"; }
208 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
209 AU.addRequiredID(PassToPrint);
210 AU.setPreservesAll();
214 char FunctionPassPrinter::ID = 0;
216 struct LoopPassPrinter : public LoopPass {
217 static char ID;
218 const PassInfo *PassToPrint;
219 LoopPassPrinter(const PassInfo *PI) :
220 LoopPass(&ID), PassToPrint(PI) {}
222 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
223 if (!Quiet) {
224 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
225 getAnalysisID<Pass>(PassToPrint).print(outs(),
226 L->getHeader()->getParent()->getParent());
228 // Get and print pass...
229 return false;
232 virtual const char *getPassName() const { return "'Pass' Printer"; }
234 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
235 AU.addRequiredID(PassToPrint);
236 AU.setPreservesAll();
240 char LoopPassPrinter::ID = 0;
242 struct BasicBlockPassPrinter : public BasicBlockPass {
243 const PassInfo *PassToPrint;
244 static char ID;
245 BasicBlockPassPrinter(const PassInfo *PI)
246 : BasicBlockPass(&ID), PassToPrint(PI) {}
248 virtual bool runOnBasicBlock(BasicBlock &BB) {
249 if (!Quiet) {
250 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
251 << "': Pass " << PassToPrint->getPassName() << ":\n";
254 // Get and print pass...
255 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
256 return false;
259 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
261 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
262 AU.addRequiredID(PassToPrint);
263 AU.setPreservesAll();
267 char BasicBlockPassPrinter::ID = 0;
268 inline void addPass(PassManager &PM, Pass *P) {
269 // Add the pass to the pass manager...
270 PM.add(P);
272 // If we are verifying all of the intermediate steps, add the verifier...
273 if (VerifyEach) PM.add(createVerifierPass());
276 /// AddOptimizationPasses - This routine adds optimization passes
277 /// based on selected optimization level, OptLevel. This routine
278 /// duplicates llvm-gcc behaviour.
280 /// OptLevel - Optimization Level
281 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
282 unsigned OptLevel) {
283 createStandardFunctionPasses(&FPM, OptLevel);
285 llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
286 createStandardModulePasses(&MPM, OptLevel,
287 /*OptimizeSize=*/ false,
288 UnitAtATime,
289 /*UnrollLoops=*/ OptLevel > 1,
290 !DisableSimplifyLibCalls,
291 /*HaveExceptions=*/ true,
292 InliningPass);
295 void AddStandardCompilePasses(PassManager &PM) {
296 PM.add(createVerifierPass()); // Verify that input is correct
298 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
300 // If the -strip-debug command line option was specified, do it.
301 if (StripDebug)
302 addPass(PM, createStripSymbolsPass(true));
304 if (DisableOptimizations) return;
306 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
308 // -std-compile-opts adds the same module passes as -O3.
309 createStandardModulePasses(&PM, 3,
310 /*OptimizeSize=*/ false,
311 /*UnitAtATime=*/ true,
312 /*UnrollLoops=*/ true,
313 /*SimplifyLibCalls=*/ true,
314 /*HaveExceptions=*/ true,
315 InliningPass);
318 void AddStandardLinkPasses(PassManager &PM) {
319 PM.add(createVerifierPass()); // Verify that input is correct
321 // If the -strip-debug command line option was specified, do it.
322 if (StripDebug)
323 addPass(PM, createStripSymbolsPass(true));
325 if (DisableOptimizations) return;
327 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
328 /*RunInliner=*/ !DisableInline,
329 /*VerifyEach=*/ VerifyEach);
332 } // anonymous namespace
335 //===----------------------------------------------------------------------===//
336 // main for opt
338 int main(int argc, char **argv) {
339 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
340 LLVMContext &Context = getGlobalContext();
341 try {
342 cl::ParseCommandLineOptions(argc, argv,
343 "llvm .bc -> .bc modular optimizer and analysis printer\n");
344 sys::PrintStackTraceOnErrorSignal();
346 // Allocate a full target machine description only if necessary.
347 // FIXME: The choice of target should be controllable on the command line.
348 std::auto_ptr<TargetMachine> target;
350 SMDiagnostic Err;
352 // Load the input module...
353 std::auto_ptr<Module> M;
354 M.reset(ParseIRFile(InputFilename, Err, Context));
356 if (M.get() == 0) {
357 Err.Print(argv[0], errs());
358 return 1;
361 // Figure out what stream we are supposed to write to...
362 // FIXME: outs() is not binary!
363 raw_ostream *Out = &outs(); // Default to printing to stdout...
364 if (OutputFilename != "-") {
365 // Make sure that the Output file gets unlinked from the disk if we get a
366 // SIGINT
367 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
369 std::string ErrorInfo;
370 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
371 raw_fd_ostream::F_Binary);
372 if (!ErrorInfo.empty()) {
373 errs() << ErrorInfo << '\n';
374 delete Out;
375 return 1;
379 // If the output is set to be emitted to standard out, and standard out is a
380 // console, print out a warning message and refuse to do it. We don't
381 // impress anyone by spewing tons of binary goo to a terminal.
382 if (!Force && !NoOutput && !OutputAssembly)
383 if (CheckBitcodeOutputToConsole(*Out, !Quiet))
384 NoOutput = true;
386 // Create a PassManager to hold and optimize the collection of passes we are
387 // about to build...
389 PassManager Passes;
391 // Add an appropriate TargetData instance for this module...
392 Passes.add(new TargetData(M.get()));
394 FunctionPassManager *FPasses = NULL;
395 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
396 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
397 FPasses->add(new TargetData(M.get()));
400 // If the -strip-debug command line option was specified, add it. If
401 // -std-compile-opts was also specified, it will handle StripDebug.
402 if (StripDebug && !StandardCompileOpts)
403 addPass(Passes, createStripSymbolsPass(true));
405 // Create a new optimization pass for each one specified on the command line
406 for (unsigned i = 0; i < PassList.size(); ++i) {
407 // Check to see if -std-compile-opts was specified before this option. If
408 // so, handle it.
409 if (StandardCompileOpts &&
410 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
411 AddStandardCompilePasses(Passes);
412 StandardCompileOpts = false;
415 if (StandardLinkOpts &&
416 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
417 AddStandardLinkPasses(Passes);
418 StandardLinkOpts = false;
421 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
422 AddOptimizationPasses(Passes, *FPasses, 1);
423 OptLevelO1 = false;
426 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
427 AddOptimizationPasses(Passes, *FPasses, 2);
428 OptLevelO2 = false;
431 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
432 AddOptimizationPasses(Passes, *FPasses, 3);
433 OptLevelO3 = false;
436 const PassInfo *PassInf = PassList[i];
437 Pass *P = 0;
438 if (PassInf->getNormalCtor())
439 P = PassInf->getNormalCtor()();
440 else
441 errs() << argv[0] << ": cannot create pass: "
442 << PassInf->getPassName() << "\n";
443 if (P) {
444 bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
445 bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
446 bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
447 bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
449 addPass(Passes, P);
451 if (AnalyzeOnly) {
452 if (isBBPass)
453 Passes.add(new BasicBlockPassPrinter(PassInf));
454 else if (isLPass)
455 Passes.add(new LoopPassPrinter(PassInf));
456 else if (isFPass)
457 Passes.add(new FunctionPassPrinter(PassInf));
458 else if (isCGSCCPass)
459 Passes.add(new CallGraphSCCPassPrinter(PassInf));
460 else
461 Passes.add(new ModulePassPrinter(PassInf));
465 if (PrintEachXForm)
466 Passes.add(createPrintModulePass(&errs()));
469 // If -std-compile-opts was specified at the end of the pass list, add them.
470 if (StandardCompileOpts) {
471 AddStandardCompilePasses(Passes);
472 StandardCompileOpts = false;
475 if (StandardLinkOpts) {
476 AddStandardLinkPasses(Passes);
477 StandardLinkOpts = false;
480 if (OptLevelO1) {
481 AddOptimizationPasses(Passes, *FPasses, 1);
484 if (OptLevelO2) {
485 AddOptimizationPasses(Passes, *FPasses, 2);
488 if (OptLevelO3) {
489 AddOptimizationPasses(Passes, *FPasses, 3);
492 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
493 FPasses->doInitialization();
494 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
495 I != E; ++I)
496 FPasses->run(*I);
499 // Check that the module is well formed on completion of optimization
500 if (!NoVerify && !VerifyEach)
501 Passes.add(createVerifierPass());
503 // Write bitcode or assembly out to disk or outs() as the last step...
504 if (!NoOutput && !AnalyzeOnly) {
505 if (OutputAssembly)
506 Passes.add(createPrintModulePass(Out));
507 else
508 Passes.add(createBitcodeWriterPass(*Out));
511 // Now that we have all of the passes ready, run them.
512 Passes.run(*M.get());
514 // Delete the raw_fd_ostream.
515 if (Out != &outs())
516 delete Out;
517 return 0;
519 } catch (const std::string& msg) {
520 errs() << argv[0] << ": " << msg << "\n";
521 } catch (...) {
522 errs() << argv[0] << ": Unexpected unknown exception occurred.\n";
524 llvm_shutdown();
525 return 1;