Move pass configuration out of pass constructors: BranchFolderPass
[oota-llvm.git] / lib / Target / PTX / PTXTargetMachine.cpp
1 //===-- PTXTargetMachine.cpp - Define TargetMachine for PTX ---------------===//
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 // Top-level implementation for the PTX target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PTX.h"
15 #include "PTXTargetMachine.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetLoweringObjectFile.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/TargetRegistry.h"
42
43
44 using namespace llvm;
45
46 namespace llvm {
47   MCStreamer *createPTXAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
48                                    bool isVerboseAsm, bool useLoc,
49                                    bool useCFI, bool useDwarfDirectory,
50                                    MCInstPrinter *InstPrint,
51                                    MCCodeEmitter *CE,
52                                    MCAsmBackend *MAB,
53                                    bool ShowInst);
54 }
55
56 extern "C" void LLVMInitializePTXTarget() {
57
58   RegisterTargetMachine<PTX32TargetMachine> X(ThePTX32Target);
59   RegisterTargetMachine<PTX64TargetMachine> Y(ThePTX64Target);
60
61   TargetRegistry::RegisterAsmStreamer(ThePTX32Target, createPTXAsmStreamer);
62   TargetRegistry::RegisterAsmStreamer(ThePTX64Target, createPTXAsmStreamer);
63 }
64
65 namespace {
66   const char* DataLayout32 =
67     "e-p:32:32-i64:32:32-f64:32:32-v128:32:128-v64:32:64-n32:64";
68   const char* DataLayout64 =
69     "e-p:64:64-i64:32:32-f64:32:32-v128:32:128-v64:32:64-n32:64";
70 }
71
72 // DataLayout and FrameLowering are filled with dummy data
73 PTXTargetMachine::PTXTargetMachine(const Target &T,
74                                    StringRef TT, StringRef CPU, StringRef FS,
75                                    const TargetOptions &Options,
76                                    Reloc::Model RM, CodeModel::Model CM,
77                                    CodeGenOpt::Level OL,
78                                    bool is64Bit)
79   : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
80     DataLayout(is64Bit ? DataLayout64 : DataLayout32),
81     Subtarget(TT, CPU, FS, is64Bit),
82     FrameLowering(Subtarget),
83     InstrInfo(*this),
84     TSInfo(*this),
85     TLInfo(*this) {
86 }
87
88 void PTX32TargetMachine::anchor() { }
89
90 PTX32TargetMachine::PTX32TargetMachine(const Target &T, StringRef TT,
91                                        StringRef CPU, StringRef FS,
92                                        const TargetOptions &Options,
93                                        Reloc::Model RM, CodeModel::Model CM,
94                                        CodeGenOpt::Level OL)
95   : PTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {
96 }
97
98 void PTX64TargetMachine::anchor() { }
99
100 PTX64TargetMachine::PTX64TargetMachine(const Target &T, StringRef TT,
101                                        StringRef CPU, StringRef FS,
102                                        const TargetOptions &Options,
103                                        Reloc::Model RM, CodeModel::Model CM,
104                                        CodeGenOpt::Level OL)
105   : PTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {
106 }
107
108 namespace llvm {
109 /// PTX Code Generator Pass Configuration Options.
110 class PTXPassConfig : public TargetPassConfig {
111 public:
112   PTXPassConfig(PTXTargetMachine *TM, PassManagerBase &PM)
113     : TargetPassConfig(TM, PM) {}
114
115   PTXTargetMachine &getPTXTargetMachine() const {
116       return getTM<PTXTargetMachine>();
117   }
118
119   bool addInstSelector();
120   bool addPostRegAlloc();
121   bool addCodeGenPasses(MCContext *&OutContext);
122 };
123 } // namespace
124
125 TargetPassConfig *PTXTargetMachine::createPassConfig(PassManagerBase &PM) {
126   return new PTXPassConfig(this, PM);
127 }
128
129 bool PTXPassConfig::addInstSelector() {
130   PM.add(createPTXISelDag(getPTXTargetMachine(), getOptLevel()));
131   return false;
132 }
133
134 bool PTXPassConfig::addPostRegAlloc() {
135   // PTXMFInfoExtract must after register allocation!
136   //PM.add(createPTXMFInfoExtract(getPTXTargetMachine()));
137   return false;
138 }
139
140 bool PTXTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
141                                            formatted_raw_ostream &Out,
142                                            CodeGenFileType FileType,
143                                            bool DisableVerify) {
144   // This is mostly based on LLVMTargetMachine::addPassesToEmitFile
145
146   // Add common CodeGen passes.
147   MCContext *Context = 0;
148
149   // FIXME: soon this will be converted to use the exposed TargetPassConfig API.
150   PTXPassConfig *PassConfig =
151     static_cast<PTXPassConfig*>(createPassConfig(PM));
152
153   PassConfig->setDisableVerify(DisableVerify);
154
155   PM.add(PassConfig);
156
157   if (PassConfig->addCodeGenPasses(Context))
158     return true;
159   assert(Context != 0 && "Failed to get MCContext");
160
161   if (hasMCSaveTempLabels())
162     Context->setAllowTemporaryLabels(false);
163
164   const MCAsmInfo &MAI = *getMCAsmInfo();
165   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
166   OwningPtr<MCStreamer> AsmStreamer;
167
168   switch (FileType) {
169   case CGFT_AssemblyFile: {
170     MCInstPrinter *InstPrinter =
171       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
172
173     // Create a code emitter if asked to show the encoding.
174     MCCodeEmitter *MCE = 0;
175     MCAsmBackend *MAB = 0;
176
177     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
178                                                   true, /* verbose asm */
179                                                   hasMCUseLoc(),
180                                                   hasMCUseCFI(),
181                                                   hasMCUseDwarfDirectory(),
182                                                   InstPrinter,
183                                                   MCE, MAB,
184                                                   false /* show MC encoding */);
185     AsmStreamer.reset(S);
186     break;
187   }
188   case CGFT_ObjectFile: {
189     llvm_unreachable("Object file emission is not supported with PTX");
190   }
191   case CGFT_Null:
192     // The Null output is intended for use for performance analysis and testing,
193     // not real users.
194     AsmStreamer.reset(createNullStreamer(*Context));
195     break;
196   }
197
198   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
199   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
200   if (Printer == 0)
201     return true;
202
203   // If successful, createAsmPrinter took ownership of AsmStreamer.
204   AsmStreamer.take();
205
206   PM.add(Printer);
207
208   PM.add(createGCInfoDeleter());
209   return false;
210 }
211
212 bool PTXPassConfig::addCodeGenPasses(MCContext *&OutContext) {
213   // Add standard LLVM codegen passes.
214   // This is derived from LLVMTargetMachine::addCommonCodeGenPasses, with some
215   // modifications for the PTX target.
216
217   // Standard LLVM-Level Passes.
218
219   // Basic AliasAnalysis support.
220   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
221   // BasicAliasAnalysis wins if they disagree. This is intended to help
222   // support "obvious" type-punning idioms.
223   PM.add(createTypeBasedAliasAnalysisPass());
224   PM.add(createBasicAliasAnalysisPass());
225
226   // Before running any passes, run the verifier to determine if the input
227   // coming from the front-end and/or optimizer is valid.
228   if (!DisableVerify)
229     PM.add(createVerifierPass());
230
231   // Run loop strength reduction before anything else.
232   if (getOptLevel() != CodeGenOpt::None) {
233     PM.add(createLoopStrengthReducePass(getTargetLowering()));
234     //PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
235   }
236
237   PM.add(createGCLoweringPass());
238
239   // Make sure that no unreachable blocks are instruction selected.
240   PM.add(createUnreachableBlockEliminationPass());
241
242   PM.add(createLowerInvokePass(getTargetLowering()));
243   // The lower invoke pass may create unreachable code. Remove it.
244   PM.add(createUnreachableBlockEliminationPass());
245
246   if (getOptLevel() != CodeGenOpt::None)
247     PM.add(createCodeGenPreparePass(getTargetLowering()));
248
249   PM.add(createStackProtectorPass(getTargetLowering()));
250
251   addPreISel();
252
253   //PM.add(createPrintFunctionPass("\n\n"
254   //                               "*** Final LLVM Code input to ISel ***\n",
255   //                               &dbgs()));
256
257   // All passes which modify the LLVM IR are now complete; run the verifier
258   // to ensure that the IR is valid.
259   if (!DisableVerify)
260     PM.add(createVerifierPass());
261
262   // Standard Lower-Level Passes.
263
264   // Install a MachineModuleInfo class, which is an immutable pass that holds
265   // all the per-module stuff we're generating, including MCContext.
266   MachineModuleInfo *MMI = new MachineModuleInfo(*TM->getMCAsmInfo(),
267                                                  *TM->getRegisterInfo(),
268                                     &getTargetLowering()->getObjFileLowering());
269   PM.add(MMI);
270   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
271
272   // Set up a MachineFunction for the rest of CodeGen to work on.
273   PM.add(new MachineFunctionAnalysis(*TM));
274
275   // Ask the target for an isel.
276   if (addInstSelector())
277     return true;
278
279   // Print the instruction selected machine code...
280   printAndVerify("After Instruction Selection");
281
282   // Expand pseudo-instructions emitted by ISel.
283   PM.add(createExpandISelPseudosPass());
284
285   // Pre-ra tail duplication.
286   if (getOptLevel() != CodeGenOpt::None) {
287     PM.add(createTailDuplicatePass());
288     printAndVerify("After Pre-RegAlloc TailDuplicate");
289   }
290
291   // Optimize PHIs before DCE: removing dead PHI cycles may make more
292   // instructions dead.
293   if (getOptLevel() != CodeGenOpt::None)
294     PM.add(createOptimizePHIsPass());
295
296   // If the target requests it, assign local variables to stack slots relative
297   // to one another and simplify frame index references where possible.
298   PM.add(createLocalStackSlotAllocationPass());
299
300   if (getOptLevel() != CodeGenOpt::None) {
301     // With optimization, dead code should already be eliminated. However
302     // there is one known exception: lowered code for arguments that are only
303     // used by tail calls, where the tail calls reuse the incoming stack
304     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
305     PM.add(createDeadMachineInstructionElimPass());
306     printAndVerify("After codegen DCE pass");
307
308     PM.add(createMachineLICMPass());
309     PM.add(createMachineCSEPass());
310     PM.add(createMachineSinkingPass());
311     printAndVerify("After Machine LICM, CSE and Sinking passes");
312
313     PM.add(createPeepholeOptimizerPass());
314     printAndVerify("After codegen peephole optimization pass");
315   }
316
317   // Run pre-ra passes.
318   if (addPreRegAlloc())
319     printAndVerify("After PreRegAlloc passes");
320
321   // Perform register allocation.
322   PM.add(createPTXRegisterAllocator());
323   printAndVerify("After Register Allocation");
324
325   // Perform stack slot coloring and post-ra machine LICM.
326   if (getOptLevel() != CodeGenOpt::None) {
327     // FIXME: Re-enable coloring with register when it's capable of adding
328     // kill markers.
329     PM.add(createStackSlotColoringPass(false));
330
331     // FIXME: Post-RA LICM has asserts that fire on virtual registers.
332     // Run post-ra machine LICM to hoist reloads / remats.
333     //if (!DisablePostRAMachineLICM)
334     //  PM.add(createMachineLICMPass(false));
335
336     printAndVerify("After StackSlotColoring and postra Machine LICM");
337   }
338
339   // Run post-ra passes.
340   if (addPostRegAlloc())
341     printAndVerify("After PostRegAlloc passes");
342
343   PM.add(createExpandPostRAPseudosPass());
344   printAndVerify("After ExpandPostRAPseudos");
345
346   // Insert prolog/epilog code.  Eliminate abstract frame index references...
347   PM.add(createPrologEpilogCodeInserter());
348   printAndVerify("After PrologEpilogCodeInserter");
349
350   // Run pre-sched2 passes.
351   if (addPreSched2())
352     printAndVerify("After PreSched2 passes");
353
354   // Second pass scheduler.
355   if (getOptLevel() != CodeGenOpt::None) {
356     PM.add(createPostRAScheduler(getOptLevel()));
357     printAndVerify("After PostRAScheduler");
358   }
359
360   // Branch folding must be run after regalloc and prolog/epilog insertion.
361   if (getOptLevel() != CodeGenOpt::None) {
362     addPass(BranchFolderPassID);
363     printNoVerify("After BranchFolding");
364   }
365
366   // Tail duplication.
367   if (getOptLevel() != CodeGenOpt::None) {
368     PM.add(createTailDuplicatePass());
369     printNoVerify("After TailDuplicate");
370   }
371
372   PM.add(createGCMachineCodeAnalysisPass());
373
374   //if (PrintGCInfo)
375   //  PM.add(createGCInfoPrinter(dbgs()));
376
377   if (getOptLevel() != CodeGenOpt::None) {
378     PM.add(createCodePlacementOptPass());
379     printNoVerify("After CodePlacementOpt");
380   }
381
382   if (addPreEmitPass())
383     printNoVerify("After PreEmit passes");
384
385   PM.add(createPTXMFInfoExtract(getPTXTargetMachine(), getOptLevel()));
386   PM.add(createPTXFPRoundingModePass(getPTXTargetMachine(), getOptLevel()));
387
388   setInitialized();
389
390   return false;
391 }