"Minor LSR debugging stuff"
[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 bool PTXTargetMachine::addInstSelector(PassManagerBase &PM) {
109   PM.add(createPTXISelDag(*this, getOptLevel()));
110   return false;
111 }
112
113 bool PTXTargetMachine::addPostRegAlloc(PassManagerBase &PM) {
114   // PTXMFInfoExtract must after register allocation!
115   //PM.add(createPTXMFInfoExtract(*this));
116   return false;
117 }
118
119 bool PTXTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
120                                            formatted_raw_ostream &Out,
121                                            CodeGenFileType FileType,
122                                            bool DisableVerify) {
123   // This is mostly based on LLVMTargetMachine::addPassesToEmitFile
124
125   // Add common CodeGen passes.
126   MCContext *Context = 0;
127   if (addCommonCodeGenPasses(PM, 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   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
136   OwningPtr<MCStreamer> AsmStreamer;
137
138   switch (FileType) {
139   default: return true;
140   case CGFT_AssemblyFile: {
141     MCInstPrinter *InstPrinter =
142       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
143
144     // Create a code emitter if asked to show the encoding.
145     MCCodeEmitter *MCE = 0;
146     MCAsmBackend *MAB = 0;
147
148     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
149                                                   true, /* verbose asm */
150                                                   hasMCUseLoc(),
151                                                   hasMCUseCFI(),
152                                                   hasMCUseDwarfDirectory(),
153                                                   InstPrinter,
154                                                   MCE, MAB,
155                                                   false /* show MC encoding */);
156     AsmStreamer.reset(S);
157     break;
158   }
159   case CGFT_ObjectFile: {
160     llvm_unreachable("Object file emission is not supported with PTX");
161   }
162   case CGFT_Null:
163     // The Null output is intended for use for performance analysis and testing,
164     // not real users.
165     AsmStreamer.reset(createNullStreamer(*Context));
166     break;
167   }
168
169   // MC Logging
170   //AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
171
172   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
173   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
174   if (Printer == 0)
175     return true;
176
177   // If successful, createAsmPrinter took ownership of AsmStreamer.
178   AsmStreamer.take();
179
180   PM.add(Printer);
181
182   PM.add(createGCInfoDeleter());
183   return false;
184 }
185
186 bool PTXTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
187                                               bool DisableVerify,
188                                               MCContext *&OutContext) {
189   // Add standard LLVM codegen passes.
190   // This is derived from LLVMTargetMachine::addCommonCodeGenPasses, with some
191   // modifications for the PTX target.
192
193   // Standard LLVM-Level Passes.
194
195   // Basic AliasAnalysis support.
196   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
197   // BasicAliasAnalysis wins if they disagree. This is intended to help
198   // support "obvious" type-punning idioms.
199   PM.add(createTypeBasedAliasAnalysisPass());
200   PM.add(createBasicAliasAnalysisPass());
201
202   // Before running any passes, run the verifier to determine if the input
203   // coming from the front-end and/or optimizer is valid.
204   if (!DisableVerify)
205     PM.add(createVerifierPass());
206
207   // Run loop strength reduction before anything else.
208   if (getOptLevel() != CodeGenOpt::None) {
209     PM.add(createLoopStrengthReducePass(getTargetLowering()));
210     //PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
211   }
212
213   PM.add(createGCLoweringPass());
214
215   // Make sure that no unreachable blocks are instruction selected.
216   PM.add(createUnreachableBlockEliminationPass());
217
218   PM.add(createLowerInvokePass(getTargetLowering()));
219   // The lower invoke pass may create unreachable code. Remove it.
220   PM.add(createUnreachableBlockEliminationPass());
221
222   if (getOptLevel() != CodeGenOpt::None)
223     PM.add(createCodeGenPreparePass(getTargetLowering()));
224
225   PM.add(createStackProtectorPass(getTargetLowering()));
226
227   addPreISel(PM);
228
229   //PM.add(createPrintFunctionPass("\n\n"
230   //                               "*** Final LLVM Code input to ISel ***\n",
231   //                               &dbgs()));
232
233   // All passes which modify the LLVM IR are now complete; run the verifier
234   // to ensure that the IR is valid.
235   if (!DisableVerify)
236     PM.add(createVerifierPass());
237
238   // Standard Lower-Level Passes.
239
240   // Install a MachineModuleInfo class, which is an immutable pass that holds
241   // all the per-module stuff we're generating, including MCContext.
242   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
243                                                  *getRegisterInfo(),
244                                     &getTargetLowering()->getObjFileLowering());
245   PM.add(MMI);
246   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
247
248   // Set up a MachineFunction for the rest of CodeGen to work on.
249   PM.add(new MachineFunctionAnalysis(*this));
250
251   // Ask the target for an isel.
252   if (addInstSelector(PM))
253     return true;
254
255   // Print the instruction selected machine code...
256   printAndVerify(PM, "After Instruction Selection");
257
258   // Expand pseudo-instructions emitted by ISel.
259   PM.add(createExpandISelPseudosPass());
260
261   // Pre-ra tail duplication.
262   if (getOptLevel() != CodeGenOpt::None) {
263     PM.add(createTailDuplicatePass(true));
264     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
265   }
266
267   // Optimize PHIs before DCE: removing dead PHI cycles may make more
268   // instructions dead.
269   if (getOptLevel() != CodeGenOpt::None)
270     PM.add(createOptimizePHIsPass());
271
272   // If the target requests it, assign local variables to stack slots relative
273   // to one another and simplify frame index references where possible.
274   PM.add(createLocalStackSlotAllocationPass());
275
276   if (getOptLevel() != CodeGenOpt::None) {
277     // With optimization, dead code should already be eliminated. However
278     // there is one known exception: lowered code for arguments that are only
279     // used by tail calls, where the tail calls reuse the incoming stack
280     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
281     PM.add(createDeadMachineInstructionElimPass());
282     printAndVerify(PM, "After codegen DCE pass");
283
284     PM.add(createMachineLICMPass());
285     PM.add(createMachineCSEPass());
286     PM.add(createMachineSinkingPass());
287     printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
288
289     PM.add(createPeepholeOptimizerPass());
290     printAndVerify(PM, "After codegen peephole optimization pass");
291   }
292
293   // Run pre-ra passes.
294   if (addPreRegAlloc(PM))
295     printAndVerify(PM, "After PreRegAlloc passes");
296
297   // Perform register allocation.
298   PM.add(createPTXRegisterAllocator());
299   printAndVerify(PM, "After Register Allocation");
300
301   // Perform stack slot coloring and post-ra machine LICM.
302   if (getOptLevel() != CodeGenOpt::None) {
303     // FIXME: Re-enable coloring with register when it's capable of adding
304     // kill markers.
305     PM.add(createStackSlotColoringPass(false));
306
307     // FIXME: Post-RA LICM has asserts that fire on virtual registers.
308     // Run post-ra machine LICM to hoist reloads / remats.
309     //if (!DisablePostRAMachineLICM)
310     //  PM.add(createMachineLICMPass(false));
311
312     printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
313   }
314
315   // Run post-ra passes.
316   if (addPostRegAlloc(PM))
317     printAndVerify(PM, "After PostRegAlloc passes");
318
319   PM.add(createExpandPostRAPseudosPass());
320   printAndVerify(PM, "After ExpandPostRAPseudos");
321
322   // Insert prolog/epilog code.  Eliminate abstract frame index references...
323   PM.add(createPrologEpilogCodeInserter());
324   printAndVerify(PM, "After PrologEpilogCodeInserter");
325
326   // Run pre-sched2 passes.
327   if (addPreSched2(PM))
328     printAndVerify(PM, "After PreSched2 passes");
329
330   // Second pass scheduler.
331   if (getOptLevel() != CodeGenOpt::None) {
332     PM.add(createPostRAScheduler(getOptLevel()));
333     printAndVerify(PM, "After PostRAScheduler");
334   }
335
336   // Branch folding must be run after regalloc and prolog/epilog insertion.
337   if (getOptLevel() != CodeGenOpt::None) {
338     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
339     printNoVerify(PM, "After BranchFolding");
340   }
341
342   // Tail duplication.
343   if (getOptLevel() != CodeGenOpt::None) {
344     PM.add(createTailDuplicatePass(false));
345     printNoVerify(PM, "After TailDuplicate");
346   }
347
348   PM.add(createGCMachineCodeAnalysisPass());
349
350   //if (PrintGCInfo)
351   //  PM.add(createGCInfoPrinter(dbgs()));
352
353   if (getOptLevel() != CodeGenOpt::None) {
354     PM.add(createCodePlacementOptPass());
355     printNoVerify(PM, "After CodePlacementOpt");
356   }
357
358   if (addPreEmitPass(PM))
359     printNoVerify(PM, "After PreEmit passes");
360
361   PM.add(createPTXMFInfoExtract(*this, getOptLevel()));
362   PM.add(createPTXFPRoundingModePass(*this, getOptLevel()));
363
364   return false;
365 }