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(""));
135 // ---------- Define Printers for module and function passes ------------
138 struct CallGraphSCCPassPrinter
: public CallGraphSCCPass
{
140 const PassInfo
*PassToPrint
;
141 CallGraphSCCPassPrinter(const PassInfo
*PI
) :
142 CallGraphSCCPass(&ID
), PassToPrint(PI
) {}
144 virtual bool runOnSCC(std::vector
<CallGraphNode
*>&SCC
) {
146 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
148 for (unsigned i
= 0, e
= SCC
.size(); i
!= e
; ++i
) {
149 Function
*F
= SCC
[i
]->getFunction();
151 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
->getParent());
155 // Get and print pass...
159 virtual const char *getPassName() const { return "'Pass' Printer"; }
161 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
162 AU
.addRequiredID(PassToPrint
);
163 AU
.setPreservesAll();
167 char CallGraphSCCPassPrinter::ID
= 0;
169 struct ModulePassPrinter
: public ModulePass
{
171 const PassInfo
*PassToPrint
;
172 ModulePassPrinter(const PassInfo
*PI
) : ModulePass(&ID
),
175 virtual bool runOnModule(Module
&M
) {
177 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
178 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), &M
);
181 // Get and print pass...
185 virtual const char *getPassName() const { return "'Pass' Printer"; }
187 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
188 AU
.addRequiredID(PassToPrint
);
189 AU
.setPreservesAll();
193 char ModulePassPrinter::ID
= 0;
194 struct FunctionPassPrinter
: public FunctionPass
{
195 const PassInfo
*PassToPrint
;
197 FunctionPassPrinter(const PassInfo
*PI
) : FunctionPass(&ID
),
200 virtual bool runOnFunction(Function
&F
) {
202 outs() << "Printing analysis '" << PassToPrint
->getPassName()
203 << "' for function '" << F
.getName() << "':\n";
205 // Get and print pass...
206 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), F
.getParent());
210 virtual const char *getPassName() const { return "FunctionPass Printer"; }
212 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
213 AU
.addRequiredID(PassToPrint
);
214 AU
.setPreservesAll();
218 char FunctionPassPrinter::ID
= 0;
220 struct LoopPassPrinter
: public LoopPass
{
222 const PassInfo
*PassToPrint
;
223 LoopPassPrinter(const PassInfo
*PI
) :
224 LoopPass(&ID
), PassToPrint(PI
) {}
226 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
228 outs() << "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
229 getAnalysisID
<Pass
>(PassToPrint
).print(outs(),
230 L
->getHeader()->getParent()->getParent());
232 // Get and print pass...
236 virtual const char *getPassName() const { return "'Pass' Printer"; }
238 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
239 AU
.addRequiredID(PassToPrint
);
240 AU
.setPreservesAll();
244 char LoopPassPrinter::ID
= 0;
246 struct BasicBlockPassPrinter
: public BasicBlockPass
{
247 const PassInfo
*PassToPrint
;
249 BasicBlockPassPrinter(const PassInfo
*PI
)
250 : BasicBlockPass(&ID
), PassToPrint(PI
) {}
252 virtual bool runOnBasicBlock(BasicBlock
&BB
) {
254 outs() << "Printing Analysis info for BasicBlock '" << BB
.getName()
255 << "': Pass " << PassToPrint
->getPassName() << ":\n";
258 // Get and print pass...
259 getAnalysisID
<Pass
>(PassToPrint
).print(outs(), BB
.getParent()->getParent());
263 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
265 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
266 AU
.addRequiredID(PassToPrint
);
267 AU
.setPreservesAll();
271 char BasicBlockPassPrinter::ID
= 0;
272 inline void addPass(PassManager
&PM
, Pass
*P
) {
273 // Add the pass to the pass manager...
276 // If we are verifying all of the intermediate steps, add the verifier...
277 if (VerifyEach
) PM
.add(createVerifierPass());
280 /// AddOptimizationPasses - This routine adds optimization passes
281 /// based on selected optimization level, OptLevel. This routine
282 /// duplicates llvm-gcc behaviour.
284 /// OptLevel - Optimization Level
285 void AddOptimizationPasses(PassManager
&MPM
, FunctionPassManager
&FPM
,
287 createStandardFunctionPasses(&FPM
, OptLevel
);
289 llvm::Pass
*InliningPass
= OptLevel
> 1 ? createFunctionInliningPass() : 0;
290 createStandardModulePasses(&MPM
, OptLevel
,
291 /*OptimizeSize=*/ false,
293 /*UnrollLoops=*/ OptLevel
> 1,
294 !DisableSimplifyLibCalls
,
295 /*HaveExceptions=*/ true,
299 void AddStandardCompilePasses(PassManager
&PM
) {
300 PM
.add(createVerifierPass()); // Verify that input is correct
302 addPass(PM
, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
304 // If the -strip-debug command line option was specified, do it.
306 addPass(PM
, createStripSymbolsPass(true));
308 if (DisableOptimizations
) return;
310 llvm::Pass
*InliningPass
= !DisableInline
? createFunctionInliningPass() : 0;
312 // -std-compile-opts adds the same module passes as -O3.
313 createStandardModulePasses(&PM
, 3,
314 /*OptimizeSize=*/ false,
315 /*UnitAtATime=*/ true,
316 /*UnrollLoops=*/ true,
317 /*SimplifyLibCalls=*/ true,
318 /*HaveExceptions=*/ true,
322 void AddStandardLinkPasses(PassManager
&PM
) {
323 PM
.add(createVerifierPass()); // Verify that input is correct
325 // If the -strip-debug command line option was specified, do it.
327 addPass(PM
, createStripSymbolsPass(true));
329 if (DisableOptimizations
) return;
331 createStandardLTOPasses(&PM
, /*Internalize=*/ !DisableInternalize
,
332 /*RunInliner=*/ !DisableInline
,
333 /*VerifyEach=*/ VerifyEach
);
336 } // anonymous namespace
339 //===----------------------------------------------------------------------===//
342 int main(int argc
, char **argv
) {
343 llvm_shutdown_obj X
; // Call llvm_shutdown() on exit.
344 LLVMContext
&Context
= getGlobalContext();
346 cl::ParseCommandLineOptions(argc
, argv
,
347 "llvm .bc -> .bc modular optimizer and analysis printer\n");
348 sys::PrintStackTraceOnErrorSignal();
350 // Allocate a full target machine description only if necessary.
351 // FIXME: The choice of target should be controllable on the command line.
352 std::auto_ptr
<TargetMachine
> target
;
356 // Load the input module...
357 std::auto_ptr
<Module
> M
;
358 M
.reset(ParseIRFile(InputFilename
, Err
, Context
));
361 Err
.Print(argv
[0], errs());
365 // Figure out what stream we are supposed to write to...
366 // FIXME: outs() is not binary!
367 raw_ostream
*Out
= &outs(); // Default to printing to stdout...
368 if (OutputFilename
!= "-") {
369 // Make sure that the Output file gets unlinked from the disk if we get a
371 sys::RemoveFileOnSignal(sys::Path(OutputFilename
));
373 std::string ErrorInfo
;
374 Out
= new raw_fd_ostream(OutputFilename
.c_str(), ErrorInfo
,
375 raw_fd_ostream::F_Binary
);
376 if (!ErrorInfo
.empty()) {
377 errs() << ErrorInfo
<< '\n';
383 // If the output is set to be emitted to standard out, and standard out is a
384 // console, print out a warning message and refuse to do it. We don't
385 // impress anyone by spewing tons of binary goo to a terminal.
386 if (!Force
&& !NoOutput
&& !OutputAssembly
)
387 if (CheckBitcodeOutputToConsole(*Out
, !Quiet
))
390 // Create a PassManager to hold and optimize the collection of passes we are
395 // Add an appropriate TargetData instance for this module...
397 const std::string
&ModuleDataLayout
= M
.get()->getDataLayout();
398 if (!ModuleDataLayout
.empty())
399 TD
= new TargetData(ModuleDataLayout
);
400 else if (!DefaultDataLayout
.empty())
401 TD
= new TargetData(DefaultDataLayout
);
406 FunctionPassManager
*FPasses
= NULL
;
407 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
408 FPasses
= new FunctionPassManager(new ExistingModuleProvider(M
.get()));
410 FPasses
->add(new TargetData(*TD
));
413 // If the -strip-debug command line option was specified, add it. If
414 // -std-compile-opts was also specified, it will handle StripDebug.
415 if (StripDebug
&& !StandardCompileOpts
)
416 addPass(Passes
, createStripSymbolsPass(true));
418 // Create a new optimization pass for each one specified on the command line
419 for (unsigned i
= 0; i
< PassList
.size(); ++i
) {
420 // Check to see if -std-compile-opts was specified before this option. If
422 if (StandardCompileOpts
&&
423 StandardCompileOpts
.getPosition() < PassList
.getPosition(i
)) {
424 AddStandardCompilePasses(Passes
);
425 StandardCompileOpts
= false;
428 if (StandardLinkOpts
&&
429 StandardLinkOpts
.getPosition() < PassList
.getPosition(i
)) {
430 AddStandardLinkPasses(Passes
);
431 StandardLinkOpts
= false;
434 if (OptLevelO1
&& OptLevelO1
.getPosition() < PassList
.getPosition(i
)) {
435 AddOptimizationPasses(Passes
, *FPasses
, 1);
439 if (OptLevelO2
&& OptLevelO2
.getPosition() < PassList
.getPosition(i
)) {
440 AddOptimizationPasses(Passes
, *FPasses
, 2);
444 if (OptLevelO3
&& OptLevelO3
.getPosition() < PassList
.getPosition(i
)) {
445 AddOptimizationPasses(Passes
, *FPasses
, 3);
449 const PassInfo
*PassInf
= PassList
[i
];
451 if (PassInf
->getNormalCtor())
452 P
= PassInf
->getNormalCtor()();
454 errs() << argv
[0] << ": cannot create pass: "
455 << PassInf
->getPassName() << "\n";
457 bool isBBPass
= dynamic_cast<BasicBlockPass
*>(P
) != 0;
458 bool isLPass
= !isBBPass
&& dynamic_cast<LoopPass
*>(P
) != 0;
459 bool isFPass
= !isLPass
&& dynamic_cast<FunctionPass
*>(P
) != 0;
460 bool isCGSCCPass
= !isFPass
&& dynamic_cast<CallGraphSCCPass
*>(P
) != 0;
466 Passes
.add(new BasicBlockPassPrinter(PassInf
));
468 Passes
.add(new LoopPassPrinter(PassInf
));
470 Passes
.add(new FunctionPassPrinter(PassInf
));
471 else if (isCGSCCPass
)
472 Passes
.add(new CallGraphSCCPassPrinter(PassInf
));
474 Passes
.add(new ModulePassPrinter(PassInf
));
479 Passes
.add(createPrintModulePass(&errs()));
482 // If -std-compile-opts was specified at the end of the pass list, add them.
483 if (StandardCompileOpts
) {
484 AddStandardCompilePasses(Passes
);
485 StandardCompileOpts
= false;
488 if (StandardLinkOpts
) {
489 AddStandardLinkPasses(Passes
);
490 StandardLinkOpts
= false;
494 AddOptimizationPasses(Passes
, *FPasses
, 1);
497 AddOptimizationPasses(Passes
, *FPasses
, 2);
500 AddOptimizationPasses(Passes
, *FPasses
, 3);
502 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
503 FPasses
->doInitialization();
504 for (Module::iterator I
= M
.get()->begin(), E
= M
.get()->end();
509 // Check that the module is well formed on completion of optimization
510 if (!NoVerify
&& !VerifyEach
)
511 Passes
.add(createVerifierPass());
513 // Write bitcode or assembly out to disk or outs() as the last step...
514 if (!NoOutput
&& !AnalyzeOnly
) {
516 Passes
.add(createPrintModulePass(Out
));
518 Passes
.add(createBitcodeWriterPass(*Out
));
521 // Now that we have all of the passes ready, run them.
522 Passes
.run(*M
.get());
524 // Delete the raw_fd_ostream.