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