]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - contrib/llvm/tools/opt/opt.cpp
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / contrib / llvm / 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/Assembly/PrintModulePass.h"
24 #include "llvm/Bitcode/ReaderWriter.h"
25 #include "llvm/CodeGen/CommandFlags.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Module.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   Builder.LoopVectorize =
475       DisableLoopVectorization ? false : OptLevel > 1 && SizeLevel < 2;
476   Builder.SLPVectorize =
477       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
478
479   Builder.populateFunctionPassManager(FPM);
480   Builder.populateModulePassManager(MPM);
481 }
482
483 static void AddStandardCompilePasses(PassManagerBase &PM) {
484   PM.add(createVerifierPass());                  // Verify that input is correct
485
486   // If the -strip-debug command line option was specified, do it.
487   if (StripDebug)
488     addPass(PM, createStripSymbolsPass(true));
489
490   if (DisableOptimizations) return;
491
492   // -std-compile-opts adds the same module passes as -O3.
493   PassManagerBuilder Builder;
494   if (!DisableInline)
495     Builder.Inliner = createFunctionInliningPass();
496   Builder.OptLevel = 3;
497   Builder.populateModulePassManager(PM);
498 }
499
500 static void AddStandardLinkPasses(PassManagerBase &PM) {
501   PM.add(createVerifierPass());                  // Verify that input is correct
502
503   // If the -strip-debug command line option was specified, do it.
504   if (StripDebug)
505     addPass(PM, createStripSymbolsPass(true));
506
507   if (DisableOptimizations) return;
508
509   PassManagerBuilder Builder;
510   Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
511                                  /*RunInliner=*/ !DisableInline);
512 }
513
514 //===----------------------------------------------------------------------===//
515 // CodeGen-related helper functions.
516 //
517 static TargetOptions GetTargetOptions() {
518   TargetOptions Options;
519   Options.LessPreciseFPMADOption = EnableFPMAD;
520   Options.NoFramePointerElim = DisableFPElim;
521   Options.AllowFPOpFusion = FuseFPOps;
522   Options.UnsafeFPMath = EnableUnsafeFPMath;
523   Options.NoInfsFPMath = EnableNoInfsFPMath;
524   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
525   Options.HonorSignDependentRoundingFPMathOption =
526   EnableHonorSignDependentRoundingFPMath;
527   Options.UseSoftFloat = GenerateSoftFloatCalls;
528   if (FloatABIForCalls != FloatABI::Default)
529     Options.FloatABIType = FloatABIForCalls;
530   Options.NoZerosInBSS = DontPlaceZerosInBSS;
531   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
532   Options.DisableTailCalls = DisableTailCalls;
533   Options.StackAlignmentOverride = OverrideStackAlignment;
534   Options.TrapFuncName = TrapFuncName;
535   Options.PositionIndependentExecutable = EnablePIE;
536   Options.EnableSegmentedStacks = SegmentedStacks;
537   Options.UseInitArray = UseInitArray;
538   return Options;
539 }
540
541 CodeGenOpt::Level GetCodeGenOptLevel() {
542   if (OptLevelO1)
543     return CodeGenOpt::Less;
544   if (OptLevelO2)
545     return CodeGenOpt::Default;
546   if (OptLevelO3)
547     return CodeGenOpt::Aggressive;
548   return CodeGenOpt::None;
549 }
550
551 // Returns the TargetMachine instance or zero if no triple is provided.
552 static TargetMachine* GetTargetMachine(Triple TheTriple) {
553   std::string Error;
554   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
555                                                          Error);
556   // Some modules don't specify a triple, and this is okay.
557   if (!TheTarget) {
558     return 0;
559   }
560
561   // Package up features to be passed to target/subtarget
562   std::string FeaturesStr;
563   if (MAttrs.size()) {
564     SubtargetFeatures Features;
565     for (unsigned i = 0; i != MAttrs.size(); ++i)
566       Features.AddFeature(MAttrs[i]);
567     FeaturesStr = Features.getString();
568   }
569
570   return TheTarget->createTargetMachine(TheTriple.getTriple(),
571                                         MCPU, FeaturesStr, GetTargetOptions(),
572                                         RelocModel, CMModel,
573                                         GetCodeGenOptLevel());
574 }
575
576 //===----------------------------------------------------------------------===//
577 // main for opt
578 //
579 int main(int argc, char **argv) {
580   sys::PrintStackTraceOnErrorSignal();
581   llvm::PrettyStackTraceProgram X(argc, argv);
582
583   // Enable debug stream buffering.
584   EnableDebugBuffering = true;
585
586   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
587   LLVMContext &Context = getGlobalContext();
588
589   InitializeAllTargets();
590   InitializeAllTargetMCs();
591
592   // Initialize passes
593   PassRegistry &Registry = *PassRegistry::getPassRegistry();
594   initializeCore(Registry);
595   initializeDebugIRPass(Registry);
596   initializeScalarOpts(Registry);
597   initializeObjCARCOpts(Registry);
598   initializeVectorization(Registry);
599   initializeIPO(Registry);
600   initializeAnalysis(Registry);
601   initializeIPA(Registry);
602   initializeTransformUtils(Registry);
603   initializeInstCombine(Registry);
604   initializeInstrumentation(Registry);
605   initializeTarget(Registry);
606
607   cl::ParseCommandLineOptions(argc, argv,
608     "llvm .bc -> .bc modular optimizer and analysis printer\n");
609
610   if (AnalyzeOnly && NoOutput) {
611     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
612     return 1;
613   }
614
615   SMDiagnostic Err;
616
617   // Load the input module...
618   OwningPtr<Module> M;
619   M.reset(ParseIRFile(InputFilename, Err, Context));
620
621   if (M.get() == 0) {
622     Err.print(argv[0], errs());
623     return 1;
624   }
625
626   // If we are supposed to override the target triple, do so now.
627   if (!TargetTriple.empty())
628     M->setTargetTriple(Triple::normalize(TargetTriple));
629
630   // Figure out what stream we are supposed to write to...
631   OwningPtr<tool_output_file> Out;
632   if (NoOutput) {
633     if (!OutputFilename.empty())
634       errs() << "WARNING: The -o (output filename) option is ignored when\n"
635                 "the --disable-output option is used.\n";
636   } else {
637     // Default to standard output.
638     if (OutputFilename.empty())
639       OutputFilename = "-";
640
641     std::string ErrorInfo;
642     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
643                                    sys::fs::F_Binary));
644     if (!ErrorInfo.empty()) {
645       errs() << ErrorInfo << '\n';
646       return 1;
647     }
648   }
649
650   // If the output is set to be emitted to standard out, and standard out is a
651   // console, print out a warning message and refuse to do it.  We don't
652   // impress anyone by spewing tons of binary goo to a terminal.
653   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
654     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
655       NoOutput = true;
656
657   // Create a PassManager to hold and optimize the collection of passes we are
658   // about to build.
659   //
660   PassManager Passes;
661
662   // Add an appropriate TargetLibraryInfo pass for the module's triple.
663   TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
664
665   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
666   if (DisableSimplifyLibCalls)
667     TLI->disableAllFunctions();
668   Passes.add(TLI);
669
670   // Add an appropriate DataLayout instance for this module.
671   DataLayout *TD = 0;
672   const std::string &ModuleDataLayout = M.get()->getDataLayout();
673   if (!ModuleDataLayout.empty())
674     TD = new DataLayout(ModuleDataLayout);
675   else if (!DefaultDataLayout.empty())
676     TD = new DataLayout(DefaultDataLayout);
677
678   if (TD)
679     Passes.add(TD);
680
681   Triple ModuleTriple(M->getTargetTriple());
682   TargetMachine *Machine = 0;
683   if (ModuleTriple.getArch())
684     Machine = GetTargetMachine(Triple(ModuleTriple));
685   OwningPtr<TargetMachine> TM(Machine);
686
687   // Add internal analysis passes from the target machine.
688   if (TM.get())
689     TM->addAnalysisPasses(Passes);
690
691   OwningPtr<FunctionPassManager> FPasses;
692   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
693     FPasses.reset(new FunctionPassManager(M.get()));
694     if (TD)
695       FPasses->add(new DataLayout(*TD));
696     if (TM.get())
697       TM->addAnalysisPasses(*FPasses);
698
699   }
700
701   if (PrintBreakpoints) {
702     // Default to standard output.
703     if (!Out) {
704       if (OutputFilename.empty())
705         OutputFilename = "-";
706
707       std::string ErrorInfo;
708       Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
709                                      sys::fs::F_Binary));
710       if (!ErrorInfo.empty()) {
711         errs() << ErrorInfo << '\n';
712         return 1;
713       }
714     }
715     Passes.add(new BreakpointPrinter(Out->os()));
716     NoOutput = true;
717   }
718
719   // If the -strip-debug command line option was specified, add it.  If
720   // -std-compile-opts was also specified, it will handle StripDebug.
721   if (StripDebug && !StandardCompileOpts)
722     addPass(Passes, createStripSymbolsPass(true));
723
724   // Create a new optimization pass for each one specified on the command line
725   for (unsigned i = 0; i < PassList.size(); ++i) {
726     // Check to see if -std-compile-opts was specified before this option.  If
727     // so, handle it.
728     if (StandardCompileOpts &&
729         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
730       AddStandardCompilePasses(Passes);
731       StandardCompileOpts = false;
732     }
733
734     if (StandardLinkOpts &&
735         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
736       AddStandardLinkPasses(Passes);
737       StandardLinkOpts = false;
738     }
739
740     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
741       AddOptimizationPasses(Passes, *FPasses, 1, 0);
742       OptLevelO1 = false;
743     }
744
745     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
746       AddOptimizationPasses(Passes, *FPasses, 2, 0);
747       OptLevelO2 = false;
748     }
749
750     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
751       AddOptimizationPasses(Passes, *FPasses, 2, 1);
752       OptLevelOs = false;
753     }
754
755     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
756       AddOptimizationPasses(Passes, *FPasses, 2, 2);
757       OptLevelOz = false;
758     }
759
760     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
761       AddOptimizationPasses(Passes, *FPasses, 3, 0);
762       OptLevelO3 = false;
763     }
764
765     const PassInfo *PassInf = PassList[i];
766     Pass *P = 0;
767     if (PassInf->getNormalCtor())
768       P = PassInf->getNormalCtor()();
769     else
770       errs() << argv[0] << ": cannot create pass: "
771              << PassInf->getPassName() << "\n";
772     if (P) {
773       PassKind Kind = P->getPassKind();
774       addPass(Passes, P);
775
776       if (AnalyzeOnly) {
777         switch (Kind) {
778         case PT_BasicBlock:
779           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
780           break;
781         case PT_Region:
782           Passes.add(new RegionPassPrinter(PassInf, Out->os()));
783           break;
784         case PT_Loop:
785           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
786           break;
787         case PT_Function:
788           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
789           break;
790         case PT_CallGraphSCC:
791           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
792           break;
793         default:
794           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
795           break;
796         }
797       }
798     }
799
800     if (PrintEachXForm)
801       Passes.add(createPrintModulePass(&errs()));
802   }
803
804   // If -std-compile-opts was specified at the end of the pass list, add them.
805   if (StandardCompileOpts) {
806     AddStandardCompilePasses(Passes);
807     StandardCompileOpts = false;
808   }
809
810   if (StandardLinkOpts) {
811     AddStandardLinkPasses(Passes);
812     StandardLinkOpts = false;
813   }
814
815   if (OptLevelO1)
816     AddOptimizationPasses(Passes, *FPasses, 1, 0);
817
818   if (OptLevelO2)
819     AddOptimizationPasses(Passes, *FPasses, 2, 0);
820
821   if (OptLevelOs)
822     AddOptimizationPasses(Passes, *FPasses, 2, 1);
823
824   if (OptLevelOz)
825     AddOptimizationPasses(Passes, *FPasses, 2, 2);
826
827   if (OptLevelO3)
828     AddOptimizationPasses(Passes, *FPasses, 3, 0);
829
830   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
831     FPasses->doInitialization();
832     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
833       FPasses->run(*F);
834     FPasses->doFinalization();
835   }
836
837   // Check that the module is well formed on completion of optimization
838   if (!NoVerify && !VerifyEach)
839     Passes.add(createVerifierPass());
840
841   // Write bitcode or assembly to the output as the last step...
842   if (!NoOutput && !AnalyzeOnly) {
843     if (OutputAssembly)
844       Passes.add(createPrintModulePass(&Out->os()));
845     else
846       Passes.add(createBitcodeWriterPass(Out->os()));
847   }
848
849   // Before executing passes, print the final values of the LLVM options.
850   cl::PrintOptionValues();
851
852   // Now that we have all of the passes ready, run them.
853   Passes.run(*M.get());
854
855   // Declare success.
856   if (!NoOutput || PrintBreakpoints)
857     Out->keep();
858
859   return 0;
860 }