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/PassManager.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/RegionPass.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/PassNameParser.h"
29 #include "llvm/Support/Signals.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/IRReader.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/PluginLoader.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/StandardPasses.h"
36 #include "llvm/Support/SystemUtils.h"
37 #include "llvm/Support/ToolOutputFile.h"
38 #include "llvm/LinkAllPasses.h"
39 #include "llvm/LinkAllVMCore.h"
44 // The OptimizationList is automatically populated with registered Passes by the
47 static cl::list
<const PassInfo
*, bool, PassNameParser
>
48 PassList(cl::desc("Optimizations available:"));
50 // Other command line options...
52 static cl::opt
<std::string
>
53 InputFilename(cl::Positional
, cl::desc("<input bitcode file>"),
54 cl::init("-"), cl::value_desc("filename"));
56 static cl::opt
<std::string
>
57 OutputFilename("o", cl::desc("Override output filename"),
58 cl::value_desc("filename"));
61 Force("f", cl::desc("Enable binary output on terminals"));
64 PrintEachXForm("p", cl::desc("Print module after each transformation"));
67 NoOutput("disable-output",
68 cl::desc("Do not write result bitcode file"), cl::Hidden
);
71 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
74 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden
);
77 VerifyEach("verify-each", cl::desc("Verify after each transform"));
80 StripDebug("strip-debug",
81 cl::desc("Strip debugger symbol info from translation unit"));
84 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
87 DisableOptimizations("disable-opt",
88 cl::desc("Do not run any optimization passes"));
91 DisableInternalize("disable-internalize",
92 cl::desc("Do not mark all symbols as internal"));
95 StandardCompileOpts("std-compile-opts",
96 cl::desc("Include the standard compile time optimizations"));
99 StandardLinkOpts("std-link-opts",
100 cl::desc("Include the standard link time optimizations"));
104 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
108 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
112 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
115 UnitAtATime("funit-at-a-time",
116 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
120 DisableSimplifyLibCalls("disable-simplify-libcalls",
121 cl::desc("Disable simplify-libcalls"));
124 Quiet("q", cl::desc("Obsolete option"), cl::Hidden
);
127 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet
));
130 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
133 PrintBreakpoints("print-breakpoints-for-testing",
134 cl::desc("Print select breakpoints location for testing"));
136 static cl::opt
<std::string
>
137 DefaultDataLayout("default-data-layout",
138 cl::desc("data layout string to use if not specified by module"),
139 cl::value_desc("layout-string"), cl::init(""));
141 // ---------- Define Printers for module and function passes ------------
144 struct CallGraphSCCPassPrinter
: public CallGraphSCCPass
{
146 const PassInfo
*PassToPrint
;
148 std::string PassName
;
150 CallGraphSCCPassPrinter(const PassInfo
*PI
, raw_ostream
&out
) :
151 CallGraphSCCPass(ID
), PassToPrint(PI
), Out(out
) {
152 std::string PassToPrintName
= PassToPrint
->getPassName();
153 PassName
= "CallGraphSCCPass Printer: " + PassToPrintName
;
156 virtual bool runOnSCC(CallGraphSCC
&SCC
) {
158 Out
<< "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
160 // Get and print pass...
161 for (CallGraphSCC::iterator I
= SCC
.begin(), E
= SCC
.end(); I
!= E
; ++I
) {
162 Function
*F
= (*I
)->getFunction();
164 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
170 virtual const char *getPassName() const { return PassName
.c_str(); }
172 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
173 AU
.addRequiredID(PassToPrint
->getTypeInfo());
174 AU
.setPreservesAll();
178 char CallGraphSCCPassPrinter::ID
= 0;
180 struct ModulePassPrinter
: public ModulePass
{
182 const PassInfo
*PassToPrint
;
184 std::string PassName
;
186 ModulePassPrinter(const PassInfo
*PI
, raw_ostream
&out
)
187 : ModulePass(ID
), PassToPrint(PI
), Out(out
) {
188 std::string PassToPrintName
= PassToPrint
->getPassName();
189 PassName
= "ModulePass Printer: " + PassToPrintName
;
192 virtual bool runOnModule(Module
&M
) {
194 Out
<< "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
196 // Get and print pass...
197 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
, &M
);
201 virtual const char *getPassName() const { return PassName
.c_str(); }
203 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
204 AU
.addRequiredID(PassToPrint
->getTypeInfo());
205 AU
.setPreservesAll();
209 char ModulePassPrinter::ID
= 0;
210 struct FunctionPassPrinter
: public FunctionPass
{
211 const PassInfo
*PassToPrint
;
214 std::string PassName
;
216 FunctionPassPrinter(const PassInfo
*PI
, raw_ostream
&out
)
217 : FunctionPass(ID
), PassToPrint(PI
), Out(out
) {
218 std::string PassToPrintName
= PassToPrint
->getPassName();
219 PassName
= "FunctionPass Printer: " + PassToPrintName
;
222 virtual bool runOnFunction(Function
&F
) {
224 Out
<< "Printing analysis '" << PassToPrint
->getPassName()
225 << "' for function '" << F
.getName() << "':\n";
227 // Get and print pass...
228 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
233 virtual const char *getPassName() const { return PassName
.c_str(); }
235 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
236 AU
.addRequiredID(PassToPrint
->getTypeInfo());
237 AU
.setPreservesAll();
241 char FunctionPassPrinter::ID
= 0;
243 struct LoopPassPrinter
: public LoopPass
{
245 const PassInfo
*PassToPrint
;
247 std::string PassName
;
249 LoopPassPrinter(const PassInfo
*PI
, raw_ostream
&out
) :
250 LoopPass(ID
), PassToPrint(PI
), Out(out
) {
251 std::string PassToPrintName
= PassToPrint
->getPassName();
252 PassName
= "LoopPass Printer: " + PassToPrintName
;
256 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
258 Out
<< "Printing analysis '" << PassToPrint
->getPassName() << "':\n";
260 // Get and print pass...
261 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
262 L
->getHeader()->getParent()->getParent());
266 virtual const char *getPassName() const { return PassName
.c_str(); }
268 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
269 AU
.addRequiredID(PassToPrint
->getTypeInfo());
270 AU
.setPreservesAll();
274 char LoopPassPrinter::ID
= 0;
276 struct RegionPassPrinter
: public RegionPass
{
278 const PassInfo
*PassToPrint
;
280 std::string PassName
;
282 RegionPassPrinter(const PassInfo
*PI
, raw_ostream
&out
) : RegionPass(ID
),
283 PassToPrint(PI
), Out(out
) {
284 std::string PassToPrintName
= PassToPrint
->getPassName();
285 PassName
= "RegionPass Printer: " + PassToPrintName
;
288 virtual bool runOnRegion(Region
*R
, RGPassManager
&RGM
) {
290 Out
<< "Printing analysis '" << PassToPrint
->getPassName() << "' for "
291 << "region: '" << R
->getNameStr() << "' in function '"
292 << R
->getEntry()->getParent()->getNameStr() << "':\n";
294 // Get and print pass...
295 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
296 R
->getEntry()->getParent()->getParent());
300 virtual const char *getPassName() const { return PassName
.c_str(); }
302 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
303 AU
.addRequiredID(PassToPrint
->getTypeInfo());
304 AU
.setPreservesAll();
308 char RegionPassPrinter::ID
= 0;
310 struct BasicBlockPassPrinter
: public BasicBlockPass
{
311 const PassInfo
*PassToPrint
;
314 std::string PassName
;
316 BasicBlockPassPrinter(const PassInfo
*PI
, raw_ostream
&out
)
317 : BasicBlockPass(ID
), PassToPrint(PI
), Out(out
) {
318 std::string PassToPrintName
= PassToPrint
->getPassName();
319 PassName
= "BasicBlockPass Printer: " + PassToPrintName
;
322 virtual bool runOnBasicBlock(BasicBlock
&BB
) {
324 Out
<< "Printing Analysis info for BasicBlock '" << BB
.getName()
325 << "': Pass " << PassToPrint
->getPassName() << ":\n";
327 // Get and print pass...
328 getAnalysisID
<Pass
>(PassToPrint
->getTypeInfo()).print(Out
,
329 BB
.getParent()->getParent());
333 virtual const char *getPassName() const { return PassName
.c_str(); }
335 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
336 AU
.addRequiredID(PassToPrint
->getTypeInfo());
337 AU
.setPreservesAll();
341 char BasicBlockPassPrinter::ID
= 0;
343 struct BreakpointPrinter
: public FunctionPass
{
347 BreakpointPrinter(raw_ostream
&out
)
348 : FunctionPass(ID
), Out(out
) {
351 virtual bool runOnFunction(Function
&F
) {
352 BasicBlock
&EntryBB
= F
.getEntryBlock();
353 BasicBlock::const_iterator BI
= EntryBB
.end();
356 const Instruction
*In
= BI
;
357 const DebugLoc DL
= In
->getDebugLoc();
358 if (!DL
.isUnknown()) {
359 DIScope
S(DL
.getScope(getGlobalContext()));
360 Out
<< S
.getFilename() << " " << DL
.getLine() << "\n";
364 } while (BI
!= EntryBB
.begin());
368 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
369 AU
.setPreservesAll();
373 char BreakpointPrinter::ID
= 0;
375 inline void addPass(PassManagerBase
&PM
, Pass
*P
) {
376 // Add the pass to the pass manager...
379 // If we are verifying all of the intermediate steps, add the verifier...
380 if (VerifyEach
) PM
.add(createVerifierPass());
383 /// AddOptimizationPasses - This routine adds optimization passes
384 /// based on selected optimization level, OptLevel. This routine
385 /// duplicates llvm-gcc behaviour.
387 /// OptLevel - Optimization Level
388 void AddOptimizationPasses(PassManagerBase
&MPM
, PassManagerBase
&FPM
,
390 createStandardFunctionPasses(&FPM
, OptLevel
);
392 llvm::Pass
*InliningPass
= 0;
395 } else if (OptLevel
) {
396 unsigned Threshold
= 225;
399 InliningPass
= createFunctionInliningPass(Threshold
);
401 InliningPass
= createAlwaysInlinerPass();
403 createStandardModulePasses(&MPM
, OptLevel
,
404 /*OptimizeSize=*/ false,
406 /*UnrollLoops=*/ OptLevel
> 1,
407 !DisableSimplifyLibCalls
,
408 /*HaveExceptions=*/ true,
412 void AddStandardCompilePasses(PassManagerBase
&PM
) {
413 PM
.add(createVerifierPass()); // Verify that input is correct
415 addPass(PM
, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
417 // If the -strip-debug command line option was specified, do it.
419 addPass(PM
, createStripSymbolsPass(true));
421 if (DisableOptimizations
) return;
423 llvm::Pass
*InliningPass
= !DisableInline
? createFunctionInliningPass() : 0;
425 // -std-compile-opts adds the same module passes as -O3.
426 createStandardModulePasses(&PM
, 3,
427 /*OptimizeSize=*/ false,
428 /*UnitAtATime=*/ true,
429 /*UnrollLoops=*/ true,
430 /*SimplifyLibCalls=*/ true,
431 /*HaveExceptions=*/ true,
435 void AddStandardLinkPasses(PassManagerBase
&PM
) {
436 PM
.add(createVerifierPass()); // Verify that input is correct
438 // If the -strip-debug command line option was specified, do it.
440 addPass(PM
, createStripSymbolsPass(true));
442 if (DisableOptimizations
) return;
444 createStandardLTOPasses(&PM
, /*Internalize=*/ !DisableInternalize
,
445 /*RunInliner=*/ !DisableInline
,
446 /*VerifyEach=*/ VerifyEach
);
449 } // anonymous namespace
452 //===----------------------------------------------------------------------===//
455 int main(int argc
, char **argv
) {
456 sys::PrintStackTraceOnErrorSignal();
457 llvm::PrettyStackTraceProgram
X(argc
, argv
);
459 // Enable debug stream buffering.
460 EnableDebugBuffering
= true;
462 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
463 LLVMContext
&Context
= getGlobalContext();
466 PassRegistry
&Registry
= *PassRegistry::getPassRegistry();
467 initializeCore(Registry
);
468 initializeScalarOpts(Registry
);
469 initializeIPO(Registry
);
470 initializeAnalysis(Registry
);
471 initializeIPA(Registry
);
472 initializeTransformUtils(Registry
);
473 initializeInstCombine(Registry
);
474 initializeInstrumentation(Registry
);
475 initializeTarget(Registry
);
477 cl::ParseCommandLineOptions(argc
, argv
,
478 "llvm .bc -> .bc modular optimizer and analysis printer\n");
480 if (AnalyzeOnly
&& NoOutput
) {
481 errs() << argv
[0] << ": analyze mode conflicts with no-output mode.\n";
485 // Allocate a full target machine description only if necessary.
486 // FIXME: The choice of target should be controllable on the command line.
487 std::auto_ptr
<TargetMachine
> target
;
491 // Load the input module...
492 std::auto_ptr
<Module
> M
;
493 M
.reset(ParseIRFile(InputFilename
, Err
, Context
));
496 Err
.Print(argv
[0], errs());
500 // Figure out what stream we are supposed to write to...
501 OwningPtr
<tool_output_file
> Out
;
503 if (!OutputFilename
.empty())
504 errs() << "WARNING: The -o (output filename) option is ignored when\n"
505 "the --disable-output option is used.\n";
507 // Default to standard output.
508 if (OutputFilename
.empty())
509 OutputFilename
= "-";
511 std::string ErrorInfo
;
512 Out
.reset(new tool_output_file(OutputFilename
.c_str(), ErrorInfo
,
513 raw_fd_ostream::F_Binary
));
514 if (!ErrorInfo
.empty()) {
515 errs() << ErrorInfo
<< '\n';
520 // If the output is set to be emitted to standard out, and standard out is a
521 // console, print out a warning message and refuse to do it. We don't
522 // impress anyone by spewing tons of binary goo to a terminal.
523 if (!Force
&& !NoOutput
&& !AnalyzeOnly
&& !OutputAssembly
)
524 if (CheckBitcodeOutputToConsole(Out
->os(), !Quiet
))
527 // Create a PassManager to hold and optimize the collection of passes we are
532 // Add an appropriate TargetData instance for this module...
534 const std::string
&ModuleDataLayout
= M
.get()->getDataLayout();
535 if (!ModuleDataLayout
.empty())
536 TD
= new TargetData(ModuleDataLayout
);
537 else if (!DefaultDataLayout
.empty())
538 TD
= new TargetData(DefaultDataLayout
);
543 OwningPtr
<PassManager
> FPasses
;
544 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
) {
545 FPasses
.reset(new PassManager());
547 FPasses
->add(new TargetData(*TD
));
550 if (PrintBreakpoints
) {
551 // Default to standard output.
553 if (OutputFilename
.empty())
554 OutputFilename
= "-";
556 std::string ErrorInfo
;
557 Out
.reset(new tool_output_file(OutputFilename
.c_str(), ErrorInfo
,
558 raw_fd_ostream::F_Binary
));
559 if (!ErrorInfo
.empty()) {
560 errs() << ErrorInfo
<< '\n';
564 Passes
.add(new BreakpointPrinter(Out
->os()));
568 // If the -strip-debug command line option was specified, add it. If
569 // -std-compile-opts was also specified, it will handle StripDebug.
570 if (StripDebug
&& !StandardCompileOpts
)
571 addPass(Passes
, createStripSymbolsPass(true));
573 // Create a new optimization pass for each one specified on the command line
574 for (unsigned i
= 0; i
< PassList
.size(); ++i
) {
575 // Check to see if -std-compile-opts was specified before this option. If
577 if (StandardCompileOpts
&&
578 StandardCompileOpts
.getPosition() < PassList
.getPosition(i
)) {
579 AddStandardCompilePasses(Passes
);
580 StandardCompileOpts
= false;
583 if (StandardLinkOpts
&&
584 StandardLinkOpts
.getPosition() < PassList
.getPosition(i
)) {
585 AddStandardLinkPasses(Passes
);
586 StandardLinkOpts
= false;
589 if (OptLevelO1
&& OptLevelO1
.getPosition() < PassList
.getPosition(i
)) {
590 AddOptimizationPasses(Passes
, *FPasses
, 1);
594 if (OptLevelO2
&& OptLevelO2
.getPosition() < PassList
.getPosition(i
)) {
595 AddOptimizationPasses(Passes
, *FPasses
, 2);
599 if (OptLevelO3
&& OptLevelO3
.getPosition() < PassList
.getPosition(i
)) {
600 AddOptimizationPasses(Passes
, *FPasses
, 3);
604 const PassInfo
*PassInf
= PassList
[i
];
606 if (PassInf
->getNormalCtor())
607 P
= PassInf
->getNormalCtor()();
609 errs() << argv
[0] << ": cannot create pass: "
610 << PassInf
->getPassName() << "\n";
612 PassKind Kind
= P
->getPassKind();
618 Passes
.add(new BasicBlockPassPrinter(PassInf
, Out
->os()));
621 Passes
.add(new RegionPassPrinter(PassInf
, Out
->os()));
624 Passes
.add(new LoopPassPrinter(PassInf
, Out
->os()));
627 Passes
.add(new FunctionPassPrinter(PassInf
, Out
->os()));
629 case PT_CallGraphSCC
:
630 Passes
.add(new CallGraphSCCPassPrinter(PassInf
, Out
->os()));
633 Passes
.add(new ModulePassPrinter(PassInf
, Out
->os()));
640 Passes
.add(createPrintModulePass(&errs()));
643 // If -std-compile-opts was specified at the end of the pass list, add them.
644 if (StandardCompileOpts
) {
645 AddStandardCompilePasses(Passes
);
646 StandardCompileOpts
= false;
649 if (StandardLinkOpts
) {
650 AddStandardLinkPasses(Passes
);
651 StandardLinkOpts
= false;
655 AddOptimizationPasses(Passes
, *FPasses
, 1);
658 AddOptimizationPasses(Passes
, *FPasses
, 2);
661 AddOptimizationPasses(Passes
, *FPasses
, 3);
663 if (OptLevelO1
|| OptLevelO2
|| OptLevelO3
)
664 FPasses
->run(*M
.get());
666 // Check that the module is well formed on completion of optimization
667 if (!NoVerify
&& !VerifyEach
)
668 Passes
.add(createVerifierPass());
670 // Write bitcode or assembly to the output as the last step...
671 if (!NoOutput
&& !AnalyzeOnly
) {
673 Passes
.add(createPrintModulePass(&Out
->os()));
675 Passes
.add(createBitcodeWriterPass(Out
->os()));
678 // Now that we have all of the passes ready, run them.
679 Passes
.run(*M
.get());
682 if (!NoOutput
|| PrintBreakpoints
)