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/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/StandardPasses.h"
33 #include "llvm/Support/SystemUtils.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/LinkAllPasses.h"
36 #include "llvm/LinkAllVMCore.h"
41 // The OptimizationList is automatically populated with registered Passes by the
44 static cl::list
<const PassInfo
*, bool, PassNameParser
>
45 PassList(cl::desc("Optimizations available:"));
47 // Other command line options...
49 static cl::opt
<std::string
>
50 InputFilename(cl::Positional
, cl::desc("<input bitcode file>"),
51 cl::init("-"), cl::value_desc("filename"));
53 static cl::opt
<std::string
>
54 OutputFilename("o", cl::desc("Override output filename"),
55 cl::value_desc("filename"), cl::init("-"));
58 Force("f", cl::desc("Enable binary output on terminals"));
61 PrintEachXForm("p", cl::desc("Print module after each transformation"));
64 NoOutput("disable-output",
65 cl::desc("Do not write result bitcode file"), cl::Hidden
);
68 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden
);
71 VerifyEach("verify-each", cl::desc("Verify after each transform"));
74 StripDebug("strip-debug",
75 cl::desc("Strip debugger symbol info from translation unit"));
78 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
81 DisableOptimizations("disable-opt",
82 cl::desc("Do not run any optimization passes"));
85 DisableInternalize("disable-internalize",
86 cl::desc("Do not mark all symbols as internal"));
89 StandardCompileOpts("std-compile-opts",
90 cl::desc("Include the standard compile time optimizations"));
93 StandardLinkOpts("std-link-opts",
94 cl::desc("Include the standard link time optimizations"));
98 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
102 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
106 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
109 UnitAtATime("funit-at-a-time",
110 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
114 DisableSimplifyLibCalls("disable-simplify-libcalls",
115 cl::desc("Disable simplify-libcalls"));
118 Quiet("q", cl::desc("Obsolete option"), cl::Hidden
);
121 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet
));
124 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
126 // ---------- Define Printers for module and function passes ------------
129 struct CallGraphSCCPassPrinter
: public CallGraphSCCPass
{
131 const PassInfo
*PassToPrint
;
132 CallGraphSCCPassPrinter(const PassInfo
*PI
) :
133 CallGraphSCCPass(&ID
), PassToPrint(PI
) {}
135 virtual bool runOnSCC(std::vector
<CallGraphNode
*>&SCC
) {
137 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
139 for (unsigned i
= 0, e
= SCC
.size(); i
!= e
; ++i
) {
140 Function
*F
= SCC
[i
]->getFunction();
142 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
->getParent());
146 // Get and print pass...
150 virtual const char *getPassName() const { return "'Pass' Printer"; }
152 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
153 AU
.addRequiredID(PassToPrint
);
154 AU
.setPreservesAll();
158 char CallGraphSCCPassPrinter::ID
= 0;
160 struct ModulePassPrinter
: public ModulePass
{
162 const PassInfo
*PassToPrint
;
163 ModulePassPrinter(const PassInfo
*PI
) : ModulePass(&ID
),
166 virtual bool runOnModule(Module
&M
) {
168 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
169 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), &M
);
172 // Get and print pass...
176 virtual const char *getPassName() const { return "'Pass' Printer"; }
178 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
179 AU
.addRequiredID(PassToPrint
);
180 AU
.setPreservesAll();
184 char ModulePassPrinter::ID
= 0;
185 struct FunctionPassPrinter
: public FunctionPass
{
186 const PassInfo
*PassToPrint
;
188 FunctionPassPrinter(const PassInfo
*PI
) : FunctionPass(&ID
),
191 virtual bool runOnFunction(Function
&F
) {
193 outs() << "Printing analysis '" << PassToPrint
->getPassName()
194 << "' for function '" << F
.getName() << "':\n";
196 // Get and print pass...
197 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
.getParent());
201 virtual const char *getPassName() const { return "FunctionPass Printer"; }
203 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
204 AU
.addRequiredID(PassToPrint
);
205 AU
.setPreservesAll();
209 char FunctionPassPrinter::ID
= 0;
211 struct LoopPassPrinter
: public LoopPass
{
213 const PassInfo
*PassToPrint
;
214 LoopPassPrinter(const PassInfo
*PI
) :
215 LoopPass(&ID
), PassToPrint(PI
) {}
217 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
219 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
220 getAnalysisID
<Pass
>(PassToPrint
).print(outs(),
221 L
->getHeader()->getParent()->getParent());
223 // Get and print pass...
227 virtual const char *getPassName() const { return "'Pass' Printer"; }
229 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
230 AU
.addRequiredID(PassToPrint
);
231 AU
.setPreservesAll();
235 char LoopPassPrinter::ID
= 0;
237 struct BasicBlockPassPrinter
: public BasicBlockPass
{
238 const PassInfo
*PassToPrint
;
240 BasicBlockPassPrinter(const PassInfo
*PI
)
241 : BasicBlockPass(&ID
), PassToPrint(PI
) {}
243 virtual bool runOnBasicBlock(BasicBlock
&BB
) {
245 outs() << "Printing Analysis info for BasicBlock '" << BB
.getName()
246 << "': Pass " << PassToPrint
->getPassName() << ":\n";
249 // Get and print pass...
250 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), BB
.getParent()->getParent());
254 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
256 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
257 AU
.addRequiredID(PassToPrint
);
258 AU
.setPreservesAll();
262 char BasicBlockPassPrinter::ID
= 0;
263 inline void addPass(PassManager
&PM
, Pass
*P
) {
264 // Add the pass to the pass manager...
267 // If we are verifying all of the intermediate steps, add the verifier...
268 if (VerifyEach
) PM
.add(createVerifierPass());
271 /// AddOptimizationPasses - This routine adds optimization passes
272 /// based on selected optimization level, OptLevel. This routine
273 /// duplicates llvm-gcc behaviour.
275 /// OptLevel - Optimization Level
276 void AddOptimizationPasses(PassManager
&MPM
, FunctionPassManager
&FPM
,
278 createStandardFunctionPasses(&FPM
, OptLevel
);
280 llvm::Pass
*InliningPass
= OptLevel
> 1 ? createFunctionInliningPass() : 0;
281 createStandardModulePasses(&MPM
, OptLevel
,
282 /*OptimizeSize=*/ false,
284 /*UnrollLoops=*/ OptLevel
> 1,
285 !DisableSimplifyLibCalls
,
286 /*HaveExceptions=*/ true,
290 void AddStandardCompilePasses(PassManager
&PM
) {
291 PM
.add(createVerifierPass()); // Verify that input is correct
293 addPass(PM
, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
295 // If the -strip-debug command line option was specified, do it.
297 addPass(PM
, createStripSymbolsPass(true));
299 if (DisableOptimizations
) return;
301 llvm::Pass
*InliningPass
= !DisableInline
? createFunctionInliningPass() : 0;
303 // -std-compile-opts adds the same module passes as -O3.
304 createStandardModulePasses(&PM
, 3,
305 /*OptimizeSize=*/ false,
306 /*UnitAtATime=*/ true,
307 /*UnrollLoops=*/ true,
308 /*SimplifyLibCalls=*/ true,
309 /*HaveExceptions=*/ true,
313 void AddStandardLinkPasses(PassManager
&PM
) {
314 PM
.add(createVerifierPass()); // Verify that input is correct
316 // If the -strip-debug command line option was specified, do it.
318 addPass(PM
, createStripSymbolsPass(true));
320 if (DisableOptimizations
) return;
322 createStandardLTOPasses(&PM
, /*Internalize=*/ !DisableInternalize
,
323 /*RunInliner=*/ !DisableInline
,
324 /*VerifyEach=*/ VerifyEach
);
327 } // anonymous namespace
330 //===----------------------------------------------------------------------===//
333 int main(int argc
, char **argv
) {
334 llvm_shutdown_obj X
; // Call llvm_shutdown() on exit.
335 LLVMContext
&Context
= getGlobalContext();
337 cl::ParseCommandLineOptions(argc
, argv
,
338 "llvm .bc -> .bc modular optimizer and analysis printer\n");
339 sys::PrintStackTraceOnErrorSignal();
341 // Allocate a full target machine description only if necessary.
342 // FIXME: The choice of target should be controllable on the command line.
343 std::auto_ptr
<TargetMachine
> target
;
345 std::string ErrorMessage
;
347 // Load the input module...
348 std::auto_ptr
<Module
> M
;
349 if (MemoryBuffer
*Buffer
350 = MemoryBuffer::getFileOrSTDIN(InputFilename
, &ErrorMessage
)) {
351 M
.reset(ParseBitcodeFile(Buffer
, Context
, &ErrorMessage
));
356 errs() << argv
[0] << ": ";
357 if (ErrorMessage
.size())
358 errs() << ErrorMessage
<< "\n";
360 errs() << "bitcode didn't read correctly.\n";
364 // Figure out what stream we are supposed to write to...
365 // FIXME: outs() is not binary!
366 raw_ostream
*Out
= &outs(); // Default to printing to stdout...
367 if (OutputFilename
!= "-") {
368 std::string ErrorInfo
;
369 Out
= new raw_fd_ostream(OutputFilename
.c_str(), ErrorInfo
,
370 raw_fd_ostream::F_Binary
);
371 if (!ErrorInfo
.empty()) {
372 errs() << ErrorInfo
<< '\n';
377 // Make sure that the Output file gets unlinked from the disk if we get a
379 sys::RemoveFileOnSignal(sys::Path(OutputFilename
));
382 // If the output is set to be emitted to standard out, and standard out is a
383 // console, print out a warning message and refuse to do it. We don't
384 // impress anyone by spewing tons of binary goo to a terminal.
385 if (!Force
&& !NoOutput
&& CheckBitcodeOutputToConsole(*Out
, !Quiet
))
388 // Create a PassManager to hold and optimize the collection of passes we are
393 // Add an appropriate TargetData instance for this module...
394 Passes
.add(new TargetData(M
.get()));
396 FunctionPassManager
*FPasses
= NULL
;
397 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
398 FPasses
= new FunctionPassManager(new ExistingModuleProvider(M
.get()));
399 FPasses
->add(new TargetData(M
.get()));
402 // If the -strip-debug command line option was specified, add it. If
403 // -std-compile-opts was also specified, it will handle StripDebug.
404 if (StripDebug
&& !StandardCompileOpts
)
405 addPass(Passes
, createStripSymbolsPass(true));
407 // Create a new optimization pass for each one specified on the command line
408 for (unsigned i
= 0; i
< PassList
.size(); ++i
) {
409 // Check to see if -std-compile-opts was specified before this option. If
411 if (StandardCompileOpts
&&
412 StandardCompileOpts
.getPosition() < PassList
.getPosition(i
)) {
413 AddStandardCompilePasses(Passes
);
414 StandardCompileOpts
= false;
417 if (StandardLinkOpts
&&
418 StandardLinkOpts
.getPosition() < PassList
.getPosition(i
)) {
419 AddStandardLinkPasses(Passes
);
420 StandardLinkOpts
= false;
423 if (OptLevelO1
&& OptLevelO1
.getPosition() < PassList
.getPosition(i
)) {
424 AddOptimizationPasses(Passes
, *FPasses
, 1);
428 if (OptLevelO2
&& OptLevelO2
.getPosition() < PassList
.getPosition(i
)) {
429 AddOptimizationPasses(Passes
, *FPasses
, 2);
433 if (OptLevelO3
&& OptLevelO3
.getPosition() < PassList
.getPosition(i
)) {
434 AddOptimizationPasses(Passes
, *FPasses
, 3);
438 const PassInfo
*PassInf
= PassList
[i
];
440 if (PassInf
->getNormalCtor())
441 P
= PassInf
->getNormalCtor()();
443 errs() << argv
[0] << ": cannot create pass: "
444 << PassInf
->getPassName() << "\n";
446 bool isBBPass
= dynamic_cast<BasicBlockPass
*>(P
) != 0;
447 bool isLPass
= !isBBPass
&& dynamic_cast<LoopPass
*>(P
) != 0;
448 bool isFPass
= !isLPass
&& dynamic_cast<FunctionPass
*>(P
) != 0;
449 bool isCGSCCPass
= !isFPass
&& dynamic_cast<CallGraphSCCPass
*>(P
) != 0;
455 Passes
.add(new BasicBlockPassPrinter(PassInf
));
457 Passes
.add(new LoopPassPrinter(PassInf
));
459 Passes
.add(new FunctionPassPrinter(PassInf
));
460 else if (isCGSCCPass
)
461 Passes
.add(new CallGraphSCCPassPrinter(PassInf
));
463 Passes
.add(new ModulePassPrinter(PassInf
));
468 Passes
.add(createPrintModulePass(&errs()));
471 // If -std-compile-opts was specified at the end of the pass list, add them.
472 if (StandardCompileOpts
) {
473 AddStandardCompilePasses(Passes
);
474 StandardCompileOpts
= false;
477 if (StandardLinkOpts
) {
478 AddStandardLinkPasses(Passes
);
479 StandardLinkOpts
= false;
483 AddOptimizationPasses(Passes
, *FPasses
, 1);
487 AddOptimizationPasses(Passes
, *FPasses
, 2);
491 AddOptimizationPasses(Passes
, *FPasses
, 3);
494 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
495 FPasses
->doInitialization();
496 for (Module::iterator I
= M
.get()->begin(), E
= M
.get()->end();
501 // Check that the module is well formed on completion of optimization
502 if (!NoVerify
&& !VerifyEach
)
503 Passes
.add(createVerifierPass());
505 // Write bitcode out to disk or outs() as the last step...
506 if (!NoOutput
&& !AnalyzeOnly
)
507 Passes
.add(createBitcodeWriterPass(*Out
));
509 // Now that we have all of the passes ready, run them.
510 Passes
.run(*M
.get());
512 // Delete the raw_fd_ostream.
517 } catch (const std::string
& msg
) {
518 errs() << argv
[0] << ": " << msg
<< "\n";
520 errs() << argv
[0] << ": Unexpected unknown exception occurred.\n";