Add an option that allows one to "decode" the LSDA.
[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/Analysis/Passes.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/GCStrategy.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/ADT/OwningPtr.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FormattedStream.h"
36 using namespace llvm;
37
38 namespace llvm {
39   bool EnableFastISel;
40 }
41
42 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
43     cl::desc("Disable Post Regalloc"));
44 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
45     cl::desc("Disable branch folding"));
46 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
47     cl::desc("Disable tail duplication"));
48 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
49     cl::desc("Disable pre-register allocation tail duplication"));
50 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
51     cl::desc("Disable code placement"));
52 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
53     cl::desc("Disable Stack Slot Coloring"));
54 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
55     cl::desc("Disable Machine LICM"));
56 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
57     cl::Hidden,
58     cl::desc("Disable Machine LICM"));
59 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
60     cl::desc("Disable Machine Sinking"));
61 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
62     cl::desc("Disable Loop Strength Reduction Pass"));
63 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
64     cl::desc("Disable Codegen Prepare"));
65 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
66     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
67 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
68     cl::desc("Print LLVM IR input to isel pass"));
69 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
70     cl::desc("Dump garbage collector data"));
71 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
72     cl::desc("Show encoding in .s output"));
73 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
74     cl::desc("Show instruction structure in .s output"));
75 static cl::opt<bool> DecodeMCLSDA("decode-mc-lsda", cl::Hidden,
76     cl::desc("Print LSDA in human readable format in .s output"));
77 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
78     cl::desc("Enable MC API logging"));
79 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
80     cl::desc("Verify generated machine code"),
81     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
82
83 static cl::opt<cl::boolOrDefault>
84 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
85            cl::init(cl::BOU_UNSET));
86
87 static bool getVerboseAsm() {
88   switch (AsmVerbose) {
89   default:
90   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
91   case cl::BOU_TRUE:  return true;
92   case cl::BOU_FALSE: return false;
93   }
94 }
95
96 // Enable or disable FastISel. Both options are needed, because
97 // FastISel is enabled by default with -fast, and we wish to be
98 // able to enable or disable fast-isel independently from -O0.
99 static cl::opt<cl::boolOrDefault>
100 EnableFastISelOption("fast-isel", cl::Hidden,
101   cl::desc("Enable the \"fast\" instruction selector"));
102
103 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
104                                      const std::string &Triple)
105   : TargetMachine(T), TargetTriple(Triple) {
106   AsmInfo = T.createAsmInfo(TargetTriple);
107 }
108
109 // Set the default code model for the JIT for a generic target.
110 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
111 void LLVMTargetMachine::setCodeModelForJIT() {
112   setCodeModel(CodeModel::Small);
113 }
114
115 // Set the default code model for static compilation for a generic target.
116 void LLVMTargetMachine::setCodeModelForStatic() {
117   setCodeModel(CodeModel::Small);
118 }
119
120 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
121                                             formatted_raw_ostream &Out,
122                                             CodeGenFileType FileType,
123                                             CodeGenOpt::Level OptLevel,
124                                             bool DisableVerify) {
125   // Add common CodeGen passes.
126   MCContext *Context = 0;
127   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
128     return true;
129   assert(Context != 0 && "Failed to get MCContext");
130
131   if (hasMCSaveTempLabels())
132     Context->setAllowTemporaryLabels(false);
133
134   const MCAsmInfo &MAI = *getMCAsmInfo();
135   OwningPtr<MCStreamer> AsmStreamer;
136
137   switch (FileType) {
138   default: return true;
139   case CGFT_AssemblyFile: {
140     MCInstPrinter *InstPrinter =
141       getTarget().createMCInstPrinter(*this, MAI.getAssemblerDialect(), MAI);
142
143     // Create a code emitter if asked to show the encoding.
144     MCCodeEmitter *MCE = 0;
145     TargetAsmBackend *TAB = 0;
146     if (ShowMCEncoding) {
147       MCE = getTarget().createCodeEmitter(*this, *Context);
148       TAB = getTarget().createAsmBackend(TargetTriple);
149     }
150
151     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
152                                                   getVerboseAsm(),
153                                                   hasMCUseLoc(),
154                                                   hasMCUseCFI(),
155                                                   InstPrinter,
156                                                   MCE, TAB,
157                                                   ShowMCInst,
158                                                   DecodeMCLSDA);
159     AsmStreamer.reset(S);
160     break;
161   }
162   case CGFT_ObjectFile: {
163     // Create the code emitter for the target if it exists.  If not, .o file
164     // emission fails.
165     MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
166     TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
167     if (MCE == 0 || TAB == 0)
168       return true;
169
170     AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context,
171                                                        *TAB, Out, MCE,
172                                                        hasMCRelaxAll(),
173                                                        hasMCNoExecStack()));
174     AsmStreamer.get()->InitSections();
175     break;
176   }
177   case CGFT_Null:
178     // The Null output is intended for use for performance analysis and testing,
179     // not real users.
180     AsmStreamer.reset(createNullStreamer(*Context));
181     break;
182   }
183
184   if (EnableMCLogging)
185     AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
186
187   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
188   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
189   if (Printer == 0)
190     return true;
191
192   // If successful, createAsmPrinter took ownership of AsmStreamer.
193   AsmStreamer.take();
194
195   PM.add(Printer);
196
197   // Make sure the code model is set.
198   setCodeModelForStatic();
199   PM.add(createGCInfoDeleter());
200   return false;
201 }
202
203 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
204 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
205 /// actually outputting the machine code and resolving things like the address
206 /// of functions.  This method should returns true if machine code emission is
207 /// not supported.
208 ///
209 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
210                                                    JITCodeEmitter &JCE,
211                                                    CodeGenOpt::Level OptLevel,
212                                                    bool DisableVerify) {
213   // Make sure the code model is set.
214   setCodeModelForJIT();
215
216   // Add common CodeGen passes.
217   MCContext *Ctx = 0;
218   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
219     return true;
220
221   addCodeEmitter(PM, OptLevel, JCE);
222   PM.add(createGCInfoDeleter());
223
224   return false; // success!
225 }
226
227 /// addPassesToEmitMC - Add passes to the specified pass manager to get
228 /// machine code emitted with the MCJIT. This method returns true if machine
229 /// code is not supported. It fills the MCContext Ctx pointer which can be
230 /// used to build custom MCStreamer.
231 ///
232 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
233                                           MCContext *&Ctx,
234                                           raw_ostream &Out,
235                                           CodeGenOpt::Level OptLevel,
236                                           bool DisableVerify) {
237   // Add common CodeGen passes.
238   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
239     return true;
240
241   if (hasMCSaveTempLabels())
242     Ctx->setAllowTemporaryLabels(false);
243
244   // Create the code emitter for the target if it exists.  If not, .o file
245   // emission fails.
246   MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Ctx);
247   TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
248   if (MCE == 0 || TAB == 0)
249     return true;
250
251   OwningPtr<MCStreamer> AsmStreamer;
252   AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Ctx,
253                                                      *TAB, Out, MCE,
254                                                      hasMCRelaxAll(),
255                                                      hasMCNoExecStack()));
256   AsmStreamer.get()->InitSections();
257
258   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
259   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
260   if (Printer == 0)
261     return true;
262
263   // If successful, createAsmPrinter took ownership of AsmStreamer.
264   AsmStreamer.take();
265
266   PM.add(Printer);
267
268   // Make sure the code model is set.
269   setCodeModelForJIT();
270
271   return false; // success!
272 }
273
274 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
275   if (PrintMachineCode)
276     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
277 }
278
279 static void printAndVerify(PassManagerBase &PM,
280                            const char *Banner) {
281   if (PrintMachineCode)
282     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
283
284   if (VerifyMachineCode)
285     PM.add(createMachineVerifierPass(Banner));
286 }
287
288 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
289 /// emitting to assembly files or machine code output.
290 ///
291 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
292                                                CodeGenOpt::Level OptLevel,
293                                                bool DisableVerify,
294                                                MCContext *&OutContext) {
295   // Standard LLVM-Level Passes.
296
297   // Basic AliasAnalysis support.
298   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
299   // BasicAliasAnalysis wins if they disagree. This is intended to help
300   // support "obvious" type-punning idioms.
301   PM.add(createTypeBasedAliasAnalysisPass());
302   PM.add(createBasicAliasAnalysisPass());
303
304   // Before running any passes, run the verifier to determine if the input
305   // coming from the front-end and/or optimizer is valid.
306   if (!DisableVerify)
307     PM.add(createVerifierPass());
308
309   // Simplify ObjC ARC code. This is done late because it makes re-optimization
310   // difficult.
311   PM.add(createObjCARCContractPass());
312
313   // Run loop strength reduction before anything else.
314   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
315     PM.add(createLoopStrengthReducePass(getTargetLowering()));
316     if (PrintLSR)
317       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
318   }
319
320   PM.add(createGCLoweringPass());
321
322   // Make sure that no unreachable blocks are instruction selected.
323   PM.add(createUnreachableBlockEliminationPass());
324
325   // Turn exception handling constructs into something the code generators can
326   // handle.
327   switch (getMCAsmInfo()->getExceptionHandlingType()) {
328   case ExceptionHandling::SjLj:
329     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
330     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
331     // catch info can get misplaced when a selector ends up more than one block
332     // removed from the parent invoke(s). This could happen when a landing
333     // pad is shared by multiple invokes and is also a target of a normal
334     // edge from elsewhere.
335     PM.add(createSjLjEHPass(getTargetLowering()));
336     // FALLTHROUGH
337   case ExceptionHandling::DwarfCFI:
338   case ExceptionHandling::ARM:
339   case ExceptionHandling::Win64:
340     PM.add(createDwarfEHPass(this));
341     break;
342   case ExceptionHandling::None:
343     PM.add(createLowerInvokePass(getTargetLowering()));
344
345     // The lower invoke pass may create unreachable code. Remove it.
346     PM.add(createUnreachableBlockEliminationPass());
347     break;
348   }
349
350   if (OptLevel != CodeGenOpt::None && !DisableCGP)
351     PM.add(createCodeGenPreparePass(getTargetLowering()));
352
353   PM.add(createStackProtectorPass(getTargetLowering()));
354
355   addPreISel(PM, OptLevel);
356
357   if (PrintISelInput)
358     PM.add(createPrintFunctionPass("\n\n"
359                                    "*** Final LLVM Code input to ISel ***\n",
360                                    &dbgs()));
361
362   // All passes which modify the LLVM IR are now complete; run the verifier
363   // to ensure that the IR is valid.
364   if (!DisableVerify)
365     PM.add(createVerifierPass());
366
367   // Standard Lower-Level Passes.
368
369   // Install a MachineModuleInfo class, which is an immutable pass that holds
370   // all the per-module stuff we're generating, including MCContext.
371   TargetAsmInfo *TAI = new TargetAsmInfo(*this);
372   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), TAI);
373   PM.add(MMI);
374   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
375
376   // Set up a MachineFunction for the rest of CodeGen to work on.
377   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
378
379   // Enable FastISel with -fast, but allow that to be overridden.
380   if (EnableFastISelOption == cl::BOU_TRUE ||
381       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
382     EnableFastISel = true;
383
384   // Ask the target for an isel.
385   if (addInstSelector(PM, OptLevel))
386     return true;
387
388   // Print the instruction selected machine code...
389   printAndVerify(PM, "After Instruction Selection");
390
391   // Expand pseudo-instructions emitted by ISel.
392   PM.add(createExpandISelPseudosPass());
393
394   // Optimize PHIs before DCE: removing dead PHI cycles may make more
395   // instructions dead.
396   if (OptLevel != CodeGenOpt::None)
397     PM.add(createOptimizePHIsPass());
398
399   // If the target requests it, assign local variables to stack slots relative
400   // to one another and simplify frame index references where possible.
401   PM.add(createLocalStackSlotAllocationPass());
402
403   if (OptLevel != CodeGenOpt::None) {
404     // With optimization, dead code should already be eliminated. However
405     // there is one known exception: lowered code for arguments that are only
406     // used by tail calls, where the tail calls reuse the incoming stack
407     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
408     PM.add(createDeadMachineInstructionElimPass());
409     printAndVerify(PM, "After codegen DCE pass");
410
411     if (!DisableMachineLICM)
412       PM.add(createMachineLICMPass());
413     PM.add(createMachineCSEPass());
414     if (!DisableMachineSink)
415       PM.add(createMachineSinkingPass());
416     printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
417
418     PM.add(createPeepholeOptimizerPass());
419     printAndVerify(PM, "After codegen peephole optimization pass");
420   }
421
422   // Pre-ra tail duplication.
423   if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
424     PM.add(createTailDuplicatePass(true));
425     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
426   }
427
428   // Run pre-ra passes.
429   if (addPreRegAlloc(PM, OptLevel))
430     printAndVerify(PM, "After PreRegAlloc passes");
431
432   // Perform register allocation.
433   PM.add(createRegisterAllocator(OptLevel));
434   printAndVerify(PM, "After Register Allocation");
435
436   // Perform stack slot coloring and post-ra machine LICM.
437   if (OptLevel != CodeGenOpt::None) {
438     // FIXME: Re-enable coloring with register when it's capable of adding
439     // kill markers.
440     if (!DisableSSC)
441       PM.add(createStackSlotColoringPass(false));
442
443     // Run post-ra machine LICM to hoist reloads / remats.
444     if (!DisablePostRAMachineLICM)
445       PM.add(createMachineLICMPass(false));
446
447     printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
448   }
449
450   // Run post-ra passes.
451   if (addPostRegAlloc(PM, OptLevel))
452     printAndVerify(PM, "After PostRegAlloc passes");
453
454   PM.add(createLowerSubregsPass());
455   printAndVerify(PM, "After LowerSubregs");
456
457   // Insert prolog/epilog code.  Eliminate abstract frame index references...
458   PM.add(createPrologEpilogCodeInserter());
459   printAndVerify(PM, "After PrologEpilogCodeInserter");
460
461   // Run pre-sched2 passes.
462   if (addPreSched2(PM, OptLevel))
463     printAndVerify(PM, "After PreSched2 passes");
464
465   // Second pass scheduler.
466   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
467     PM.add(createPostRAScheduler(OptLevel));
468     printAndVerify(PM, "After PostRAScheduler");
469   }
470
471   // Branch folding must be run after regalloc and prolog/epilog insertion.
472   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
473     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
474     printNoVerify(PM, "After BranchFolding");
475   }
476
477   // Tail duplication.
478   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
479     PM.add(createTailDuplicatePass(false));
480     printNoVerify(PM, "After TailDuplicate");
481   }
482
483   PM.add(createGCMachineCodeAnalysisPass());
484
485   if (PrintGCInfo)
486     PM.add(createGCInfoPrinter(dbgs()));
487
488   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
489     PM.add(createCodePlacementOptPass());
490     printNoVerify(PM, "After CodePlacementOpt");
491   }
492
493   if (addPreEmitPass(PM, OptLevel))
494     printNoVerify(PM, "After PreEmit passes");
495
496   return false;
497 }