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