make the mangler take an MCContext instead of an MAI.
[oota-llvm.git] / lib / CodeGen / LLVMTargetMachine.cpp
1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
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 // This file implements the LLVMTargetMachine class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/PassManager.h"
16 #include "llvm/Pass.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/FormattedStream.h"
34 using namespace llvm;
35
36 namespace llvm {
37   bool EnableFastISel;
38 }
39
40 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
41     cl::desc("Disable Post Regalloc"));
42 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
43     cl::desc("Disable branch folding"));
44 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
45     cl::desc("Disable tail duplication"));
46 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
47     cl::desc("Disable pre-register allocation tail duplication"));
48 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
49     cl::desc("Disable code placement"));
50 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
51     cl::desc("Disable Stack Slot Coloring"));
52 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
53     cl::desc("Disable Machine LICM"));
54 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
55     cl::desc("Disable Machine Sinking"));
56 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
57     cl::desc("Disable Loop Strength Reduction Pass"));
58 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
59     cl::desc("Disable Codegen Prepare"));
60 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
61     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
62 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
63     cl::desc("Print LLVM IR input to isel pass"));
64 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
65     cl::desc("Dump garbage collector data"));
66 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
67     cl::desc("Verify generated machine code"),
68     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
69
70 static cl::opt<cl::boolOrDefault>
71 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
72            cl::init(cl::BOU_UNSET));
73
74 static bool getVerboseAsm() {
75   switch (AsmVerbose) {
76   default:
77   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
78   case cl::BOU_TRUE:  return true;
79   case cl::BOU_FALSE: return false;
80   }      
81 }
82
83 // Enable or disable FastISel. Both options are needed, because
84 // FastISel is enabled by default with -fast, and we wish to be
85 // able to enable or disable fast-isel independently from -O0.
86 static cl::opt<cl::boolOrDefault>
87 EnableFastISelOption("fast-isel", cl::Hidden,
88   cl::desc("Enable the \"fast\" instruction selector"));
89
90 // Enable or disable an experimental optimization to split GEPs
91 // and run a special GVN pass which does not examine loads, in
92 // an effort to factor out redundancy implicit in complex GEPs.
93 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
94     cl::desc("Split GEPs and run no-load GVN"));
95
96 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
97                                      const std::string &Triple)
98   : TargetMachine(T), TargetTriple(Triple) {
99   AsmInfo = T.createAsmInfo(TargetTriple);
100 }
101
102 // Set the default code model for the JIT for a generic target.
103 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
104 void LLVMTargetMachine::setCodeModelForJIT() {
105   setCodeModel(CodeModel::Small);
106 }
107
108 // Set the default code model for static compilation for a generic target.
109 void LLVMTargetMachine::setCodeModelForStatic() {
110   setCodeModel(CodeModel::Small);
111 }
112
113 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
114                                             formatted_raw_ostream &Out,
115                                             CodeGenFileType FileType,
116                                             CodeGenOpt::Level OptLevel,
117                                             bool DisableVerify) {
118   // Add common CodeGen passes.
119   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify))
120     return true;
121
122   const MCAsmInfo &MAI = *getMCAsmInfo();
123   OwningPtr<MCContext> Context(new MCContext(MAI));
124   OwningPtr<MCStreamer> AsmStreamer;
125
126   formatted_raw_ostream *LegacyOutput;
127   switch (FileType) {
128   default: return true;
129   case CGFT_AssemblyFile: {
130     MCInstPrinter *InstPrinter =
131       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, Out);
132     AsmStreamer.reset(createAsmStreamer(*Context, Out,
133                                         getTargetData()->isLittleEndian(),
134                                         getVerboseAsm(), InstPrinter,
135                                         /*codeemitter*/0));
136     // Set the AsmPrinter's "O" to the output file.
137     LegacyOutput = &Out;
138     break;
139   }
140   case CGFT_ObjectFile: {
141     // Create the code emitter for the target if it exists.  If not, .o file
142     // emission fails.
143     MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
144     TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
145     if (MCE == 0 || TAB == 0)
146       return true;
147     
148     AsmStreamer.reset(createMachOStreamer(*Context, *TAB, Out, MCE));
149     
150     // Any output to the asmprinter's "O" stream is bad and needs to be fixed,
151     // force it to come out stderr.
152     // FIXME: this is horrible and leaks, eventually remove the raw_ostream from
153     // asmprinter.
154     LegacyOutput = new formatted_raw_ostream(errs());
155     break;
156   }
157   case CGFT_Null:
158     // The Null output is intended for use for performance analysis and testing,
159     // not real users.
160     AsmStreamer.reset(createNullStreamer(*Context));
161     // Any output to the asmprinter's "O" stream is bad and needs to be fixed,
162     // force it to come out stderr.
163     // FIXME: this is horrible and leaks, eventually remove the raw_ostream from
164     // asmprinter.
165     LegacyOutput = new formatted_raw_ostream(errs());
166     break;
167   }
168   
169   // Create the AsmPrinter, which takes ownership of Context and AsmStreamer
170   // if successful.
171   FunctionPass *Printer =
172     getTarget().createAsmPrinter(*LegacyOutput, *this, *Context, *AsmStreamer,
173                                  getMCAsmInfo());
174   if (Printer == 0)
175     return true;
176   
177   // If successful, createAsmPrinter took ownership of AsmStreamer and Context.
178   Context.take(); AsmStreamer.take();
179   
180   PM.add(Printer);
181   
182   // Make sure the code model is set.
183   setCodeModelForStatic();
184   PM.add(createGCInfoDeleter());
185   return false;
186 }
187
188 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
189 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
190 /// actually outputting the machine code and resolving things like the address
191 /// of functions.  This method should returns true if machine code emission is
192 /// not supported.
193 ///
194 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
195                                                    JITCodeEmitter &JCE,
196                                                    CodeGenOpt::Level OptLevel,
197                                                    bool DisableVerify) {
198   // Make sure the code model is set.
199   setCodeModelForJIT();
200   
201   // Add common CodeGen passes.
202   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify))
203     return true;
204
205   addCodeEmitter(PM, OptLevel, JCE);
206   PM.add(createGCInfoDeleter());
207
208   return false; // success!
209 }
210
211 static void printNoVerify(PassManagerBase &PM,
212                            const char *Banner) {
213   if (PrintMachineCode)
214     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
215 }
216
217 static void printAndVerify(PassManagerBase &PM,
218                            const char *Banner,
219                            bool allowDoubleDefs = false) {
220   if (PrintMachineCode)
221     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
222
223   if (VerifyMachineCode)
224     PM.add(createMachineVerifierPass(allowDoubleDefs));
225 }
226
227 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
228 /// emitting to assembly files or machine code output.
229 ///
230 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
231                                                CodeGenOpt::Level OptLevel,
232                                                bool DisableVerify) {
233   // Standard LLVM-Level Passes.
234
235   // Before running any passes, run the verifier to determine if the input
236   // coming from the front-end and/or optimizer is valid.
237   if (!DisableVerify)
238     PM.add(createVerifierPass());
239
240   // Optionally, tun split-GEPs and no-load GVN.
241   if (EnableSplitGEPGVN) {
242     PM.add(createGEPSplitterPass());
243     PM.add(createGVNPass(/*NoLoads=*/true));
244   }
245
246   // Run loop strength reduction before anything else.
247   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
248     PM.add(createLoopStrengthReducePass(getTargetLowering()));
249     if (PrintLSR)
250       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
251   }
252
253   // Turn exception handling constructs into something the code generators can
254   // handle.
255   switch (getMCAsmInfo()->getExceptionHandlingType())
256   {
257   case ExceptionHandling::SjLj:
258     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
259     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
260     // catch info can get misplaced when a selector ends up more than one block
261     // removed from the parent invoke(s). This could happen when a landing
262     // pad is shared by multiple invokes and is also a target of a normal
263     // edge from elsewhere.
264     PM.add(createSjLjEHPass(getTargetLowering()));
265     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
266     break;
267   case ExceptionHandling::Dwarf:
268     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
269     break;
270   case ExceptionHandling::None:
271     PM.add(createLowerInvokePass(getTargetLowering()));
272     break;
273   }
274
275   PM.add(createGCLoweringPass());
276
277   // Make sure that no unreachable blocks are instruction selected.
278   PM.add(createUnreachableBlockEliminationPass());
279
280   if (OptLevel != CodeGenOpt::None && !DisableCGP)
281     PM.add(createCodeGenPreparePass(getTargetLowering()));
282
283   PM.add(createStackProtectorPass(getTargetLowering()));
284
285   if (PrintISelInput)
286     PM.add(createPrintFunctionPass("\n\n"
287                                    "*** Final LLVM Code input to ISel ***\n",
288                                    &dbgs()));
289
290   // All passes which modify the LLVM IR are now complete; run the verifier
291   // to ensure that the IR is valid.
292   if (!DisableVerify)
293     PM.add(createVerifierPass());
294
295   // Standard Lower-Level Passes.
296
297   // Set up a MachineFunction for the rest of CodeGen to work on.
298   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
299
300   // Enable FastISel with -fast, but allow that to be overridden.
301   if (EnableFastISelOption == cl::BOU_TRUE ||
302       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
303     EnableFastISel = true;
304
305   // Ask the target for an isel.
306   if (addInstSelector(PM, OptLevel))
307     return true;
308
309   // Print the instruction selected machine code...
310   printAndVerify(PM, "After Instruction Selection",
311                  /* allowDoubleDefs= */ true);
312
313   // Optimize PHIs before DCE: removing dead PHI cycles may make more
314   // instructions dead.
315   if (OptLevel != CodeGenOpt::None)
316     PM.add(createOptimizePHIsPass());
317
318   // Delete dead machine instructions regardless of optimization level.
319   PM.add(createDeadMachineInstructionElimPass());
320   printAndVerify(PM, "After codegen DCE pass",
321                  /* allowDoubleDefs= */ true);
322
323   if (OptLevel != CodeGenOpt::None) {
324     PM.add(createOptimizeExtsPass());
325     if (!DisableMachineLICM)
326       PM.add(createMachineLICMPass());
327     PM.add(createMachineCSEPass());
328     if (!DisableMachineSink)
329       PM.add(createMachineSinkingPass());
330     printAndVerify(PM, "After Machine LICM, CSE and Sinking passes",
331                    /* allowDoubleDefs= */ true);
332   }
333
334   // Pre-ra tail duplication.
335   if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
336     PM.add(createTailDuplicatePass(true));
337     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
338                    /* allowDoubleDefs= */ true);
339   }
340
341   // Run pre-ra passes.
342   if (addPreRegAlloc(PM, OptLevel))
343     printAndVerify(PM, "After PreRegAlloc passes",
344                    /* allowDoubleDefs= */ true);
345
346   // Perform register allocation.
347   PM.add(createRegisterAllocator());
348   printAndVerify(PM, "After Register Allocation");
349
350   // Perform stack slot coloring.
351   if (OptLevel != CodeGenOpt::None && !DisableSSC) {
352     // FIXME: Re-enable coloring with register when it's capable of adding
353     // kill markers.
354     PM.add(createStackSlotColoringPass(false));
355     printAndVerify(PM, "After StackSlotColoring");
356   }
357
358   // Run post-ra passes.
359   if (addPostRegAlloc(PM, OptLevel))
360     printAndVerify(PM, "After PostRegAlloc passes");
361
362   PM.add(createLowerSubregsPass());
363   printAndVerify(PM, "After LowerSubregs");
364
365   // Insert prolog/epilog code.  Eliminate abstract frame index references...
366   PM.add(createPrologEpilogCodeInserter());
367   printAndVerify(PM, "After PrologEpilogCodeInserter");
368
369   // Run pre-sched2 passes.
370   if (addPreSched2(PM, OptLevel))
371     printAndVerify(PM, "After PreSched2 passes");
372
373   // Second pass scheduler.
374   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
375     PM.add(createPostRAScheduler(OptLevel));
376     printAndVerify(PM, "After PostRAScheduler");
377   }
378
379   // Branch folding must be run after regalloc and prolog/epilog insertion.
380   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
381     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
382     printNoVerify(PM, "After BranchFolding");
383   }
384
385   // Tail duplication.
386   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
387     PM.add(createTailDuplicatePass(false));
388     printNoVerify(PM, "After TailDuplicate");
389   }
390
391   PM.add(createGCMachineCodeAnalysisPass());
392
393   if (PrintGCInfo)
394     PM.add(createGCInfoPrinter(dbgs()));
395
396   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
397     PM.add(createCodePlacementOptPass());
398     printNoVerify(PM, "After CodePlacementOpt");
399   }
400
401   if (addPreEmitPass(PM, OptLevel))
402     printNoVerify(PM, "After PreEmit passes");
403
404   return false;
405 }