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