"Minor LSR debugging stuff"
[oota-llvm.git] / lib / Target / PTX / PTXISelLowering.cpp
1 //===-- PTXISelLowering.cpp - PTX DAG Lowering Implementation -------------===//
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 PTXTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PTX.h"
15 #include "PTXISelLowering.h"
16 #include "PTXMachineFunctionInfo.h"
17 #include "PTXRegisterInfo.h"
18 #include "PTXSubtarget.h"
19 #include "llvm/Function.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 using namespace llvm;
31
32 //===----------------------------------------------------------------------===//
33 // TargetLowering Implementation
34 //===----------------------------------------------------------------------===//
35
36 PTXTargetLowering::PTXTargetLowering(TargetMachine &TM)
37   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
38   // Set up the register classes.
39   addRegisterClass(MVT::i1,  PTX::RegPredRegisterClass);
40   addRegisterClass(MVT::i16, PTX::RegI16RegisterClass);
41   addRegisterClass(MVT::i32, PTX::RegI32RegisterClass);
42   addRegisterClass(MVT::i64, PTX::RegI64RegisterClass);
43   addRegisterClass(MVT::f32, PTX::RegF32RegisterClass);
44   addRegisterClass(MVT::f64, PTX::RegF64RegisterClass);
45
46   setBooleanContents(ZeroOrOneBooleanContent);
47   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
48   setMinFunctionAlignment(2);
49
50   // Let LLVM use loads/stores for all mem* operations
51   maxStoresPerMemcpy  = 4096;
52   maxStoresPerMemmove = 4096;
53   maxStoresPerMemset  = 4096;
54
55   ////////////////////////////////////
56   /////////// Expansion //////////////
57   ////////////////////////////////////
58
59   // (any/zero/sign) extload => load + (any/zero/sign) extend
60
61   setLoadExtAction(ISD::EXTLOAD, MVT::i16, Expand);
62   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
63   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
64
65   // f32 extload => load + fextend
66
67   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
68
69   // f64 truncstore => trunc + store
70
71   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
72
73   // sign_extend_inreg => sign_extend
74
75   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
76
77   // br_cc => brcond
78
79   setOperationAction(ISD::BR_CC, MVT::Other, Expand);
80
81   // select_cc => setcc
82
83   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
84   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
85   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
86
87   ////////////////////////////////////
88   //////////// Legal /////////////////
89   ////////////////////////////////////
90
91   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
92   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
93
94   ////////////////////////////////////
95   //////////// Custom ////////////////
96   ////////////////////////////////////
97
98   // customise setcc to use bitwise logic if possible
99
100   setOperationAction(ISD::SETCC, MVT::i1, Custom);
101
102   // customize translation of memory addresses
103
104   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
105   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
106
107   // Compute derived properties from the register classes
108   computeRegisterProperties();
109 }
110
111 EVT PTXTargetLowering::getSetCCResultType(EVT VT) const {
112   return MVT::i1;
113 }
114
115 SDValue PTXTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
116   switch (Op.getOpcode()) {
117     default:
118       llvm_unreachable("Unimplemented operand");
119     case ISD::SETCC:
120       return LowerSETCC(Op, DAG);
121     case ISD::GlobalAddress:
122       return LowerGlobalAddress(Op, DAG);
123   }
124 }
125
126 const char *PTXTargetLowering::getTargetNodeName(unsigned Opcode) const {
127   switch (Opcode) {
128     default:
129       llvm_unreachable("Unknown opcode");
130     case PTXISD::COPY_ADDRESS:
131       return "PTXISD::COPY_ADDRESS";
132     case PTXISD::LOAD_PARAM:
133       return "PTXISD::LOAD_PARAM";
134     case PTXISD::STORE_PARAM:
135       return "PTXISD::STORE_PARAM";
136     case PTXISD::READ_PARAM:
137       return "PTXISD::READ_PARAM";
138     case PTXISD::WRITE_PARAM:
139       return "PTXISD::WRITE_PARAM";
140     case PTXISD::EXIT:
141       return "PTXISD::EXIT";
142     case PTXISD::RET:
143       return "PTXISD::RET";
144     case PTXISD::CALL:
145       return "PTXISD::CALL";
146   }
147 }
148
149 //===----------------------------------------------------------------------===//
150 //                      Custom Lower Operation
151 //===----------------------------------------------------------------------===//
152
153 SDValue PTXTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
154   assert(Op.getValueType() == MVT::i1 && "SetCC type must be 1-bit integer");
155   SDValue Op0 = Op.getOperand(0);
156   SDValue Op1 = Op.getOperand(1);
157   SDValue Op2 = Op.getOperand(2);
158   DebugLoc dl = Op.getDebugLoc();
159   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
160
161   // Look for X == 0, X == 1, X != 0, or X != 1
162   // We can simplify these to bitwise logic
163
164   if (Op1.getOpcode() == ISD::Constant &&
165       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
166        cast<ConstantSDNode>(Op1)->isNullValue()) &&
167       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
168
169     return DAG.getNode(ISD::AND, dl, MVT::i1, Op0, Op1);
170   }
171
172   return DAG.getNode(ISD::SETCC, dl, MVT::i1, Op0, Op1, Op2);
173 }
174
175 SDValue PTXTargetLowering::
176 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
177   EVT PtrVT = getPointerTy();
178   DebugLoc dl = Op.getDebugLoc();
179   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
180
181   assert(PtrVT.isSimple() && "Pointer must be to primitive type.");
182
183   SDValue targetGlobal = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
184   SDValue movInstr = DAG.getNode(PTXISD::COPY_ADDRESS,
185                                  dl,
186                                  PtrVT.getSimpleVT(),
187                                  targetGlobal);
188
189   return movInstr;
190 }
191
192 //===----------------------------------------------------------------------===//
193 //                      Calling Convention Implementation
194 //===----------------------------------------------------------------------===//
195
196 SDValue PTXTargetLowering::
197   LowerFormalArguments(SDValue Chain,
198                        CallingConv::ID CallConv,
199                        bool isVarArg,
200                        const SmallVectorImpl<ISD::InputArg> &Ins,
201                        DebugLoc dl,
202                        SelectionDAG &DAG,
203                        SmallVectorImpl<SDValue> &InVals) const {
204   if (isVarArg) llvm_unreachable("PTX does not support varargs");
205
206   MachineFunction &MF = DAG.getMachineFunction();
207   const PTXSubtarget& ST = getTargetMachine().getSubtarget<PTXSubtarget>();
208   PTXMachineFunctionInfo *MFI = MF.getInfo<PTXMachineFunctionInfo>();
209   PTXParamManager &PM = MFI->getParamManager();
210
211   switch (CallConv) {
212     default:
213       llvm_unreachable("Unsupported calling convention");
214       break;
215     case CallingConv::PTX_Kernel:
216       MFI->setKernel(true);
217       break;
218     case CallingConv::PTX_Device:
219       MFI->setKernel(false);
220       break;
221   }
222
223   // We do one of two things here:
224   // IsKernel || SM >= 2.0  ->  Use param space for arguments
225   // SM < 2.0               ->  Use registers for arguments
226   if (MFI->isKernel() || ST.useParamSpaceForDeviceArgs()) {
227     // We just need to emit the proper LOAD_PARAM ISDs
228     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
229       assert((!MFI->isKernel() || Ins[i].VT != MVT::i1) &&
230              "Kernels cannot take pred operands");
231
232       unsigned ParamSize = Ins[i].VT.getStoreSizeInBits();
233       unsigned Param = PM.addArgumentParam(ParamSize);
234       const std::string &ParamName = PM.getParamName(Param);
235       SDValue ParamValue = DAG.getTargetExternalSymbol(ParamName.c_str(),
236                                                        MVT::Other);
237       SDValue ArgValue = DAG.getNode(PTXISD::LOAD_PARAM, dl, Ins[i].VT, Chain,
238                                      ParamValue);
239       InVals.push_back(ArgValue);
240     }
241   }
242   else {
243     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
244       EVT                  RegVT = Ins[i].VT;
245       TargetRegisterClass* TRC   = getRegClassFor(RegVT);
246       unsigned             RegType;
247
248       // Determine which register class we need
249       if (RegVT == MVT::i1) {
250         RegType = PTXRegisterType::Pred;
251       }
252       else if (RegVT == MVT::i16) {
253         RegType = PTXRegisterType::B16;
254       }
255       else if (RegVT == MVT::i32) {
256         RegType = PTXRegisterType::B32;
257       }
258       else if (RegVT == MVT::i64) {
259         RegType = PTXRegisterType::B64;
260       }
261       else if (RegVT == MVT::f32) {
262         RegType = PTXRegisterType::F32;
263       }
264       else if (RegVT == MVT::f64) {
265         RegType = PTXRegisterType::F64;
266       }
267       else {
268         llvm_unreachable("Unknown parameter type");
269       }
270
271       // Use a unique index in the instruction to prevent instruction folding.
272       // Yes, this is a hack.
273       SDValue Index = DAG.getTargetConstant(i, MVT::i32);
274       unsigned Reg = MF.getRegInfo().createVirtualRegister(TRC);
275       SDValue ArgValue = DAG.getNode(PTXISD::READ_PARAM, dl, RegVT, Chain,
276                                      Index);
277
278       InVals.push_back(ArgValue);
279
280       MFI->addRegister(Reg, RegType, PTXRegisterSpace::Argument);
281     }
282   }
283
284   return Chain;
285 }
286
287 SDValue PTXTargetLowering::
288   LowerReturn(SDValue Chain,
289               CallingConv::ID CallConv,
290               bool isVarArg,
291               const SmallVectorImpl<ISD::OutputArg> &Outs,
292               const SmallVectorImpl<SDValue> &OutVals,
293               DebugLoc dl,
294               SelectionDAG &DAG) const {
295   if (isVarArg) llvm_unreachable("PTX does not support varargs");
296
297   switch (CallConv) {
298     default:
299       llvm_unreachable("Unsupported calling convention.");
300     case CallingConv::PTX_Kernel:
301       assert(Outs.size() == 0 && "Kernel must return void.");
302       return DAG.getNode(PTXISD::EXIT, dl, MVT::Other, Chain);
303     case CallingConv::PTX_Device:
304       assert(Outs.size() <= 1 && "Can at most return one value.");
305       break;
306   }
307
308   MachineFunction& MF = DAG.getMachineFunction();
309   PTXMachineFunctionInfo *MFI = MF.getInfo<PTXMachineFunctionInfo>();
310   PTXParamManager &PM = MFI->getParamManager();
311
312   SDValue Flag;
313   const PTXSubtarget& ST = getTargetMachine().getSubtarget<PTXSubtarget>();
314
315   if (ST.useParamSpaceForDeviceArgs()) {
316     assert(Outs.size() < 2 && "Device functions can return at most one value");
317
318     if (Outs.size() == 1) {
319       unsigned ParamSize = OutVals[0].getValueType().getSizeInBits();
320       unsigned Param = PM.addReturnParam(ParamSize);
321       const std::string &ParamName = PM.getParamName(Param);
322       SDValue ParamValue = DAG.getTargetExternalSymbol(ParamName.c_str(),
323                                                        MVT::Other);
324       Chain = DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain,
325                           ParamValue, OutVals[0]);
326     }
327   } else {
328     for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
329       EVT                  RegVT = Outs[i].VT;
330       TargetRegisterClass* TRC = 0;
331       unsigned             RegType;
332
333       // Determine which register class we need
334       if (RegVT == MVT::i1) {
335         TRC = PTX::RegPredRegisterClass;
336         RegType = PTXRegisterType::Pred;
337       }
338       else if (RegVT == MVT::i16) {
339         TRC = PTX::RegI16RegisterClass;
340         RegType = PTXRegisterType::B16;
341       }
342       else if (RegVT == MVT::i32) {
343         TRC = PTX::RegI32RegisterClass;
344         RegType = PTXRegisterType::B32;
345       }
346       else if (RegVT == MVT::i64) {
347         TRC = PTX::RegI64RegisterClass;
348         RegType = PTXRegisterType::B64;
349       }
350       else if (RegVT == MVT::f32) {
351         TRC = PTX::RegF32RegisterClass;
352         RegType = PTXRegisterType::F32;
353       }
354       else if (RegVT == MVT::f64) {
355         TRC = PTX::RegF64RegisterClass;
356         RegType = PTXRegisterType::F64;
357       }
358       else {
359         llvm_unreachable("Unknown parameter type");
360       }
361
362       unsigned Reg = MF.getRegInfo().createVirtualRegister(TRC);
363
364       SDValue Copy = DAG.getCopyToReg(Chain, dl, Reg, OutVals[i]/*, Flag*/);
365       SDValue OutReg = DAG.getRegister(Reg, RegVT);
366
367       Chain = DAG.getNode(PTXISD::WRITE_PARAM, dl, MVT::Other, Copy, OutReg);
368
369       MFI->addRegister(Reg, RegType, PTXRegisterSpace::Return);
370     }
371   }
372
373   if (Flag.getNode() == 0) {
374     return DAG.getNode(PTXISD::RET, dl, MVT::Other, Chain);
375   }
376   else {
377     return DAG.getNode(PTXISD::RET, dl, MVT::Other, Chain, Flag);
378   }
379 }
380
381 SDValue
382 PTXTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
383                              CallingConv::ID CallConv, bool isVarArg,
384                              bool &isTailCall,
385                              const SmallVectorImpl<ISD::OutputArg> &Outs,
386                              const SmallVectorImpl<SDValue> &OutVals,
387                              const SmallVectorImpl<ISD::InputArg> &Ins,
388                              DebugLoc dl, SelectionDAG &DAG,
389                              SmallVectorImpl<SDValue> &InVals) const {
390
391   MachineFunction& MF = DAG.getMachineFunction();
392   PTXMachineFunctionInfo *PTXMFI = MF.getInfo<PTXMachineFunctionInfo>();
393   PTXParamManager &PM = PTXMFI->getParamManager();
394   MachineFrameInfo *MFI = MF.getFrameInfo();
395   
396   assert(getTargetMachine().getSubtarget<PTXSubtarget>().callsAreHandled() &&
397          "Calls are not handled for the target device");
398
399   // Identify the callee function
400   const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
401   const Function *function = cast<Function>(GV);
402   
403   // allow non-device calls only for printf
404   bool isPrintf = function->getName() == "printf" || function->getName() == "puts";     
405   
406   assert((isPrintf || function->getCallingConv() == CallingConv::PTX_Device) &&
407                          "PTX function calls must be to PTX device functions");
408   
409   unsigned outSize = isPrintf ? 2 : Outs.size();
410   
411   std::vector<SDValue> Ops;
412   // The layout of the ops will be [Chain, #Ins, Ins, Callee, #Outs, Outs]
413   Ops.resize(outSize + Ins.size() + 4);
414
415   Ops[0] = Chain;
416
417   // Identify the callee function
418   Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
419   Ops[Ins.size()+2] = Callee;
420
421   // #Outs
422   Ops[Ins.size()+3] = DAG.getTargetConstant(outSize, MVT::i32);
423   
424   if (isPrintf) {
425     // first argument is the address of the global string variable in memory
426     unsigned Param0 = PM.addLocalParam(getPointerTy().getSizeInBits());
427     SDValue ParamValue0 = DAG.getTargetExternalSymbol(PM.getParamName(Param0).c_str(),
428                                                       MVT::Other);
429     Chain = DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain,
430                         ParamValue0, OutVals[0]);
431     Ops[Ins.size()+4] = ParamValue0;
432       
433     // alignment is the maximum size of all the arguments
434     unsigned alignment = 0;
435     for (unsigned i = 1; i < OutVals.size(); ++i) {
436       alignment = std::max(alignment, 
437                                OutVals[i].getValueType().getSizeInBits());
438     }
439
440     // size is the alignment multiplied by the number of arguments
441     unsigned size = alignment * (OutVals.size() - 1);
442   
443     // second argument is the address of the stack object (unless no arguments)
444     unsigned Param1 = PM.addLocalParam(getPointerTy().getSizeInBits());
445     SDValue ParamValue1 = DAG.getTargetExternalSymbol(PM.getParamName(Param1).c_str(),
446                                                       MVT::Other);
447     Ops[Ins.size()+5] = ParamValue1;
448     
449     if (size > 0)
450     {
451       // create a local stack object to store the arguments
452       unsigned StackObject = MFI->CreateStackObject(size / 8, alignment / 8, false);
453       SDValue FrameIndex = DAG.getFrameIndex(StackObject, getPointerTy());
454           
455       // store each of the arguments to the stack in turn
456       for (unsigned int i = 1; i != OutVals.size(); i++) {
457         SDValue FrameAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FrameIndex, DAG.getTargetConstant((i - 1) * 8, getPointerTy()));
458         Chain = DAG.getStore(Chain, dl, OutVals[i], FrameAddr,
459                              MachinePointerInfo(),
460                              false, false, 0);
461       }
462
463       // copy the address of the local frame index to get the address in non-local space
464       SDValue genericAddr = DAG.getNode(PTXISD::COPY_ADDRESS, dl, getPointerTy(), FrameIndex);
465
466       // store this address in the second argument
467       Chain = DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain, ParamValue1, genericAddr);
468     }
469   }
470   else
471   {
472           // Generate STORE_PARAM nodes for each function argument.  In PTX, function
473           // arguments are explicitly stored into .param variables and passed as
474           // arguments. There is no register/stack-based calling convention in PTX.
475           for (unsigned i = 0; i != OutVals.size(); ++i) {
476                 unsigned Size = OutVals[i].getValueType().getSizeInBits();
477                 unsigned Param = PM.addLocalParam(Size);
478                 const std::string &ParamName = PM.getParamName(Param);
479                 SDValue ParamValue = DAG.getTargetExternalSymbol(ParamName.c_str(),
480                                                                                                                  MVT::Other);
481                 Chain = DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain,
482                                                         ParamValue, OutVals[i]);
483                 Ops[i+Ins.size()+4] = ParamValue;
484           }
485   }
486   
487   std::vector<SDValue> InParams;
488
489   // Generate list of .param variables to hold the return value(s).
490   Ops[1] = DAG.getTargetConstant(Ins.size(), MVT::i32);
491   for (unsigned i = 0; i < Ins.size(); ++i) {
492     unsigned Size = Ins[i].VT.getStoreSizeInBits();
493     unsigned Param = PM.addLocalParam(Size);
494     const std::string &ParamName = PM.getParamName(Param);
495     SDValue ParamValue = DAG.getTargetExternalSymbol(ParamName.c_str(),
496                                                      MVT::Other);
497     Ops[i+2] = ParamValue;
498     InParams.push_back(ParamValue);
499   }
500
501   Ops[0] = Chain;
502
503   // Create the CALL node.
504   Chain = DAG.getNode(PTXISD::CALL, dl, MVT::Other, &Ops[0], Ops.size());
505
506   // Create the LOAD_PARAM nodes that retrieve the function return value(s).
507   for (unsigned i = 0; i < Ins.size(); ++i) {
508     SDValue Load = DAG.getNode(PTXISD::LOAD_PARAM, dl, Ins[i].VT, Chain,
509                                InParams[i]);
510     InVals.push_back(Load);
511   }
512
513   return Chain;
514 }
515
516 unsigned PTXTargetLowering::getNumRegisters(LLVMContext &Context, EVT VT) {
517   // All arguments consist of one "register," regardless of the type.
518   return 1;
519 }
520