9e76451229664848b892efa47320bf0a7d55f0ce
[oota-llvm.git] / tools / opt / opt.cpp
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Analysis/CallGraph.h"
19 #include "llvm/Analysis/CallGraphSCCPass.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/RegionPass.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/CodeGen/CommandFlags.h"
25 #include "llvm/DebugInfo.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/PrintModulePass.h"
29 #include "llvm/IRReader/IRReader.h"
30 #include "llvm/LinkAllIR.h"
31 #include "llvm/LinkAllPasses.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/PassManager.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/PassNameParser.h"
37 #include "llvm/Support/PluginLoader.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/SystemUtils.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/ToolOutputFile.h"
45 #include "llvm/Target/TargetLibraryInfo.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48 #include <algorithm>
49 #include <memory>
50 using namespace llvm;
51
52 // The OptimizationList is automatically populated with registered Passes by the
53 // PassNameParser.
54 //
55 static cl::list<const PassInfo*, bool, PassNameParser>
56 PassList(cl::desc("Optimizations available:"));
57
58 // Other command line options...
59 //
60 static cl::opt<std::string>
61 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
62     cl::init("-"), cl::value_desc("filename"));
63
64 static cl::opt<std::string>
65 OutputFilename("o", cl::desc("Override output filename"),
66                cl::value_desc("filename"));
67
68 static cl::opt<bool>
69 Force("f", cl::desc("Enable binary output on terminals"));
70
71 static cl::opt<bool>
72 PrintEachXForm("p", cl::desc("Print module after each transformation"));
73
74 static cl::opt<bool>
75 NoOutput("disable-output",
76          cl::desc("Do not write result bitcode file"), cl::Hidden);
77
78 static cl::opt<bool>
79 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
80
81 static cl::opt<bool>
82 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
83
84 static cl::opt<bool>
85 VerifyEach("verify-each", cl::desc("Verify after each transform"));
86
87 static cl::opt<bool>
88 StripDebug("strip-debug",
89            cl::desc("Strip debugger symbol info from translation unit"));
90
91 static cl::opt<bool>
92 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
93
94 static cl::opt<bool>
95 DisableOptimizations("disable-opt",
96                      cl::desc("Do not run any optimization passes"));
97
98 static cl::opt<bool>
99 DisableInternalize("disable-internalize",
100                    cl::desc("Do not mark all symbols as internal"));
101
102 static cl::opt<bool>
103 StandardCompileOpts("std-compile-opts",
104                    cl::desc("Include the standard compile time optimizations"));
105
106 static cl::opt<bool>
107 StandardLinkOpts("std-link-opts",
108                  cl::desc("Include the standard link time optimizations"));
109
110 static cl::opt<bool>
111 OptLevelO1("O1",
112            cl::desc("Optimization level 1. Similar to clang -O1"));
113
114 static cl::opt<bool>
115 OptLevelO2("O2",
116            cl::desc("Optimization level 2. Similar to clang -O2"));
117
118 static cl::opt<bool>
119 OptLevelOs("Os",
120            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
121
122 static cl::opt<bool>
123 OptLevelOz("Oz",
124            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
125
126 static cl::opt<bool>
127 OptLevelO3("O3",
128            cl::desc("Optimization level 3. Similar to clang -O3"));
129
130 static cl::opt<std::string>
131 TargetTriple("mtriple", cl::desc("Override target triple for module"));
132
133 static cl::opt<bool>
134 UnitAtATime("funit-at-a-time",
135             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
136             cl::init(true));
137
138 static cl::opt<bool>
139 DisableLoopUnrolling("disable-loop-unrolling",
140                      cl::desc("Disable loop unrolling in all relevant passes"),
141                      cl::init(false));
142 static cl::opt<bool>
143 DisableLoopVectorization("disable-loop-vectorization",
144                      cl::desc("Disable the loop vectorization pass"),
145                      cl::init(false));
146
147 static cl::opt<bool>
148 DisableSLPVectorization("disable-slp-vectorization",
149                         cl::desc("Disable the slp vectorization pass"),
150                         cl::init(false));
151
152
153 static cl::opt<bool>
154 DisableSimplifyLibCalls("disable-simplify-libcalls",
155                         cl::desc("Disable simplify-libcalls"));
156
157 static cl::opt<bool>
158 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
159
160 static cl::alias
161 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
162
163 static cl::opt<bool>
164 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
165
166 static cl::opt<bool>
167 PrintBreakpoints("print-breakpoints-for-testing",
168                  cl::desc("Print select breakpoints location for testing"));
169
170 static cl::opt<std::string>
171 DefaultDataLayout("default-data-layout",
172           cl::desc("data layout string to use if not specified by module"),
173           cl::value_desc("layout-string"), cl::init(""));
174
175 // ---------- Define Printers for module and function passes ------------
176 namespace {
177
178 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
179   static char ID;
180   const PassInfo *PassToPrint;
181   raw_ostream &Out;
182   std::string PassName;
183
184   CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
185     CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
186       std::string PassToPrintName =  PassToPrint->getPassName();
187       PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
188     }
189
190   virtual bool runOnSCC(CallGraphSCC &SCC) {
191     if (!Quiet)
192       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
193
194     // Get and print pass...
195     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
196       Function *F = (*I)->getFunction();
197       if (F)
198         getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
199                                                               F->getParent());
200     }
201     return false;
202   }
203
204   virtual const char *getPassName() const { return PassName.c_str(); }
205
206   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
207     AU.addRequiredID(PassToPrint->getTypeInfo());
208     AU.setPreservesAll();
209   }
210 };
211
212 char CallGraphSCCPassPrinter::ID = 0;
213
214 struct ModulePassPrinter : public ModulePass {
215   static char ID;
216   const PassInfo *PassToPrint;
217   raw_ostream &Out;
218   std::string PassName;
219
220   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
221     : ModulePass(ID), PassToPrint(PI), Out(out) {
222       std::string PassToPrintName =  PassToPrint->getPassName();
223       PassName = "ModulePass Printer: " + PassToPrintName;
224     }
225
226   virtual bool runOnModule(Module &M) {
227     if (!Quiet)
228       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
229
230     // Get and print pass...
231     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
232     return false;
233   }
234
235   virtual const char *getPassName() const { return PassName.c_str(); }
236
237   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
238     AU.addRequiredID(PassToPrint->getTypeInfo());
239     AU.setPreservesAll();
240   }
241 };
242
243 char ModulePassPrinter::ID = 0;
244 struct FunctionPassPrinter : public FunctionPass {
245   const PassInfo *PassToPrint;
246   raw_ostream &Out;
247   static char ID;
248   std::string PassName;
249
250   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
251     : FunctionPass(ID), PassToPrint(PI), Out(out) {
252       std::string PassToPrintName =  PassToPrint->getPassName();
253       PassName = "FunctionPass Printer: " + PassToPrintName;
254     }
255
256   virtual bool runOnFunction(Function &F) {
257     if (!Quiet)
258       Out << "Printing analysis '" << PassToPrint->getPassName()
259           << "' for function '" << F.getName() << "':\n";
260
261     // Get and print pass...
262     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
263             F.getParent());
264     return false;
265   }
266
267   virtual const char *getPassName() const { return PassName.c_str(); }
268
269   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
270     AU.addRequiredID(PassToPrint->getTypeInfo());
271     AU.setPreservesAll();
272   }
273 };
274
275 char FunctionPassPrinter::ID = 0;
276
277 struct LoopPassPrinter : public LoopPass {
278   static char ID;
279   const PassInfo *PassToPrint;
280   raw_ostream &Out;
281   std::string PassName;
282
283   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
284     LoopPass(ID), PassToPrint(PI), Out(out) {
285       std::string PassToPrintName =  PassToPrint->getPassName();
286       PassName = "LoopPass Printer: " + PassToPrintName;
287     }
288
289
290   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
291     if (!Quiet)
292       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
293
294     // Get and print pass...
295     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
296                         L->getHeader()->getParent()->getParent());
297     return false;
298   }
299
300   virtual const char *getPassName() const { return PassName.c_str(); }
301
302   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
303     AU.addRequiredID(PassToPrint->getTypeInfo());
304     AU.setPreservesAll();
305   }
306 };
307
308 char LoopPassPrinter::ID = 0;
309
310 struct RegionPassPrinter : public RegionPass {
311   static char ID;
312   const PassInfo *PassToPrint;
313   raw_ostream &Out;
314   std::string PassName;
315
316   RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
317     PassToPrint(PI), Out(out) {
318     std::string PassToPrintName =  PassToPrint->getPassName();
319     PassName = "RegionPass Printer: " + PassToPrintName;
320   }
321
322   virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
323     if (!Quiet) {
324       Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
325           << "region: '" << R->getNameStr() << "' in function '"
326           << R->getEntry()->getParent()->getName() << "':\n";
327     }
328     // Get and print pass...
329    getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
330                        R->getEntry()->getParent()->getParent());
331     return false;
332   }
333
334   virtual const char *getPassName() const { return PassName.c_str(); }
335
336   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
337     AU.addRequiredID(PassToPrint->getTypeInfo());
338     AU.setPreservesAll();
339   }
340 };
341
342 char RegionPassPrinter::ID = 0;
343
344 struct BasicBlockPassPrinter : public BasicBlockPass {
345   const PassInfo *PassToPrint;
346   raw_ostream &Out;
347   static char ID;
348   std::string PassName;
349
350   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
351     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
352       std::string PassToPrintName =  PassToPrint->getPassName();
353       PassName = "BasicBlockPass Printer: " + PassToPrintName;
354     }
355
356   virtual bool runOnBasicBlock(BasicBlock &BB) {
357     if (!Quiet)
358       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
359           << "': Pass " << PassToPrint->getPassName() << ":\n";
360
361     // Get and print pass...
362     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
363             BB.getParent()->getParent());
364     return false;
365   }
366
367   virtual const char *getPassName() const { return PassName.c_str(); }
368
369   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
370     AU.addRequiredID(PassToPrint->getTypeInfo());
371     AU.setPreservesAll();
372   }
373 };
374
375 char BasicBlockPassPrinter::ID = 0;
376
377 struct BreakpointPrinter : public ModulePass {
378   raw_ostream &Out;
379   static char ID;
380   DITypeIdentifierMap TypeIdentifierMap;
381
382   BreakpointPrinter(raw_ostream &out)
383     : ModulePass(ID), Out(out) {
384     }
385
386   void getContextName(DIDescriptor Context, std::string &N) {
387     if (Context.isNameSpace()) {
388       DINameSpace NS(Context);
389       if (!NS.getName().empty()) {
390         getContextName(NS.getContext(), N);
391         N = N + NS.getName().str() + "::";
392       }
393     } else if (Context.isType()) {
394       DIType TY(Context);
395       if (!TY.getName().empty()) {
396         getContextName(TY.getContext().resolve(TypeIdentifierMap), N);
397         N = N + TY.getName().str() + "::";
398       }
399     }
400   }
401
402   virtual bool runOnModule(Module &M) {
403     TypeIdentifierMap.clear();
404     NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
405     if (CU_Nodes)
406       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
407
408     StringSet<> Processed;
409     if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
410       for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
411         std::string Name;
412         DISubprogram SP(NMD->getOperand(i));
413         assert((!SP || SP.isSubprogram()) &&
414           "A MDNode in llvm.dbg.sp should be null or a DISubprogram.");
415         if (!SP)
416           continue;
417         getContextName(SP.getContext().resolve(TypeIdentifierMap), Name);
418         Name = Name + SP.getDisplayName().str();
419         if (!Name.empty() && Processed.insert(Name)) {
420           Out << Name << "\n";
421         }
422       }
423     return false;
424   }
425
426   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
427     AU.setPreservesAll();
428   }
429 };
430
431 } // anonymous namespace
432
433 char BreakpointPrinter::ID = 0;
434
435 static inline void addPass(PassManagerBase &PM, Pass *P) {
436   // Add the pass to the pass manager...
437   PM.add(P);
438
439   // If we are verifying all of the intermediate steps, add the verifier...
440   if (VerifyEach) PM.add(createVerifierPass());
441 }
442
443 /// AddOptimizationPasses - This routine adds optimization passes
444 /// based on selected optimization level, OptLevel. This routine
445 /// duplicates llvm-gcc behaviour.
446 ///
447 /// OptLevel - Optimization Level
448 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
449                                   unsigned OptLevel, unsigned SizeLevel) {
450   FPM.add(createVerifierPass());                  // Verify that input is correct
451
452   PassManagerBuilder Builder;
453   Builder.OptLevel = OptLevel;
454   Builder.SizeLevel = SizeLevel;
455
456   if (DisableInline) {
457     // No inlining pass
458   } else if (OptLevel > 1) {
459     unsigned Threshold = 225;
460     if (SizeLevel == 1)      // -Os
461       Threshold = 75;
462     else if (SizeLevel == 2) // -Oz
463       Threshold = 25;
464     if (OptLevel > 2)
465       Threshold = 275;
466     Builder.Inliner = createFunctionInliningPass(Threshold);
467   } else {
468     Builder.Inliner = createAlwaysInlinerPass();
469   }
470   Builder.DisableUnitAtATime = !UnitAtATime;
471   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
472                                DisableLoopUnrolling : OptLevel == 0;
473
474   // This is final, unless there is a #pragma vectorize enable
475   if (DisableLoopVectorization)
476     Builder.LoopVectorize = false;
477   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
478   else if (!Builder.LoopVectorize)
479     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
480
481   // When #pragma vectorize is on for SLP, do the same as above
482   Builder.SLPVectorize =
483       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
484
485   Builder.populateFunctionPassManager(FPM);
486   Builder.populateModulePassManager(MPM);
487 }
488
489 static void AddStandardCompilePasses(PassManagerBase &PM) {
490   PM.add(createVerifierPass());                  // Verify that input is correct
491
492   // If the -strip-debug command line option was specified, do it.
493   if (StripDebug)
494     addPass(PM, createStripSymbolsPass(true));
495
496   if (DisableOptimizations) return;
497
498   // -std-compile-opts adds the same module passes as -O3.
499   PassManagerBuilder Builder;
500   if (!DisableInline)
501     Builder.Inliner = createFunctionInliningPass();
502   Builder.OptLevel = 3;
503   Builder.populateModulePassManager(PM);
504 }
505
506 static void AddStandardLinkPasses(PassManagerBase &PM) {
507   PM.add(createVerifierPass());                  // Verify that input is correct
508
509   // If the -strip-debug command line option was specified, do it.
510   if (StripDebug)
511     addPass(PM, createStripSymbolsPass(true));
512
513   if (DisableOptimizations) return;
514
515   PassManagerBuilder Builder;
516   Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
517                                  /*RunInliner=*/ !DisableInline);
518 }
519
520 //===----------------------------------------------------------------------===//
521 // CodeGen-related helper functions.
522 //
523 static TargetOptions GetTargetOptions() {
524   TargetOptions Options;
525   Options.LessPreciseFPMADOption = EnableFPMAD;
526   Options.NoFramePointerElim = DisableFPElim;
527   Options.AllowFPOpFusion = FuseFPOps;
528   Options.UnsafeFPMath = EnableUnsafeFPMath;
529   Options.NoInfsFPMath = EnableNoInfsFPMath;
530   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
531   Options.HonorSignDependentRoundingFPMathOption =
532   EnableHonorSignDependentRoundingFPMath;
533   Options.UseSoftFloat = GenerateSoftFloatCalls;
534   if (FloatABIForCalls != FloatABI::Default)
535     Options.FloatABIType = FloatABIForCalls;
536   Options.NoZerosInBSS = DontPlaceZerosInBSS;
537   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
538   Options.DisableTailCalls = DisableTailCalls;
539   Options.StackAlignmentOverride = OverrideStackAlignment;
540   Options.TrapFuncName = TrapFuncName;
541   Options.PositionIndependentExecutable = EnablePIE;
542   Options.EnableSegmentedStacks = SegmentedStacks;
543   Options.UseInitArray = UseInitArray;
544   return Options;
545 }
546
547 CodeGenOpt::Level GetCodeGenOptLevel() {
548   if (OptLevelO1)
549     return CodeGenOpt::Less;
550   if (OptLevelO2)
551     return CodeGenOpt::Default;
552   if (OptLevelO3)
553     return CodeGenOpt::Aggressive;
554   return CodeGenOpt::None;
555 }
556
557 // Returns the TargetMachine instance or zero if no triple is provided.
558 static TargetMachine* GetTargetMachine(Triple TheTriple) {
559   std::string Error;
560   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
561                                                          Error);
562   // Some modules don't specify a triple, and this is okay.
563   if (!TheTarget) {
564     return 0;
565   }
566
567   // Package up features to be passed to target/subtarget
568   std::string FeaturesStr;
569   if (MAttrs.size()) {
570     SubtargetFeatures Features;
571     for (unsigned i = 0; i != MAttrs.size(); ++i)
572       Features.AddFeature(MAttrs[i]);
573     FeaturesStr = Features.getString();
574   }
575
576   return TheTarget->createTargetMachine(TheTriple.getTriple(),
577                                         MCPU, FeaturesStr, GetTargetOptions(),
578                                         RelocModel, CMModel,
579                                         GetCodeGenOptLevel());
580 }
581
582 //===----------------------------------------------------------------------===//
583 // main for opt
584 //
585 int main(int argc, char **argv) {
586   sys::PrintStackTraceOnErrorSignal();
587   llvm::PrettyStackTraceProgram X(argc, argv);
588
589   // Enable debug stream buffering.
590   EnableDebugBuffering = true;
591
592   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
593   LLVMContext &Context = getGlobalContext();
594
595   InitializeAllTargets();
596   InitializeAllTargetMCs();
597
598   // Initialize passes
599   PassRegistry &Registry = *PassRegistry::getPassRegistry();
600   initializeCore(Registry);
601   initializeDebugIRPass(Registry);
602   initializeScalarOpts(Registry);
603   initializeObjCARCOpts(Registry);
604   initializeVectorization(Registry);
605   initializeIPO(Registry);
606   initializeAnalysis(Registry);
607   initializeIPA(Registry);
608   initializeTransformUtils(Registry);
609   initializeInstCombine(Registry);
610   initializeInstrumentation(Registry);
611   initializeTarget(Registry);
612
613   cl::ParseCommandLineOptions(argc, argv,
614     "llvm .bc -> .bc modular optimizer and analysis printer\n");
615
616   if (AnalyzeOnly && NoOutput) {
617     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
618     return 1;
619   }
620
621   SMDiagnostic Err;
622
623   // Load the input module...
624   OwningPtr<Module> M;
625   M.reset(ParseIRFile(InputFilename, Err, Context));
626
627   if (M.get() == 0) {
628     Err.print(argv[0], errs());
629     return 1;
630   }
631
632   // If we are supposed to override the target triple, do so now.
633   if (!TargetTriple.empty())
634     M->setTargetTriple(Triple::normalize(TargetTriple));
635
636   // Figure out what stream we are supposed to write to...
637   OwningPtr<tool_output_file> Out;
638   if (NoOutput) {
639     if (!OutputFilename.empty())
640       errs() << "WARNING: The -o (output filename) option is ignored when\n"
641                 "the --disable-output option is used.\n";
642   } else {
643     // Default to standard output.
644     if (OutputFilename.empty())
645       OutputFilename = "-";
646
647     std::string ErrorInfo;
648     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
649                                    sys::fs::F_Binary));
650     if (!ErrorInfo.empty()) {
651       errs() << ErrorInfo << '\n';
652       return 1;
653     }
654   }
655
656   // If the output is set to be emitted to standard out, and standard out is a
657   // console, print out a warning message and refuse to do it.  We don't
658   // impress anyone by spewing tons of binary goo to a terminal.
659   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
660     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
661       NoOutput = true;
662
663   // Create a PassManager to hold and optimize the collection of passes we are
664   // about to build.
665   //
666   PassManager Passes;
667
668   // Add an appropriate TargetLibraryInfo pass for the module's triple.
669   TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
670
671   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
672   if (DisableSimplifyLibCalls)
673     TLI->disableAllFunctions();
674   Passes.add(TLI);
675
676   // Add an appropriate DataLayout instance for this module.
677   DataLayout *TD = 0;
678   const std::string &ModuleDataLayout = M.get()->getDataLayout();
679   if (!ModuleDataLayout.empty())
680     TD = new DataLayout(ModuleDataLayout);
681   else if (!DefaultDataLayout.empty())
682     TD = new DataLayout(DefaultDataLayout);
683
684   if (TD)
685     Passes.add(TD);
686
687   Triple ModuleTriple(M->getTargetTriple());
688   TargetMachine *Machine = 0;
689   if (ModuleTriple.getArch())
690     Machine = GetTargetMachine(Triple(ModuleTriple));
691   OwningPtr<TargetMachine> TM(Machine);
692
693   // Add internal analysis passes from the target machine.
694   if (TM.get())
695     TM->addAnalysisPasses(Passes);
696
697   OwningPtr<FunctionPassManager> FPasses;
698   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
699     FPasses.reset(new FunctionPassManager(M.get()));
700     if (TD)
701       FPasses->add(new DataLayout(*TD));
702     if (TM.get())
703       TM->addAnalysisPasses(*FPasses);
704
705   }
706
707   if (PrintBreakpoints) {
708     // Default to standard output.
709     if (!Out) {
710       if (OutputFilename.empty())
711         OutputFilename = "-";
712
713       std::string ErrorInfo;
714       Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
715                                      sys::fs::F_Binary));
716       if (!ErrorInfo.empty()) {
717         errs() << ErrorInfo << '\n';
718         return 1;
719       }
720     }
721     Passes.add(new BreakpointPrinter(Out->os()));
722     NoOutput = true;
723   }
724
725   // If the -strip-debug command line option was specified, add it.  If
726   // -std-compile-opts was also specified, it will handle StripDebug.
727   if (StripDebug && !StandardCompileOpts)
728     addPass(Passes, createStripSymbolsPass(true));
729
730   // Create a new optimization pass for each one specified on the command line
731   for (unsigned i = 0; i < PassList.size(); ++i) {
732     // Check to see if -std-compile-opts was specified before this option.  If
733     // so, handle it.
734     if (StandardCompileOpts &&
735         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
736       AddStandardCompilePasses(Passes);
737       StandardCompileOpts = false;
738     }
739
740     if (StandardLinkOpts &&
741         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
742       AddStandardLinkPasses(Passes);
743       StandardLinkOpts = false;
744     }
745
746     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
747       AddOptimizationPasses(Passes, *FPasses, 1, 0);
748       OptLevelO1 = false;
749     }
750
751     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
752       AddOptimizationPasses(Passes, *FPasses, 2, 0);
753       OptLevelO2 = false;
754     }
755
756     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
757       AddOptimizationPasses(Passes, *FPasses, 2, 1);
758       OptLevelOs = false;
759     }
760
761     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
762       AddOptimizationPasses(Passes, *FPasses, 2, 2);
763       OptLevelOz = false;
764     }
765
766     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
767       AddOptimizationPasses(Passes, *FPasses, 3, 0);
768       OptLevelO3 = false;
769     }
770
771     const PassInfo *PassInf = PassList[i];
772     Pass *P = 0;
773     if (PassInf->getNormalCtor())
774       P = PassInf->getNormalCtor()();
775     else
776       errs() << argv[0] << ": cannot create pass: "
777              << PassInf->getPassName() << "\n";
778     if (P) {
779       PassKind Kind = P->getPassKind();
780       addPass(Passes, P);
781
782       if (AnalyzeOnly) {
783         switch (Kind) {
784         case PT_BasicBlock:
785           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
786           break;
787         case PT_Region:
788           Passes.add(new RegionPassPrinter(PassInf, Out->os()));
789           break;
790         case PT_Loop:
791           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
792           break;
793         case PT_Function:
794           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
795           break;
796         case PT_CallGraphSCC:
797           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
798           break;
799         default:
800           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
801           break;
802         }
803       }
804     }
805
806     if (PrintEachXForm)
807       Passes.add(createPrintModulePass(&errs()));
808   }
809
810   // If -std-compile-opts was specified at the end of the pass list, add them.
811   if (StandardCompileOpts) {
812     AddStandardCompilePasses(Passes);
813     StandardCompileOpts = false;
814   }
815
816   if (StandardLinkOpts) {
817     AddStandardLinkPasses(Passes);
818     StandardLinkOpts = false;
819   }
820
821   if (OptLevelO1)
822     AddOptimizationPasses(Passes, *FPasses, 1, 0);
823
824   if (OptLevelO2)
825     AddOptimizationPasses(Passes, *FPasses, 2, 0);
826
827   if (OptLevelOs)
828     AddOptimizationPasses(Passes, *FPasses, 2, 1);
829
830   if (OptLevelOz)
831     AddOptimizationPasses(Passes, *FPasses, 2, 2);
832
833   if (OptLevelO3)
834     AddOptimizationPasses(Passes, *FPasses, 3, 0);
835
836   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
837     FPasses->doInitialization();
838     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
839       FPasses->run(*F);
840     FPasses->doFinalization();
841   }
842
843   // Check that the module is well formed on completion of optimization
844   if (!NoVerify && !VerifyEach)
845     Passes.add(createVerifierPass());
846
847   // Write bitcode or assembly to the output as the last step...
848   if (!NoOutput && !AnalyzeOnly) {
849     if (OutputAssembly)
850       Passes.add(createPrintModulePass(&Out->os()));
851     else
852       Passes.add(createBitcodeWriterPass(Out->os()));
853   }
854
855   // Before executing passes, print the final values of the LLVM options.
856   cl::PrintOptionValues();
857
858   // Now that we have all of the passes ready, run them.
859   Passes.run(*M.get());
860
861   // Declare success.
862   if (!NoOutput || PrintBreakpoints)
863     Out->keep();
864
865   return 0;
866 }