blob: ae076102d5b6d737a7bf94bff1bfb41b61cee1f5 [file] [log] [blame]
Chris Lattner76351aa2004-04-02 05:06:57 +00001//===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattner00950542001-06-06 20:29:01 +000010// Optimizations may be specified an arbitrary number of times on the command
Reid Spencerfd90dd52006-08-18 06:34:30 +000011// line, They are run in the order specified.
Chris Lattner00950542001-06-06 20:29:01 +000012//
Chris Lattner0eafc312001-10-18 06:05:15 +000013//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000014
Chris Lattner00950542001-06-06 20:29:01 +000015#include "llvm/Module.h"
Devang Patel2d7551c2008-09-16 22:25:14 +000016#include "llvm/ModuleProvider.h"
Chris Lattnerfb1b3f12002-01-31 00:47:12 +000017#include "llvm/PassManager.h"
Devang Patel28552da2007-06-28 23:09:25 +000018#include "llvm/CallGraphSCCPass.h"
Chris Lattnerb330e382007-05-06 02:42:03 +000019#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnerffa6f9c2001-10-19 15:39:14 +000020#include "llvm/Assembly/PrintModulePass.h"
Chris Lattner22d26d72002-02-20 17:56:53 +000021#include "llvm/Analysis/Verifier.h"
Devang Patel1bc89362007-03-07 00:26:10 +000022#include "llvm/Analysis/LoopPass.h"
Devang Patel28552da2007-06-28 23:09:25 +000023#include "llvm/Analysis/CallGraph.h"
Owen Anderson07000c62006-05-12 06:33:49 +000024#include "llvm/Target/TargetData.h"
Vikram S. Adve18fdfc42002-09-16 16:09:43 +000025#include "llvm/Target/TargetMachine.h"
Chris Lattner2053a2a2002-07-26 21:09:32 +000026#include "llvm/Support/PassNameParser.h"
Chris Lattnerbed85ff2004-05-27 05:41:36 +000027#include "llvm/System/Signals.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000028#include "llvm/Support/ManagedStatic.h"
Chris Lattnerb330e382007-05-06 02:42:03 +000029#include "llvm/Support/MemoryBuffer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/Support/PluginLoader.h"
Bill Wendlinga5b31ca2006-11-28 23:33:06 +000031#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/SystemUtils.h"
Reid Spencer62c51052006-08-21 05:34:03 +000033#include "llvm/LinkAllPasses.h"
Reid Spenceraf303d52006-06-07 23:03:13 +000034#include "llvm/LinkAllVMCore.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000035#include <iostream>
Chris Lattner73e11d72001-10-18 06:13:08 +000036#include <fstream>
Chris Lattner63202322001-11-26 19:22:39 +000037#include <memory>
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000038#include <algorithm>
Brian Gaeked0fde302003-11-11 22:41:34 +000039using namespace llvm;
Chris Lattner9d6e7eb2002-04-12 18:21:13 +000040
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000041// The OptimizationList is automatically populated with registered Passes by the
42// PassNameParser.
43//
Chris Lattner7f500f72006-08-27 22:07:01 +000044static cl::list<const PassInfo*, bool, PassNameParser>
45PassList(cl::desc("Optimizations available:"));
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000046
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000047// Other command line options...
Chris Lattnerfb1b3f12002-01-31 00:47:12 +000048//
Chris Lattner6c8103f2003-05-22 20:13:16 +000049static cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000050InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
Reid Spencerfd90dd52006-08-18 06:34:30 +000051 cl::init("-"), cl::value_desc("filename"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000052
Chris Lattner6c8103f2003-05-22 20:13:16 +000053static cl::opt<std::string>
Chris Lattner5ff62e92002-07-22 02:10:13 +000054OutputFilename("o", cl::desc("Override output filename"),
Chris Lattnerb592fc22003-12-10 14:41:33 +000055 cl::value_desc("filename"), cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000056
57static cl::opt<bool>
58Force("f", cl::desc("Overwrite output files"));
59
60static cl::opt<bool>
61PrintEachXForm("p", cl::desc("Print module after each transformation"));
62
63static cl::opt<bool>
Chris Lattnerddd5b412003-02-26 20:00:41 +000064NoOutput("disable-output",
Gabor Greifa99be512007-07-05 17:07:56 +000065 cl::desc("Do not write result bitcode file"), cl::Hidden);
Chris Lattnerd70b68e2003-02-12 18:43:33 +000066
67static cl::opt<bool>
Chris Lattnerddd5b412003-02-26 20:00:41 +000068NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
Chris Lattnerf3bafc12003-02-12 18:45:08 +000069
70static cl::opt<bool>
Reid Spencer74ed9972007-02-02 14:46:29 +000071VerifyEach("verify-each", cl::desc("Verify after each transform"));
72
73static cl::opt<bool>
74StripDebug("strip-debug",
75 cl::desc("Strip debugger symbol info from translation unit"));
76
77static cl::opt<bool>
78DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
79
80static cl::opt<bool>
81DisableOptimizations("disable-opt",
82 cl::desc("Do not run any optimization passes"));
83
84static cl::opt<bool>
85StandardCompileOpts("std-compile-opts",
86 cl::desc("Include the standard compile time optimizations"));
87
88static cl::opt<bool>
Devang Patel2d7551c2008-09-16 22:25:14 +000089OptLevelO1("O1",
90 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
91
92static cl::opt<bool>
93OptLevelO2("O2",
Devang Pateld9424ed2008-09-17 00:01:04 +000094 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
Devang Patel2d7551c2008-09-16 22:25:14 +000095
96static cl::opt<bool>
97OptLevelO3("O3",
Devang Pateld9424ed2008-09-17 00:01:04 +000098 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
Devang Patel2d7551c2008-09-16 22:25:14 +000099
100static cl::opt<bool>
101UnitAtATime("funit-at-a-time",
Devang Patel442b1aa2008-09-17 16:01:39 +0000102 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"));
Devang Patel2d7551c2008-09-16 22:25:14 +0000103
104static cl::opt<bool>
105DisableSimplifyLibCalls("disable-simplify-libcalls",
Devang Patel442b1aa2008-09-17 16:01:39 +0000106 cl::desc("Disable simplify-libcalls"));
Devang Patel2d7551c2008-09-16 22:25:14 +0000107
108static cl::opt<bool>
Chris Lattner3153e4f2004-05-27 20:32:10 +0000109Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
Chris Lattner5ff62e92002-07-22 02:10:13 +0000110
Reid Spencerec7eb452004-05-27 16:28:54 +0000111static cl::alias
112QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
113
Reid Spencerfd90dd52006-08-18 06:34:30 +0000114static cl::opt<bool>
115AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
116
Reid Spencerfd90dd52006-08-18 06:34:30 +0000117// ---------- Define Printers for module and function passes ------------
118namespace {
119
Devang Patel28552da2007-06-28 23:09:25 +0000120struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
121 static char ID;
122 const PassInfo *PassToPrint;
123 CallGraphSCCPassPrinter(const PassInfo *PI) :
124 CallGraphSCCPass((intptr_t)&ID), PassToPrint(PI) {}
125
126 virtual bool runOnSCC(const std::vector<CallGraphNode *>&SCC) {
127 if (!Quiet) {
128 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
129
130 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
131 Function *F = SCC[i]->getFunction();
132 if (F)
133 getAnalysisID<Pass>(PassToPrint).print(cout, F->getParent());
134 }
135 }
136 // Get and print pass...
137 return false;
138 }
139
140 virtual const char *getPassName() const { return "'Pass' Printer"; }
141
142 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
143 AU.addRequiredID(PassToPrint);
144 AU.setPreservesAll();
145 }
146};
147
148char CallGraphSCCPassPrinter::ID = 0;
149
Reid Spencerfd90dd52006-08-18 06:34:30 +0000150struct ModulePassPrinter : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +0000151 static char ID;
Reid Spencerfd90dd52006-08-18 06:34:30 +0000152 const PassInfo *PassToPrint;
Devang Patel794fd752007-05-01 21:15:47 +0000153 ModulePassPrinter(const PassInfo *PI) : ModulePass((intptr_t)&ID),
154 PassToPrint(PI) {}
Reid Spencerfd90dd52006-08-18 06:34:30 +0000155
156 virtual bool runOnModule(Module &M) {
157 if (!Quiet) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000158 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
159 getAnalysisID<Pass>(PassToPrint).print(cout, &M);
Reid Spencerfd90dd52006-08-18 06:34:30 +0000160 }
161
162 // Get and print pass...
163 return false;
164 }
165
166 virtual const char *getPassName() const { return "'Pass' Printer"; }
167
168 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
169 AU.addRequiredID(PassToPrint);
170 AU.setPreservesAll();
171 }
172};
173
Devang Patel19974732007-05-03 01:11:54 +0000174char ModulePassPrinter::ID = 0;
Reid Spencerfd90dd52006-08-18 06:34:30 +0000175struct FunctionPassPrinter : public FunctionPass {
176 const PassInfo *PassToPrint;
Devang Patel19974732007-05-03 01:11:54 +0000177 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +0000178 FunctionPassPrinter(const PassInfo *PI) : FunctionPass((intptr_t)&ID),
179 PassToPrint(PI) {}
Reid Spencerfd90dd52006-08-18 06:34:30 +0000180
181 virtual bool runOnFunction(Function &F) {
Devang Patel794fd752007-05-01 21:15:47 +0000182 if (!Quiet) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000183 cout << "Printing analysis '" << PassToPrint->getPassName()
184 << "' for function '" << F.getName() << "':\n";
Reid Spencerfd90dd52006-08-18 06:34:30 +0000185 }
186 // Get and print pass...
Bill Wendlinge8156192006-12-07 01:30:32 +0000187 getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent());
Reid Spencerfd90dd52006-08-18 06:34:30 +0000188 return false;
189 }
190
191 virtual const char *getPassName() const { return "FunctionPass Printer"; }
192
193 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
194 AU.addRequiredID(PassToPrint);
195 AU.setPreservesAll();
196 }
197};
198
Devang Patel19974732007-05-03 01:11:54 +0000199char FunctionPassPrinter::ID = 0;
Devang Patel56fb1642007-07-05 15:32:03 +0000200
201struct LoopPassPrinter : public LoopPass {
202 static char ID;
203 const PassInfo *PassToPrint;
204 LoopPassPrinter(const PassInfo *PI) :
205 LoopPass((intptr_t)&ID), PassToPrint(PI) {}
206
207 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
208 if (!Quiet) {
209 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
210 getAnalysisID<Pass>(PassToPrint).print(cout,
211 L->getHeader()->getParent()->getParent());
212 }
213 // Get and print pass...
214 return false;
215 }
216
217 virtual const char *getPassName() const { return "'Pass' Printer"; }
218
219 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
220 AU.addRequiredID(PassToPrint);
221 AU.setPreservesAll();
222 }
223};
224
225char LoopPassPrinter::ID = 0;
226
Reid Spencerfd90dd52006-08-18 06:34:30 +0000227struct BasicBlockPassPrinter : public BasicBlockPass {
228 const PassInfo *PassToPrint;
Devang Patel19974732007-05-03 01:11:54 +0000229 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +0000230 BasicBlockPassPrinter(const PassInfo *PI)
231 : BasicBlockPass((intptr_t)&ID), PassToPrint(PI) {}
Reid Spencerfd90dd52006-08-18 06:34:30 +0000232
233 virtual bool runOnBasicBlock(BasicBlock &BB) {
234 if (!Quiet) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000235 cout << "Printing Analysis info for BasicBlock '" << BB.getName()
236 << "': Pass " << PassToPrint->getPassName() << ":\n";
Reid Spencerfd90dd52006-08-18 06:34:30 +0000237 }
238
239 // Get and print pass...
Bill Wendlinge8156192006-12-07 01:30:32 +0000240 getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
Reid Spencerfd90dd52006-08-18 06:34:30 +0000241 return false;
242 }
243
244 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
245
246 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
247 AU.addRequiredID(PassToPrint);
248 AU.setPreservesAll();
249 }
250};
251
Devang Patel19974732007-05-03 01:11:54 +0000252char BasicBlockPassPrinter::ID = 0;
Reid Spencer74ed9972007-02-02 14:46:29 +0000253inline void addPass(PassManager &PM, Pass *P) {
254 // Add the pass to the pass manager...
255 PM.add(P);
256
257 // If we are verifying all of the intermediate steps, add the verifier...
258 if (VerifyEach) PM.add(createVerifierPass());
259}
260
Devang Patel2d7551c2008-09-16 22:25:14 +0000261/// AddOptimizationPasses - This routine adds optimization passes
262/// based on selected optimization level, OptLevel. This routine
263/// duplicates llvm-gcc behaviour.
264///
265/// OptLevel - Optimization Level
Devang Patel2d7551c2008-09-16 22:25:14 +0000266 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
267 unsigned OptLevel) {
268
269 if (OptLevel == 0)
270 return;
271
272 FPM.add(createCFGSimplificationPass());
273 if (OptLevel == 1)
274 FPM.add(createPromoteMemoryToRegisterPass());
275 else
276 FPM.add(createScalarReplAggregatesPass());
277 FPM.add(createInstructionCombiningPass());
278
279 if (UnitAtATime)
280 MPM.add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
281 MPM.add(createCFGSimplificationPass()); // Clean up disgusting code
282 MPM.add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
283 if (UnitAtATime) {
284 MPM.add(createGlobalOptimizerPass()); // OptLevel out global vars
285 MPM.add(createGlobalDCEPass()); // Remove unused fns and globs
286 MPM.add(createIPConstantPropagationPass()); // IP Constant Propagation
287 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
288 }
289 MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
290 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
291 if (UnitAtATime)
292 MPM.add(createPruneEHPass()); // Remove dead EH info
293 if (OptLevel > 1)
294 MPM.add(createFunctionInliningPass()); // Inline small functions
295 if (OptLevel > 2)
296 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
297 if (!DisableSimplifyLibCalls)
298 MPM.add(createSimplifyLibCallsPass()); // Library Call Optimizations
299 MPM.add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
300 MPM.add(createJumpThreadingPass()); // Thread jumps.
301 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
302 MPM.add(createScalarReplAggregatesPass()); // Break up aggregate allocas
303 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
304 MPM.add(createCondPropagationPass()); // Propagate conditionals
305 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
306 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
307 MPM.add(createReassociatePass()); // Reassociate expressions
308 MPM.add(createLoopRotatePass()); // Rotate Loop
309 MPM.add(createLICMPass()); // Hoist loop invariants
310 MPM.add(createLoopUnswitchPass());
311 MPM.add(createLoopIndexSplitPass()); // Split loop index
312 MPM.add(createInstructionCombiningPass());
313 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
314 MPM.add(createLoopDeletionPass()); // Delete dead loops
315 if (OptLevel > 1)
316 MPM.add(createLoopUnrollPass()); // Unroll small loops
317 MPM.add(createInstructionCombiningPass()); // Clean up after the unroller
318 MPM.add(createGVNPass()); // Remove redundancies
319 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
320 MPM.add(createSCCPPass()); // Constant prop with SCCP
321
322 // Run instcombine after redundancy elimination to exploit opportunities
323 // opened up by them.
324 MPM.add(createInstructionCombiningPass());
325 MPM.add(createCondPropagationPass()); // Propagate conditionals
326 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
327 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
328 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
329
330 if (UnitAtATime) {
331 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
332 MPM.add(createDeadTypeEliminationPass()); // Eliminate dead types
333 }
334
335 if (OptLevel > 1 && UnitAtATime)
336 MPM.add(createConstantMergePass()); // Merge dup global constants
337
338 return;
339}
340
Reid Spencer74ed9972007-02-02 14:46:29 +0000341void AddStandardCompilePasses(PassManager &PM) {
342 PM.add(createVerifierPass()); // Verify that input is correct
343
344 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
Reid Spencer74ed9972007-02-02 14:46:29 +0000345
346 // If the -strip-debug command line option was specified, do it.
347 if (StripDebug)
348 addPass(PM, createStripSymbolsPass(true));
349
350 if (DisableOptimizations) return;
351
352 addPass(PM, createRaiseAllocationsPass()); // call %malloc -> malloc inst
353 addPass(PM, createCFGSimplificationPass()); // Clean up disgusting code
354 addPass(PM, createPromoteMemoryToRegisterPass());// Kill useless allocas
355 addPass(PM, createGlobalOptimizerPass()); // Optimize out global vars
356 addPass(PM, createGlobalDCEPass()); // Remove unused fns and globs
357 addPass(PM, createIPConstantPropagationPass());// IP Constant Propagation
358 addPass(PM, createDeadArgEliminationPass()); // Dead argument elimination
359 addPass(PM, createInstructionCombiningPass()); // Clean up after IPCP & DAE
360 addPass(PM, createCFGSimplificationPass()); // Clean up after IPCP & DAE
361
362 addPass(PM, createPruneEHPass()); // Remove dead EH info
363
364 if (!DisableInline)
365 addPass(PM, createFunctionInliningPass()); // Inline small functions
366 addPass(PM, createArgumentPromotionPass()); // Scalarize uninlined fn args
367
Chris Lattner866b9e12008-05-02 22:05:06 +0000368 addPass(PM, createSimplifyLibCallsPass()); // Library Call Optimizations
Reid Spencer74ed9972007-02-02 14:46:29 +0000369 addPass(PM, createInstructionCombiningPass()); // Cleanup for scalarrepl.
Chris Lattner2510c3b2008-04-21 04:22:09 +0000370 addPass(PM, createJumpThreadingPass()); // Thread jumps.
Reid Spencer74ed9972007-02-02 14:46:29 +0000371 addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
Evan Cheng74b1e142007-07-17 20:07:21 +0000372 addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
Reid Spencer74ed9972007-02-02 14:46:29 +0000373 addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
374 addPass(PM, createCondPropagationPass()); // Propagate conditionals
375
376 addPass(PM, createTailCallEliminationPass()); // Eliminate tail calls
377 addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
378 addPass(PM, createReassociatePass()); // Reassociate expressions
Devang Patel0aa37f42007-04-10 15:43:36 +0000379 addPass(PM, createLoopRotatePass());
Reid Spencer74ed9972007-02-02 14:46:29 +0000380 addPass(PM, createLICMPass()); // Hoist loop invariants
381 addPass(PM, createLoopUnswitchPass()); // Unswitch loops.
Devang Patel305743d2007-09-04 20:46:58 +0000382 addPass(PM, createLoopIndexSplitPass()); // Index split loops.
Devang Patel8ffe2e22008-05-14 18:04:30 +0000383 // FIXME : Removing instcombine causes nestedloop regression.
Duncan Sands0e3b7b22008-09-12 08:23:37 +0000384 addPass(PM, createInstructionCombiningPass());
Reid Spencer74ed9972007-02-02 14:46:29 +0000385 addPass(PM, createIndVarSimplifyPass()); // Canonicalize indvars
Owen Anderson4982bab2008-05-10 07:10:24 +0000386 addPass(PM, createLoopDeletionPass()); // Delete dead loops
Reid Spencer74ed9972007-02-02 14:46:29 +0000387 addPass(PM, createLoopUnrollPass()); // Unroll small loops
388 addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
Owen Andersond06eb2c2007-09-08 22:23:52 +0000389 addPass(PM, createGVNPass()); // Remove redundancies
Evan Cheng5d4ed3b2008-04-10 01:33:05 +0000390 addPass(PM, createMemCpyOptPass()); // Remove memcpy / form memset
Reid Spencer74ed9972007-02-02 14:46:29 +0000391 addPass(PM, createSCCPPass()); // Constant prop with SCCP
392
393 // Run instcombine after redundancy elimination to exploit opportunities
394 // opened up by them.
395 addPass(PM, createInstructionCombiningPass());
396 addPass(PM, createCondPropagationPass()); // Propagate conditionals
397
Owen Andersonf6a05f92007-08-01 06:36:51 +0000398 addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
Owen Andersonc5b27102008-05-29 08:48:21 +0000399 addPass(PM, createAggressiveDCEPass()); // Delete dead instructions
Reid Spencer74ed9972007-02-02 14:46:29 +0000400 addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
Duncan Sandsfa191e42008-04-17 12:03:38 +0000401 addPass(PM, createStripDeadPrototypesPass()); // Get rid of dead prototypes
Reid Spencer74ed9972007-02-02 14:46:29 +0000402 addPass(PM, createDeadTypeEliminationPass()); // Eliminate dead types
403 addPass(PM, createConstantMergePass()); // Merge dup global constants
404}
405
Reid Spencerfd90dd52006-08-18 06:34:30 +0000406} // anonymous namespace
407
Chris Lattner0be41012002-02-01 04:54:11 +0000408
Chris Lattnerc0ce68b2002-07-23 18:12:22 +0000409//===----------------------------------------------------------------------===//
410// main for opt
411//
Chris Lattner00950542001-06-06 20:29:01 +0000412int main(int argc, char **argv) {
Chris Lattnerc30598b2006-12-06 01:18:01 +0000413 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000414 try {
415 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000416 "llvm .bc -> .bc modular optimizer and analysis printer\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000417 sys::PrintStackTraceOnErrorSignal();
Chris Lattnerfb1b3f12002-01-31 00:47:12 +0000418
Devang Patelff5d06d2008-08-27 20:51:49 +0000419 // Allocate a full target machine description only if necessary.
420 // FIXME: The choice of target should be controllable on the command line.
421 std::auto_ptr<TargetMachine> target;
422
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000423 std::string ErrorMessage;
Vikram S. Adve18fdfc42002-09-16 16:09:43 +0000424
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000425 // Load the input module...
Chris Lattnerb330e382007-05-06 02:42:03 +0000426 std::auto_ptr<Module> M;
Chris Lattner065344d2007-05-06 23:45:49 +0000427 if (MemoryBuffer *Buffer
428 = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
Chris Lattner744879e2007-05-06 09:32:02 +0000429 M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
Chris Lattner065344d2007-05-06 23:45:49 +0000430 delete Buffer;
431 }
Chris Lattner744879e2007-05-06 09:32:02 +0000432
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000433 if (M.get() == 0) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000434 cerr << argv[0] << ": ";
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000435 if (ErrorMessage.size())
Bill Wendlinge8156192006-12-07 01:30:32 +0000436 cerr << ErrorMessage << "\n";
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000437 else
Gabor Greifa99be512007-07-05 17:07:56 +0000438 cerr << "bitcode didn't read correctly.\n";
Chris Lattner00950542001-06-06 20:29:01 +0000439 return 1;
440 }
Chris Lattner76d12292002-04-18 19:55:25 +0000441
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000442 // Figure out what stream we are supposed to write to...
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000443 // FIXME: cout is not binary!
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000444 std::ostream *Out = &std::cout; // Default to printing to stdout...
445 if (OutputFilename != "-") {
446 if (!Force && std::ifstream(OutputFilename.c_str())) {
447 // If force is not specified, make sure not to overwrite a file!
Bill Wendlinge8156192006-12-07 01:30:32 +0000448 cerr << argv[0] << ": error opening '" << OutputFilename
449 << "': file exists!\n"
450 << "Use -f command line argument to force output\n";
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000451 return 1;
452 }
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000453 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
454 std::ios::binary;
455 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
Chris Lattner00950542001-06-06 20:29:01 +0000456
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000457 if (!Out->good()) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000458 cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000459 return 1;
460 }
Chris Lattner76351aa2004-04-02 05:06:57 +0000461
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000462 // Make sure that the Output file gets unlinked from the disk if we get a
463 // SIGINT
464 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
465 }
Chris Lattner00950542001-06-06 20:29:01 +0000466
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000467 // If the output is set to be emitted to standard out, and standard out is a
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000468 // console, print out a warning message and refuse to do it. We don't
469 // impress anyone by spewing tons of binary goo to a terminal.
Gabor Greifa99be512007-07-05 17:07:56 +0000470 if (!Force && !NoOutput && CheckBitcodeOutputToConsole(Out,!Quiet)) {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000471 NoOutput = true;
472 }
Chris Lattner9c3b55e2003-04-24 19:13:02 +0000473
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000474 // Create a PassManager to hold and optimize the collection of passes we are
475 // about to build...
476 //
477 PassManager Passes;
478
479 // Add an appropriate TargetData instance for this module...
Chris Lattner831b1212006-06-16 18:23:49 +0000480 Passes.add(new TargetData(M.get()));
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000481
Devang Patel2d7551c2008-09-16 22:25:14 +0000482 FunctionPassManager *FPasses = NULL;
483 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
484 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
485 FPasses->add(new TargetData(M.get()));
486 }
487
Chris Lattner3dda08a2008-07-13 19:35:21 +0000488 // If the -strip-debug command line option was specified, add it. If
489 // -std-compile-opts was also specified, it will handle StripDebug.
490 if (StripDebug && !StandardCompileOpts)
Reid Spencer74ed9972007-02-02 14:46:29 +0000491 addPass(Passes, createStripSymbolsPass(true));
492
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000493 // Create a new optimization pass for each one specified on the command line
Chris Lattner7f500f72006-08-27 22:07:01 +0000494 for (unsigned i = 0; i < PassList.size(); ++i) {
Duncan Sands56eb1332008-07-13 20:14:38 +0000495 // Check to see if -std-compile-opts was specified before this option. If
Chris Lattner3dda08a2008-07-13 19:35:21 +0000496 // so, handle it.
497 if (StandardCompileOpts &&
498 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
499 AddStandardCompilePasses(Passes);
500 StandardCompileOpts = false;
501 }
502
Devang Patel2d7551c2008-09-16 22:25:14 +0000503 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
504 AddOptimizationPasses(Passes, *FPasses, 1);
505 OptLevelO1 = false;
506 }
507
508 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
509 AddOptimizationPasses(Passes, *FPasses, 2);
510 OptLevelO2 = false;
511 }
512
513 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
514 AddOptimizationPasses(Passes, *FPasses, 3);
515 OptLevelO3 = false;
516 }
517
Chris Lattner7f500f72006-08-27 22:07:01 +0000518 const PassInfo *PassInf = PassList[i];
519 Pass *P = 0;
520 if (PassInf->getNormalCtor())
521 P = PassInf->getNormalCtor()();
Chris Lattnercd950a52006-12-01 21:59:37 +0000522 else
Bill Wendlinge8156192006-12-07 01:30:32 +0000523 cerr << argv[0] << ": cannot create pass: "
524 << PassInf->getPassName() << "\n";
Chris Lattner7f500f72006-08-27 22:07:01 +0000525 if (P) {
Reid Spencer74ed9972007-02-02 14:46:29 +0000526 addPass(Passes, P);
Chris Lattner7f500f72006-08-27 22:07:01 +0000527
528 if (AnalyzeOnly) {
Reid Spencer3ed469c2006-11-02 20:25:50 +0000529 if (dynamic_cast<BasicBlockPass*>(P))
Chris Lattner7f500f72006-08-27 22:07:01 +0000530 Passes.add(new BasicBlockPassPrinter(PassInf));
Devang Patel56fb1642007-07-05 15:32:03 +0000531 else if (dynamic_cast<LoopPass*>(P))
532 Passes.add(new LoopPassPrinter(PassInf));
Reid Spencer3ed469c2006-11-02 20:25:50 +0000533 else if (dynamic_cast<FunctionPass*>(P))
Chris Lattner7f500f72006-08-27 22:07:01 +0000534 Passes.add(new FunctionPassPrinter(PassInf));
Devang Patel28552da2007-06-28 23:09:25 +0000535 else if (dynamic_cast<CallGraphSCCPass*>(P))
536 Passes.add(new CallGraphSCCPassPrinter(PassInf));
Chris Lattner7f500f72006-08-27 22:07:01 +0000537 else
538 Passes.add(new ModulePassPrinter(PassInf));
539 }
540 }
541
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000542 if (PrintEachXForm)
Bill Wendlinge8156192006-12-07 01:30:32 +0000543 Passes.add(new PrintModulePass(&cerr));
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000544 }
Chris Lattner3dda08a2008-07-13 19:35:21 +0000545
546 // If -std-compile-opts was specified at the end of the pass list, add them.
547 if (StandardCompileOpts) {
548 AddStandardCompilePasses(Passes);
549 StandardCompileOpts = false;
550 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000551
Devang Patel2d7551c2008-09-16 22:25:14 +0000552 if (OptLevelO1) {
553 AddOptimizationPasses(Passes, *FPasses, 1);
554 }
555
556 if (OptLevelO2) {
557 AddOptimizationPasses(Passes, *FPasses, 2);
558 }
559
560 if (OptLevelO3) {
561 AddOptimizationPasses(Passes, *FPasses, 3);
562 }
563
564 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
565 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
566 I != E; ++I)
567 FPasses->run(*I);
568 }
569
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000570 // Check that the module is well formed on completion of optimization
Reid Spencer74ed9972007-02-02 14:46:29 +0000571 if (!NoVerify && !VerifyEach)
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000572 Passes.add(createVerifierPass());
573
Gabor Greifa99be512007-07-05 17:07:56 +0000574 // Write bitcode out to disk or cout as the last step...
Chris Lattner744879e2007-05-06 09:32:02 +0000575 if (!NoOutput && !AnalyzeOnly)
576 Passes.add(CreateBitcodeWriterPass(*Out));
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000577
578 // Now that we have all of the passes ready, run them.
579 Passes.run(*M.get());
580
Chris Lattnerd44ae902007-05-06 19:17:23 +0000581 // Delete the ofstream.
582 if (Out != &std::cout)
583 delete Out;
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000584 return 0;
Reid Spencerfd90dd52006-08-18 06:34:30 +0000585
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000586 } catch (const std::string& msg) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000587 cerr << argv[0] << ": " << msg << "\n";
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000588 } catch (...) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000589 cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
Chris Lattnerfb1b3f12002-01-31 00:47:12 +0000590 }
Chris Lattner03315242007-01-31 04:45:28 +0000591 llvm_shutdown();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000592 return 1;
Chris Lattner00950542001-06-06 20:29:01 +0000593}