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