1 //===-- PTXTargetMachine.cpp - Define TargetMachine for PTX ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Top-level implementation for the PTX target.
12 //===----------------------------------------------------------------------===//
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"
47 MCStreamer *createPTXAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
48 bool isVerboseAsm, bool useLoc,
49 bool useCFI, bool useDwarfDirectory,
50 MCInstPrinter *InstPrint,
56 extern "C" void LLVMInitializePTXTarget() {
58 RegisterTargetMachine<PTX32TargetMachine> X(ThePTX32Target);
59 RegisterTargetMachine<PTX64TargetMachine> Y(ThePTX64Target);
61 TargetRegistry::RegisterAsmStreamer(ThePTX32Target, createPTXAsmStreamer);
62 TargetRegistry::RegisterAsmStreamer(ThePTX64Target, createPTXAsmStreamer);
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";
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,
79 : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
80 DataLayout(is64Bit ? DataLayout64 : DataLayout32),
81 Subtarget(TT, CPU, FS, is64Bit),
82 FrameLowering(Subtarget),
88 void PTX32TargetMachine::anchor() { }
90 PTX32TargetMachine::PTX32TargetMachine(const Target &T, StringRef TT,
91 StringRef CPU, StringRef FS,
92 const TargetOptions &Options,
93 Reloc::Model RM, CodeModel::Model CM,
95 : PTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {
98 void PTX64TargetMachine::anchor() { }
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) {
109 /// PTX Code Generator Pass Configuration Options.
110 class PTXPassConfig : public TargetPassConfig {
112 PTXPassConfig(PTXTargetMachine *TM, PassManagerBase &PM)
113 : TargetPassConfig(TM, PM) {}
115 PTXTargetMachine &getPTXTargetMachine() const {
116 return getTM<PTXTargetMachine>();
119 bool addInstSelector();
120 bool addPostRegAlloc();
121 bool addCodeGenPasses(MCContext *&OutContext);
125 TargetPassConfig *PTXTargetMachine::createPassConfig(PassManagerBase &PM) {
126 return new PTXPassConfig(this, PM);
129 bool PTXPassConfig::addInstSelector() {
130 PM.add(createPTXISelDag(getPTXTargetMachine(), getOptLevel()));
134 bool PTXPassConfig::addPostRegAlloc() {
135 // PTXMFInfoExtract must after register allocation!
136 //PM.add(createPTXMFInfoExtract(getPTXTargetMachine()));
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
146 // Add common CodeGen passes.
147 MCContext *Context = 0;
149 // FIXME: soon this will be converted to use the exposed TargetPassConfig API.
150 PTXPassConfig *PassConfig =
151 static_cast<PTXPassConfig*>(createPassConfig(PM));
153 PassConfig->setDisableVerify(DisableVerify);
157 if (PassConfig->addCodeGenPasses(Context))
159 assert(Context != 0 && "Failed to get MCContext");
161 if (hasMCSaveTempLabels())
162 Context->setAllowTemporaryLabels(false);
164 const MCAsmInfo &MAI = *getMCAsmInfo();
165 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
166 OwningPtr<MCStreamer> AsmStreamer;
169 case CGFT_AssemblyFile: {
170 MCInstPrinter *InstPrinter =
171 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
173 // Create a code emitter if asked to show the encoding.
174 MCCodeEmitter *MCE = 0;
175 MCAsmBackend *MAB = 0;
177 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
178 true, /* verbose asm */
181 hasMCUseDwarfDirectory(),
184 false /* show MC encoding */);
185 AsmStreamer.reset(S);
188 case CGFT_ObjectFile: {
189 llvm_unreachable("Object file emission is not supported with PTX");
192 // The Null output is intended for use for performance analysis and testing,
194 AsmStreamer.reset(createNullStreamer(*Context));
198 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
199 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
203 // If successful, createAsmPrinter took ownership of AsmStreamer.
208 PM.add(createGCInfoDeleter());
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.
217 // Standard LLVM-Level Passes.
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());
226 // Before running any passes, run the verifier to determine if the input
227 // coming from the front-end and/or optimizer is valid.
229 PM.add(createVerifierPass());
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()));
237 PM.add(createGCLoweringPass());
239 // Make sure that no unreachable blocks are instruction selected.
240 PM.add(createUnreachableBlockEliminationPass());
242 PM.add(createLowerInvokePass(getTargetLowering()));
243 // The lower invoke pass may create unreachable code. Remove it.
244 PM.add(createUnreachableBlockEliminationPass());
246 if (getOptLevel() != CodeGenOpt::None)
247 PM.add(createCodeGenPreparePass(getTargetLowering()));
249 PM.add(createStackProtectorPass(getTargetLowering()));
253 //PM.add(createPrintFunctionPass("\n\n"
254 // "*** Final LLVM Code input to ISel ***\n",
257 // All passes which modify the LLVM IR are now complete; run the verifier
258 // to ensure that the IR is valid.
260 PM.add(createVerifierPass());
262 // Standard Lower-Level Passes.
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());
270 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
272 // Set up a MachineFunction for the rest of CodeGen to work on.
273 PM.add(new MachineFunctionAnalysis(*TM));
275 // Ask the target for an isel.
276 if (addInstSelector())
279 // Print the instruction selected machine code...
280 printAndVerify("After Instruction Selection");
282 // Expand pseudo-instructions emitted by ISel.
283 addPass(ExpandISelPseudosID);
285 // Pre-ra tail duplication.
286 if (getOptLevel() != CodeGenOpt::None) {
287 addPass(TailDuplicateID);
288 printAndVerify("After Pre-RegAlloc TailDuplicate");
291 // Optimize PHIs before DCE: removing dead PHI cycles may make more
292 // instructions dead.
293 if (getOptLevel() != CodeGenOpt::None)
294 addPass(OptimizePHIsID);
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 addPass(LocalStackSlotAllocationID);
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 addPass(DeadMachineInstructionElimID);
306 printAndVerify("After codegen DCE pass");
308 addPass(MachineLICMID);
309 addPass(MachineCSEID);
310 addPass(MachineSinkingID);
311 printAndVerify("After Machine LICM, CSE and Sinking passes");
313 addPass(PeepholeOptimizerID);
314 printAndVerify("After codegen peephole optimization pass");
317 // Run pre-ra passes.
318 if (addPreRegAlloc())
319 printAndVerify("After PreRegAlloc passes");
321 // Perform register allocation.
322 PM.add(createPTXRegisterAllocator());
323 printAndVerify("After Register Allocation");
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
329 addPass(StackSlotColoringID);
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 // addPass(MachineLICMPass(false));
336 printAndVerify("After StackSlotColoring and postra Machine LICM");
339 // Run post-ra passes.
340 if (addPostRegAlloc())
341 printAndVerify("After PostRegAlloc passes");
343 addPass(ExpandPostRAPseudosID);
344 printAndVerify("After ExpandPostRAPseudos");
346 // Insert prolog/epilog code. Eliminate abstract frame index references...
347 addPass(PrologEpilogCodeInserterID);
348 printAndVerify("After PrologEpilogCodeInserter");
350 // Run pre-sched2 passes.
352 printAndVerify("After PreSched2 passes");
354 // Second pass scheduler.
355 if (getOptLevel() != CodeGenOpt::None) {
356 addPass(PostRASchedulerID);
357 printAndVerify("After PostRAScheduler");
360 // Branch folding must be run after regalloc and prolog/epilog insertion.
361 if (getOptLevel() != CodeGenOpt::None) {
362 addPass(BranchFolderPassID);
363 printNoVerify("After BranchFolding");
367 if (getOptLevel() != CodeGenOpt::None) {
368 addPass(TailDuplicateID);
369 printNoVerify("After TailDuplicate");
372 addPass(GCMachineCodeAnalysisID);
375 // PM.add(createGCInfoPrinter(dbgs()));
377 if (getOptLevel() != CodeGenOpt::None) {
378 addPass(CodePlacementOptID);
379 printNoVerify("After CodePlacementOpt");
382 if (addPreEmitPass())
383 printNoVerify("After PreEmit passes");
385 PM.add(createPTXMFInfoExtract(getPTXTargetMachine(), getOptLevel()));
386 PM.add(createPTXFPRoundingModePass(getPTXTargetMachine(), getOptLevel()));