1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
42 // The OptimizationList is automatically populated with registered Passes by the
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("-"));
59 Force("f", cl::desc("Enable binary output on terminals"));
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
65 NoOutput("disable-output",
66 cl::desc("Do not write result bitcode file"), cl::Hidden);
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
78 StripDebug("strip-debug",
79 cl::desc("Strip debugger symbol info from translation unit"));
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
85 DisableOptimizations("disable-opt",
86 cl::desc("Do not run any optimization passes"));
89 DisableInternalize("disable-internalize",
90 cl::desc("Do not mark all symbols as internal"));
93 StandardCompileOpts("std-compile-opts",
94 cl::desc("Include the standard compile time optimizations"));
97 StandardLinkOpts("std-link-opts",
98 cl::desc("Include the standard link time optimizations"));
102 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
106 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
110 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
113 UnitAtATime("funit-at-a-time",
114 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119 cl::desc("Disable simplify-libcalls"));
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
128 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
130 static cl::opt<std::string>
131 DefaultDataLayout("default-data-layout",
132 cl::desc("data layout string to use if not specified by module"),
133 cl::value_desc("layout-string"), cl::init(""));
136 NoDefaultDataLayout("no-default-data-layout",
137 cl::desc("no data layout assumptions unless module specifies data layout"));
139 // ---------- Define Printers for module and function passes ------------
142 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
144 const PassInfo *PassToPrint;
145 CallGraphSCCPassPrinter(const PassInfo *PI) :
146 CallGraphSCCPass(&ID), PassToPrint(PI) {}
148 virtual bool runOnSCC(std::vector<CallGraphNode *>&SCC) {
150 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
152 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
153 Function *F = SCC[i]->getFunction();
155 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
159 // Get and print pass...
163 virtual const char *getPassName() const { return "'Pass' Printer"; }
165 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166 AU.addRequiredID(PassToPrint);
167 AU.setPreservesAll();
171 char CallGraphSCCPassPrinter::ID = 0;
173 struct ModulePassPrinter : public ModulePass {
175 const PassInfo *PassToPrint;
176 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
179 virtual bool runOnModule(Module &M) {
181 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
182 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
185 // Get and print pass...
189 virtual const char *getPassName() const { return "'Pass' Printer"; }
191 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
192 AU.addRequiredID(PassToPrint);
193 AU.setPreservesAll();
197 char ModulePassPrinter::ID = 0;
198 struct FunctionPassPrinter : public FunctionPass {
199 const PassInfo *PassToPrint;
201 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
204 virtual bool runOnFunction(Function &F) {
206 outs() << "Printing analysis '" << PassToPrint->getPassName()
207 << "' for function '" << F.getName() << "':\n";
209 // Get and print pass...
210 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
214 virtual const char *getPassName() const { return "FunctionPass Printer"; }
216 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
217 AU.addRequiredID(PassToPrint);
218 AU.setPreservesAll();
222 char FunctionPassPrinter::ID = 0;
224 struct LoopPassPrinter : public LoopPass {
226 const PassInfo *PassToPrint;
227 LoopPassPrinter(const PassInfo *PI) :
228 LoopPass(&ID), PassToPrint(PI) {}
230 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
232 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
233 getAnalysisID<Pass>(PassToPrint).print(outs(),
234 L->getHeader()->getParent()->getParent());
236 // Get and print pass...
240 virtual const char *getPassName() const { return "'Pass' Printer"; }
242 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
243 AU.addRequiredID(PassToPrint);
244 AU.setPreservesAll();
248 char LoopPassPrinter::ID = 0;
250 struct BasicBlockPassPrinter : public BasicBlockPass {
251 const PassInfo *PassToPrint;
253 BasicBlockPassPrinter(const PassInfo *PI)
254 : BasicBlockPass(&ID), PassToPrint(PI) {}
256 virtual bool runOnBasicBlock(BasicBlock &BB) {
258 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
259 << "': Pass " << PassToPrint->getPassName() << ":\n";
262 // Get and print pass...
263 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
267 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
269 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
270 AU.addRequiredID(PassToPrint);
271 AU.setPreservesAll();
275 char BasicBlockPassPrinter::ID = 0;
276 inline void addPass(PassManager &PM, Pass *P) {
277 // Add the pass to the pass manager...
280 // If we are verifying all of the intermediate steps, add the verifier...
281 if (VerifyEach) PM.add(createVerifierPass());
284 /// AddOptimizationPasses - This routine adds optimization passes
285 /// based on selected optimization level, OptLevel. This routine
286 /// duplicates llvm-gcc behaviour.
288 /// OptLevel - Optimization Level
289 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
291 createStandardFunctionPasses(&FPM, OptLevel);
293 llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
294 createStandardModulePasses(&MPM, OptLevel,
295 /*OptimizeSize=*/ false,
297 /*UnrollLoops=*/ OptLevel > 1,
298 !DisableSimplifyLibCalls,
299 /*HaveExceptions=*/ true,
303 void AddStandardCompilePasses(PassManager &PM) {
304 PM.add(createVerifierPass()); // Verify that input is correct
306 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
308 // If the -strip-debug command line option was specified, do it.
310 addPass(PM, createStripSymbolsPass(true));
312 if (DisableOptimizations) return;
314 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
316 // -std-compile-opts adds the same module passes as -O3.
317 createStandardModulePasses(&PM, 3,
318 /*OptimizeSize=*/ false,
319 /*UnitAtATime=*/ true,
320 /*UnrollLoops=*/ true,
321 /*SimplifyLibCalls=*/ true,
322 /*HaveExceptions=*/ true,
326 void AddStandardLinkPasses(PassManager &PM) {
327 PM.add(createVerifierPass()); // Verify that input is correct
329 // If the -strip-debug command line option was specified, do it.
331 addPass(PM, createStripSymbolsPass(true));
333 if (DisableOptimizations) return;
335 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
336 /*RunInliner=*/ !DisableInline,
337 /*VerifyEach=*/ VerifyEach);
340 } // anonymous namespace
343 //===----------------------------------------------------------------------===//
346 int main(int argc, char **argv) {
347 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
348 LLVMContext &Context = getGlobalContext();
350 cl::ParseCommandLineOptions(argc, argv,
351 "llvm .bc -> .bc modular optimizer and analysis printer\n");
352 sys::PrintStackTraceOnErrorSignal();
354 // Allocate a full target machine description only if necessary.
355 // FIXME: The choice of target should be controllable on the command line.
356 std::auto_ptr<TargetMachine> target;
360 // Load the input module...
361 std::auto_ptr<Module> M;
362 M.reset(ParseIRFile(InputFilename, Err, Context));
365 Err.Print(argv[0], errs());
369 // Figure out what stream we are supposed to write to...
370 // FIXME: outs() is not binary!
371 raw_ostream *Out = &outs(); // Default to printing to stdout...
372 if (OutputFilename != "-") {
373 // Make sure that the Output file gets unlinked from the disk if we get a
375 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
377 std::string ErrorInfo;
378 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
379 raw_fd_ostream::F_Binary);
380 if (!ErrorInfo.empty()) {
381 errs() << ErrorInfo << '\n';
387 // If the output is set to be emitted to standard out, and standard out is a
388 // console, print out a warning message and refuse to do it. We don't
389 // impress anyone by spewing tons of binary goo to a terminal.
390 if (!Force && !NoOutput && !OutputAssembly)
391 if (CheckBitcodeOutputToConsole(*Out, !Quiet))
394 // Create a PassManager to hold and optimize the collection of passes we are
399 // Add an appropriate TargetData instance for this module...
401 const std::string &ModuleDataLayout = M.get()->getDataLayout();
402 if (!ModuleDataLayout.empty())
403 TD = new TargetData(ModuleDataLayout);
404 else if (!NoDefaultDataLayout)
405 TD = new TargetData(DefaultDataLayout);
410 FunctionPassManager *FPasses = NULL;
411 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
412 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
414 FPasses->add(new TargetData(*TD));
417 // If the -strip-debug command line option was specified, add it. If
418 // -std-compile-opts was also specified, it will handle StripDebug.
419 if (StripDebug && !StandardCompileOpts)
420 addPass(Passes, createStripSymbolsPass(true));
422 // Create a new optimization pass for each one specified on the command line
423 for (unsigned i = 0; i < PassList.size(); ++i) {
424 // Check to see if -std-compile-opts was specified before this option. If
426 if (StandardCompileOpts &&
427 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
428 AddStandardCompilePasses(Passes);
429 StandardCompileOpts = false;
432 if (StandardLinkOpts &&
433 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
434 AddStandardLinkPasses(Passes);
435 StandardLinkOpts = false;
438 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
439 AddOptimizationPasses(Passes, *FPasses, 1);
443 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
444 AddOptimizationPasses(Passes, *FPasses, 2);
448 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
449 AddOptimizationPasses(Passes, *FPasses, 3);
453 const PassInfo *PassInf = PassList[i];
455 if (PassInf->getNormalCtor())
456 P = PassInf->getNormalCtor()();
458 errs() << argv[0] << ": cannot create pass: "
459 << PassInf->getPassName() << "\n";
461 bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
462 bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
463 bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
464 bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
470 Passes.add(new BasicBlockPassPrinter(PassInf));
472 Passes.add(new LoopPassPrinter(PassInf));
474 Passes.add(new FunctionPassPrinter(PassInf));
475 else if (isCGSCCPass)
476 Passes.add(new CallGraphSCCPassPrinter(PassInf));
478 Passes.add(new ModulePassPrinter(PassInf));
483 Passes.add(createPrintModulePass(&errs()));
486 // If -std-compile-opts was specified at the end of the pass list, add them.
487 if (StandardCompileOpts) {
488 AddStandardCompilePasses(Passes);
489 StandardCompileOpts = false;
492 if (StandardLinkOpts) {
493 AddStandardLinkPasses(Passes);
494 StandardLinkOpts = false;
498 AddOptimizationPasses(Passes, *FPasses, 1);
501 AddOptimizationPasses(Passes, *FPasses, 2);
504 AddOptimizationPasses(Passes, *FPasses, 3);
506 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
507 FPasses->doInitialization();
508 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
513 // Check that the module is well formed on completion of optimization
514 if (!NoVerify && !VerifyEach)
515 Passes.add(createVerifierPass());
517 // Write bitcode or assembly out to disk or outs() as the last step...
518 if (!NoOutput && !AnalyzeOnly) {
520 Passes.add(createPrintModulePass(Out));
522 Passes.add(createBitcodeWriterPass(*Out));
525 // Now that we have all of the passes ready, run them.
526 Passes.run(*M.get());
528 // Delete the raw_fd_ostream.