Silence wrong warnings from GCC about variables possibly being used
[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
247       // Use a unique index in the instruction to prevent instruction folding.
248       // Yes, this is a hack.
249       SDValue Index = DAG.getTargetConstant(i, MVT::i32);
250       unsigned Reg = MF.getRegInfo().createVirtualRegister(TRC);
251       SDValue ArgValue = DAG.getNode(PTXISD::READ_PARAM, dl, RegVT, Chain,
252                                      Index);
253
254       InVals.push_back(ArgValue);
255
256       MFI->addArgReg(Reg);
257     }
258   }
259
260   return Chain;
261 }
262
263 SDValue PTXTargetLowering::
264   LowerReturn(SDValue Chain,
265               CallingConv::ID CallConv,
266               bool isVarArg,
267               const SmallVectorImpl<ISD::OutputArg> &Outs,
268               const SmallVectorImpl<SDValue> &OutVals,
269               DebugLoc dl,
270               SelectionDAG &DAG) const {
271   if (isVarArg) llvm_unreachable("PTX does not support varargs");
272
273   switch (CallConv) {
274     default:
275       llvm_unreachable("Unsupported calling convention.");
276     case CallingConv::PTX_Kernel:
277       assert(Outs.size() == 0 && "Kernel must return void.");
278       return DAG.getNode(PTXISD::EXIT, dl, MVT::Other, Chain);
279     case CallingConv::PTX_Device:
280       assert(Outs.size() <= 1 && "Can at most return one value.");
281       break;
282   }
283
284   MachineFunction& MF = DAG.getMachineFunction();
285   PTXMachineFunctionInfo *MFI = MF.getInfo<PTXMachineFunctionInfo>();
286   PTXParamManager &PM = MFI->getParamManager();
287
288   SDValue Flag;
289   const PTXSubtarget& ST = getTargetMachine().getSubtarget<PTXSubtarget>();
290
291   if (ST.useParamSpaceForDeviceArgs()) {
292     assert(Outs.size() < 2 && "Device functions can return at most one value");
293
294     if (Outs.size() == 1) {
295       unsigned ParamSize = OutVals[0].getValueType().getSizeInBits();
296       unsigned Param = PM.addReturnParam(ParamSize);
297       const std::string &ParamName = PM.getParamName(Param);
298       SDValue ParamValue = DAG.getTargetExternalSymbol(ParamName.c_str(),
299                                                        MVT::Other);
300       Chain = DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain,
301                           ParamValue, OutVals[0]);
302     }
303   } else {
304     for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
305       EVT                  RegVT = Outs[i].VT;
306       TargetRegisterClass* TRC = 0;
307
308       // Determine which register class we need
309       if (RegVT == MVT::i1) {
310         TRC = PTX::RegPredRegisterClass;
311       }
312       else if (RegVT == MVT::i16) {
313         TRC = PTX::RegI16RegisterClass;
314       }
315       else if (RegVT == MVT::i32) {
316         TRC = PTX::RegI32RegisterClass;
317       }
318       else if (RegVT == MVT::i64) {
319         TRC = PTX::RegI64RegisterClass;
320       }
321       else if (RegVT == MVT::f32) {
322         TRC = PTX::RegF32RegisterClass;
323       }
324       else if (RegVT == MVT::f64) {
325         TRC = PTX::RegF64RegisterClass;
326       }
327       else {
328         llvm_unreachable("Unknown parameter type");
329       }
330
331       unsigned Reg = MF.getRegInfo().createVirtualRegister(TRC);
332
333       SDValue Copy = DAG.getCopyToReg(Chain, dl, Reg, OutVals[i]/*, Flag*/);
334       SDValue OutReg = DAG.getRegister(Reg, RegVT);
335
336       Chain = DAG.getNode(PTXISD::WRITE_PARAM, dl, MVT::Other, Copy, OutReg);
337
338       MFI->addRetReg(Reg);
339     }
340   }
341
342   if (Flag.getNode() == 0) {
343     return DAG.getNode(PTXISD::RET, dl, MVT::Other, Chain);
344   }
345   else {
346     return DAG.getNode(PTXISD::RET, dl, MVT::Other, Chain, Flag);
347   }
348 }
349
350 SDValue
351 PTXTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
352                              CallingConv::ID CallConv, bool isVarArg,
353                              bool &isTailCall,
354                              const SmallVectorImpl<ISD::OutputArg> &Outs,
355                              const SmallVectorImpl<SDValue> &OutVals,
356                              const SmallVectorImpl<ISD::InputArg> &Ins,
357                              DebugLoc dl, SelectionDAG &DAG,
358                              SmallVectorImpl<SDValue> &InVals) const {
359
360   MachineFunction& MF = DAG.getMachineFunction();
361   PTXMachineFunctionInfo *PTXMFI = MF.getInfo<PTXMachineFunctionInfo>();
362   PTXParamManager &PM = PTXMFI->getParamManager();
363   MachineFrameInfo *MFI = MF.getFrameInfo();
364   
365   assert(getTargetMachine().getSubtarget<PTXSubtarget>().callsAreHandled() &&
366          "Calls are not handled for the target device");
367
368   // Identify the callee function
369   const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
370   const Function *function = cast<Function>(GV);
371   
372   // allow non-device calls only for printf
373   bool isPrintf = function->getName() == "printf" || function->getName() == "puts";     
374   
375   assert((isPrintf || function->getCallingConv() == CallingConv::PTX_Device) &&
376                          "PTX function calls must be to PTX device functions");
377   
378   unsigned outSize = isPrintf ? 2 : Outs.size();
379   
380   std::vector<SDValue> Ops;
381   // The layout of the ops will be [Chain, #Ins, Ins, Callee, #Outs, Outs]
382   Ops.resize(outSize + Ins.size() + 4);
383
384   Ops[0] = Chain;
385
386   // Identify the callee function
387   Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
388   Ops[Ins.size()+2] = Callee;
389
390   // #Outs
391   Ops[Ins.size()+3] = DAG.getTargetConstant(outSize, MVT::i32);
392   
393   if (isPrintf) {
394     // first argument is the address of the global string variable in memory
395     unsigned Param0 = PM.addLocalParam(getPointerTy().getSizeInBits());
396     SDValue ParamValue0 = DAG.getTargetExternalSymbol(PM.getParamName(Param0).c_str(),
397                                                       MVT::Other);
398     Chain = DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain,
399                         ParamValue0, OutVals[0]);
400     Ops[Ins.size()+4] = ParamValue0;
401       
402     // alignment is the maximum size of all the arguments
403     unsigned alignment = 0;
404     for (unsigned i = 1; i < OutVals.size(); ++i) {
405       alignment = std::max(alignment, 
406                                OutVals[i].getValueType().getSizeInBits());
407     }
408
409     // size is the alignment multiplied by the number of arguments
410     unsigned size = alignment * (OutVals.size() - 1);
411   
412     // second argument is the address of the stack object (unless no arguments)
413     unsigned Param1 = PM.addLocalParam(getPointerTy().getSizeInBits());
414     SDValue ParamValue1 = DAG.getTargetExternalSymbol(PM.getParamName(Param1).c_str(),
415                                                       MVT::Other);
416     Ops[Ins.size()+5] = ParamValue1;
417     
418     if (size > 0)
419     {
420       // create a local stack object to store the arguments
421       unsigned StackObject = MFI->CreateStackObject(size / 8, alignment / 8, false);
422       SDValue FrameIndex = DAG.getFrameIndex(StackObject, getPointerTy());
423           
424       // store each of the arguments to the stack in turn
425       for (unsigned int i = 1; i != OutVals.size(); i++) {
426         SDValue FrameAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FrameIndex, DAG.getTargetConstant((i - 1) * 8, getPointerTy()));
427         Chain = DAG.getStore(Chain, dl, OutVals[i], FrameAddr,
428                              MachinePointerInfo(),
429                              false, false, 0);
430       }
431
432       // copy the address of the local frame index to get the address in non-local space
433       SDValue genericAddr = DAG.getNode(PTXISD::COPY_ADDRESS, dl, getPointerTy(), FrameIndex);
434
435       // store this address in the second argument
436       Chain = DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain, ParamValue1, genericAddr);
437     }
438   }
439   else
440   {
441           // Generate STORE_PARAM nodes for each function argument.  In PTX, function
442           // arguments are explicitly stored into .param variables and passed as
443           // arguments. There is no register/stack-based calling convention in PTX.
444           for (unsigned i = 0; i != OutVals.size(); ++i) {
445                 unsigned Size = OutVals[i].getValueType().getSizeInBits();
446                 unsigned Param = PM.addLocalParam(Size);
447                 const std::string &ParamName = PM.getParamName(Param);
448                 SDValue ParamValue = DAG.getTargetExternalSymbol(ParamName.c_str(),
449                                                                                                                  MVT::Other);
450                 Chain = DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain,
451                                                         ParamValue, OutVals[i]);
452                 Ops[i+Ins.size()+4] = ParamValue;
453           }
454   }
455   
456   std::vector<SDValue> InParams;
457
458   // Generate list of .param variables to hold the return value(s).
459   Ops[1] = DAG.getTargetConstant(Ins.size(), MVT::i32);
460   for (unsigned i = 0; i < Ins.size(); ++i) {
461     unsigned Size = Ins[i].VT.getStoreSizeInBits();
462     unsigned Param = PM.addLocalParam(Size);
463     const std::string &ParamName = PM.getParamName(Param);
464     SDValue ParamValue = DAG.getTargetExternalSymbol(ParamName.c_str(),
465                                                      MVT::Other);
466     Ops[i+2] = ParamValue;
467     InParams.push_back(ParamValue);
468   }
469
470   Ops[0] = Chain;
471
472   // Create the CALL node.
473   Chain = DAG.getNode(PTXISD::CALL, dl, MVT::Other, &Ops[0], Ops.size());
474
475   // Create the LOAD_PARAM nodes that retrieve the function return value(s).
476   for (unsigned i = 0; i < Ins.size(); ++i) {
477     SDValue Load = DAG.getNode(PTXISD::LOAD_PARAM, dl, Ins[i].VT, Chain,
478                                InParams[i]);
479     InVals.push_back(Load);
480   }
481
482   return Chain;
483 }
484
485 unsigned PTXTargetLowering::getNumRegisters(LLVMContext &Context, EVT VT) {
486   // All arguments consist of one "register," regardless of the type.
487   return 1;
488 }
489