Expand fp_to_uint too
[oota-llvm.git] / lib / Target / SystemZ / SystemZISelLowering.cpp
1 //===-- SystemZISelLowering.cpp - SystemZ 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 SystemZTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "systemz-lower"
15
16 #include "SystemZISelLowering.h"
17 #include "SystemZ.h"
18 #include "SystemZTargetMachine.h"
19 #include "SystemZSubtarget.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/PseudoSourceValue.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/VectorExtras.h"
37 using namespace llvm;
38
39 SystemZTargetLowering::SystemZTargetLowering(SystemZTargetMachine &tm) :
40   TargetLowering(tm), Subtarget(*tm.getSubtargetImpl()), TM(tm) {
41
42   RegInfo = TM.getRegisterInfo();
43
44   // Set up the register classes.
45   addRegisterClass(MVT::i32,  SystemZ::GR32RegisterClass);
46   addRegisterClass(MVT::i64,  SystemZ::GR64RegisterClass);
47   addRegisterClass(MVT::v2i32,SystemZ::GR64PRegisterClass);
48   addRegisterClass(MVT::i128, SystemZ::GR128RegisterClass);
49   addRegisterClass(MVT::v2i64,SystemZ::GR128RegisterClass);
50
51   if (!UseSoftFloat) {
52     addRegisterClass(MVT::f32, SystemZ::FP32RegisterClass);
53     addRegisterClass(MVT::f64, SystemZ::FP64RegisterClass);
54
55     addLegalFPImmediate(APFloat(+0.0));  // lzer
56     addLegalFPImmediate(APFloat(+0.0f)); // lzdr
57     addLegalFPImmediate(APFloat(-0.0));  // lzer + lner
58     addLegalFPImmediate(APFloat(-0.0f)); // lzdr + lndr
59   }
60
61   // Compute derived properties from the register classes
62   computeRegisterProperties();
63
64   // Set shifts properties
65   setShiftAmountFlavor(Extend);
66   setShiftAmountType(MVT::i64);
67
68   // Provide all sorts of operation actions
69   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
70   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
71   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
72
73   setLoadExtAction(ISD::SEXTLOAD, MVT::f32, Expand);
74   setLoadExtAction(ISD::ZEXTLOAD, MVT::f32, Expand);
75   setLoadExtAction(ISD::EXTLOAD,  MVT::f32, Expand);
76
77   setLoadExtAction(ISD::SEXTLOAD, MVT::f64, Expand);
78   setLoadExtAction(ISD::ZEXTLOAD, MVT::f64, Expand);
79   setLoadExtAction(ISD::EXTLOAD,  MVT::f64, Expand);
80
81   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
82   setSchedulingPreference(SchedulingForLatency);
83
84   setOperationAction(ISD::RET,              MVT::Other, Custom);
85
86   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
87   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
88   setOperationAction(ISD::BR_CC,            MVT::i32, Custom);
89   setOperationAction(ISD::BR_CC,            MVT::i64, Custom);
90   setOperationAction(ISD::BR_CC,            MVT::f32, Custom);
91   setOperationAction(ISD::BR_CC,            MVT::f64, Custom);
92   setOperationAction(ISD::ConstantPool,     MVT::i32, Custom);
93   setOperationAction(ISD::ConstantPool,     MVT::i64, Custom);
94   setOperationAction(ISD::GlobalAddress,    MVT::i64, Custom);
95   setOperationAction(ISD::JumpTable,        MVT::i64, Custom);
96   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
97
98   setOperationAction(ISD::SDIV,             MVT::i32, Expand);
99   setOperationAction(ISD::UDIV,             MVT::i32, Expand);
100   setOperationAction(ISD::SDIV,             MVT::i64, Expand);
101   setOperationAction(ISD::UDIV,             MVT::i64, Expand);
102   setOperationAction(ISD::SREM,             MVT::i32, Expand);
103   setOperationAction(ISD::UREM,             MVT::i32, Expand);
104   setOperationAction(ISD::SREM,             MVT::i64, Expand);
105   setOperationAction(ISD::UREM,             MVT::i64, Expand);
106
107   // FIXME: Can we lower these 2 efficiently?
108   setOperationAction(ISD::SETCC,            MVT::i32, Expand);
109   setOperationAction(ISD::SETCC,            MVT::i64, Expand);
110   setOperationAction(ISD::SETCC,            MVT::f32, Expand);
111   setOperationAction(ISD::SETCC,            MVT::f64, Expand);
112   setOperationAction(ISD::SELECT,           MVT::i32, Expand);
113   setOperationAction(ISD::SELECT,           MVT::i64, Expand);
114   setOperationAction(ISD::SELECT,           MVT::f32, Expand);
115   setOperationAction(ISD::SELECT,           MVT::f64, Expand);
116   setOperationAction(ISD::SELECT_CC,        MVT::i32, Custom);
117   setOperationAction(ISD::SELECT_CC,        MVT::i64, Custom);
118   setOperationAction(ISD::SELECT_CC,        MVT::f32, Custom);
119   setOperationAction(ISD::SELECT_CC,        MVT::f64, Custom);
120
121   // Funny enough: we don't have 64-bit signed versions of these stuff, but have
122   // unsigned.
123   setOperationAction(ISD::MULHS,            MVT::i64, Expand);
124   setOperationAction(ISD::SMUL_LOHI,        MVT::i64, Expand);
125
126   // Lower some FP stuff
127   setOperationAction(ISD::FSIN,             MVT::f32, Expand);
128   setOperationAction(ISD::FSIN,             MVT::f64, Expand);
129   setOperationAction(ISD::FCOS,             MVT::f32, Expand);
130   setOperationAction(ISD::FCOS,             MVT::f64, Expand);
131
132   setOperationAction(ISD::UINT_TO_FP,       MVT::i32, Expand);
133   setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Expand);
134   setOperationAction(ISD::FP_TO_UINT,       MVT::i32, Expand);
135   setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Expand);
136
137   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
138 }
139
140 SDValue SystemZTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
141   switch (Op.getOpcode()) {
142   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
143   case ISD::RET:              return LowerRET(Op, DAG);
144   case ISD::CALL:             return LowerCALL(Op, DAG);
145   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
146   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
147   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
148   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
149   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
150   default:
151     assert(0 && "unimplemented operand");
152     return SDValue();
153   }
154 }
155
156 //===----------------------------------------------------------------------===//
157 //                      Calling Convention Implementation
158 //===----------------------------------------------------------------------===//
159
160 #include "SystemZGenCallingConv.inc"
161
162 SDValue SystemZTargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
163                                                      SelectionDAG &DAG) {
164   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
165   switch (CC) {
166   default:
167     assert(0 && "Unsupported calling convention");
168   case CallingConv::C:
169   case CallingConv::Fast:
170     return LowerCCCArguments(Op, DAG);
171   }
172 }
173
174 SDValue SystemZTargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
175   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
176   unsigned CallingConv = TheCall->getCallingConv();
177   switch (CallingConv) {
178   default:
179     assert(0 && "Unsupported calling convention");
180   case CallingConv::Fast:
181   case CallingConv::C:
182     return LowerCCCCallTo(Op, DAG, CallingConv);
183   }
184 }
185
186 /// LowerCCCArguments - transform physical registers into virtual registers and
187 /// generate load operations for arguments places on the stack.
188 // FIXME: struct return stuff
189 // FIXME: varargs
190 SDValue SystemZTargetLowering::LowerCCCArguments(SDValue Op,
191                                                  SelectionDAG &DAG) {
192   MachineFunction &MF = DAG.getMachineFunction();
193   MachineFrameInfo *MFI = MF.getFrameInfo();
194   MachineRegisterInfo &RegInfo = MF.getRegInfo();
195   SDValue Root = Op.getOperand(0);
196   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
197   unsigned CC = MF.getFunction()->getCallingConv();
198   DebugLoc dl = Op.getDebugLoc();
199
200   // Assign locations to all of the incoming arguments.
201   SmallVector<CCValAssign, 16> ArgLocs;
202   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
203   CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_SystemZ);
204
205   assert(!isVarArg && "Varargs not supported yet");
206
207   SmallVector<SDValue, 16> ArgValues;
208   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
209     CCValAssign &VA = ArgLocs[i];
210     if (VA.isRegLoc()) {
211       // Arguments passed in registers
212       MVT RegVT = VA.getLocVT();
213       TargetRegisterClass *RC;
214       switch (RegVT.getSimpleVT()) {
215       default:
216         cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
217              << RegVT.getSimpleVT()
218              << "\n";
219         abort();
220        case MVT::i64:
221         RC = SystemZ::GR64RegisterClass;
222         break;
223        case MVT::f32:
224         RC = SystemZ::FP32RegisterClass;
225         break;
226        case MVT::f64:
227         RC = SystemZ::FP64RegisterClass;
228         break;
229       }
230
231       unsigned VReg = RegInfo.createVirtualRegister(RC);
232       RegInfo.addLiveIn(VA.getLocReg(), VReg);
233       SDValue ArgValue = DAG.getCopyFromReg(Root, dl, VReg, RegVT);
234
235       // If this is an 8/16/32-bit value, it is really passed promoted to 64
236       // bits. Insert an assert[sz]ext to capture this, then truncate to the
237       // right size.
238       if (VA.getLocInfo() == CCValAssign::SExt)
239         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
240                                DAG.getValueType(VA.getValVT()));
241       else if (VA.getLocInfo() == CCValAssign::ZExt)
242         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
243                                DAG.getValueType(VA.getValVT()));
244
245       if (VA.getLocInfo() != CCValAssign::Full)
246         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
247
248       ArgValues.push_back(ArgValue);
249     } else {
250       // Sanity check
251       assert(VA.isMemLoc());
252
253       // Create the nodes corresponding to a load from this parameter slot.
254       // Create the frame index object for this incoming parameter...
255       int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
256                                       VA.getLocMemOffset());
257
258       // Create the SelectionDAG nodes corresponding to a load
259       //from this parameter
260       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
261       ArgValues.push_back(DAG.getLoad(VA.getValVT(), dl, Root, FIN,
262                                       PseudoSourceValue::getFixedStack(FI), 0));
263     }
264   }
265
266   ArgValues.push_back(Root);
267
268   // Return the new list of results.
269   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
270                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
271 }
272
273 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
274 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
275 /// TODO: sret.
276 SDValue SystemZTargetLowering::LowerCCCCallTo(SDValue Op, SelectionDAG &DAG,
277                                               unsigned CC) {
278   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
279   SDValue Chain  = TheCall->getChain();
280   SDValue Callee = TheCall->getCallee();
281   bool isVarArg  = TheCall->isVarArg();
282   DebugLoc dl = Op.getDebugLoc();
283   MachineFunction &MF = DAG.getMachineFunction();
284
285   // Offset to first argument stack slot.
286   const unsigned FirstArgOffset = 160;
287
288   // Analyze operands of the call, assigning locations to each operand.
289   SmallVector<CCValAssign, 16> ArgLocs;
290   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
291
292   CCInfo.AnalyzeCallOperands(TheCall, CC_SystemZ);
293
294   // Get a count of how many bytes are to be pushed on the stack.
295   unsigned NumBytes = CCInfo.getNextStackOffset();
296
297   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
298                                                       getPointerTy(), true));
299
300   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
301   SmallVector<SDValue, 12> MemOpChains;
302   SDValue StackPtr;
303
304   // Walk the register/memloc assignments, inserting copies/loads.
305   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
306     CCValAssign &VA = ArgLocs[i];
307
308     // Arguments start after the 5 first operands of ISD::CALL
309     SDValue Arg = TheCall->getArg(i);
310
311     // Promote the value if needed.
312     switch (VA.getLocInfo()) {
313       default: assert(0 && "Unknown loc info!");
314       case CCValAssign::Full: break;
315       case CCValAssign::SExt:
316         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
317         break;
318       case CCValAssign::ZExt:
319         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
320         break;
321       case CCValAssign::AExt:
322         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
323         break;
324     }
325
326     // Arguments that can be passed on register must be kept at RegsToPass
327     // vector
328     if (VA.isRegLoc()) {
329       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
330     } else {
331       assert(VA.isMemLoc());
332
333       if (StackPtr.getNode() == 0)
334         StackPtr =
335           DAG.getCopyFromReg(Chain, dl,
336                              (RegInfo->hasFP(MF) ?
337                               SystemZ::R11D : SystemZ::R15D),
338                              getPointerTy());
339
340       unsigned Offset = FirstArgOffset + VA.getLocMemOffset();
341       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
342                                    StackPtr,
343                                    DAG.getIntPtrConstant(Offset));
344
345       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
346                                          PseudoSourceValue::getStack(), Offset));
347     }
348   }
349
350   // Transform all store nodes into one single node because all store nodes are
351   // independent of each other.
352   if (!MemOpChains.empty())
353     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
354                         &MemOpChains[0], MemOpChains.size());
355
356   // Build a sequence of copy-to-reg nodes chained together with token chain and
357   // flag operands which copy the outgoing args into registers.  The InFlag in
358   // necessary since all emited instructions must be stuck together.
359   SDValue InFlag;
360   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
361     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
362                              RegsToPass[i].second, InFlag);
363     InFlag = Chain.getValue(1);
364   }
365
366   // If the callee is a GlobalAddress node (quite common, every direct call is)
367   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
368   // Likewise ExternalSymbol -> TargetExternalSymbol.
369   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
370     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
371   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
372     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), getPointerTy());
373
374   // Returns a chain & a flag for retval copy to use.
375   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
376   SmallVector<SDValue, 8> Ops;
377   Ops.push_back(Chain);
378   Ops.push_back(Callee);
379
380   // Add argument registers to the end of the list so that they are
381   // known live into the call.
382   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
383     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
384                                   RegsToPass[i].second.getValueType()));
385
386   if (InFlag.getNode())
387     Ops.push_back(InFlag);
388
389   Chain = DAG.getNode(SystemZISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
390   InFlag = Chain.getValue(1);
391
392   // Create the CALLSEQ_END node.
393   Chain = DAG.getCALLSEQ_END(Chain,
394                              DAG.getConstant(NumBytes, getPointerTy(), true),
395                              DAG.getConstant(0, getPointerTy(), true),
396                              InFlag);
397   InFlag = Chain.getValue(1);
398
399   // Handle result values, copying them out of physregs into vregs that we
400   // return.
401   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
402                  Op.getResNo());
403 }
404
405 /// LowerCallResult - Lower the result values of an ISD::CALL into the
406 /// appropriate copies out of appropriate physical registers.  This assumes that
407 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
408 /// being lowered. Returns a SDNode with the same number of values as the
409 /// ISD::CALL.
410 SDNode*
411 SystemZTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
412                                        CallSDNode *TheCall,
413                                        unsigned CallingConv,
414                                        SelectionDAG &DAG) {
415   bool isVarArg = TheCall->isVarArg();
416   DebugLoc dl = TheCall->getDebugLoc();
417
418   // Assign locations to each value returned by this call.
419   SmallVector<CCValAssign, 16> RVLocs;
420   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
421
422   CCInfo.AnalyzeCallResult(TheCall, RetCC_SystemZ);
423   SmallVector<SDValue, 8> ResultVals;
424
425   // Copy all of the result registers out of their specified physreg.
426   for (unsigned i = 0; i != RVLocs.size(); ++i) {
427     CCValAssign &VA = RVLocs[i];
428
429     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
430                                VA.getLocVT(), InFlag).getValue(1);
431     SDValue RetValue = Chain.getValue(0);
432     InFlag = Chain.getValue(2);
433
434     // If this is an 8/16/32-bit value, it is really passed promoted to 64
435     // bits. Insert an assert[sz]ext to capture this, then truncate to the
436     // right size.
437     if (VA.getLocInfo() == CCValAssign::SExt)
438       RetValue = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), RetValue,
439                              DAG.getValueType(VA.getValVT()));
440     else if (VA.getLocInfo() == CCValAssign::ZExt)
441       RetValue = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), RetValue,
442                              DAG.getValueType(VA.getValVT()));
443
444     if (VA.getLocInfo() != CCValAssign::Full)
445       RetValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), RetValue);
446
447     ResultVals.push_back(RetValue);
448   }
449
450   ResultVals.push_back(Chain);
451
452   // Merge everything together with a MERGE_VALUES node.
453   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
454                      &ResultVals[0], ResultVals.size()).getNode();
455 }
456
457
458 SDValue SystemZTargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
459   // CCValAssign - represent the assignment of the return value to a location
460   SmallVector<CCValAssign, 16> RVLocs;
461   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
462   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
463   DebugLoc dl = Op.getDebugLoc();
464
465   // CCState - Info about the registers and stack slot.
466   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
467
468   // Analize return values of ISD::RET
469   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_SystemZ);
470
471   // If this is the first return lowered for this function, add the regs to the
472   // liveout set for the function.
473   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
474     for (unsigned i = 0; i != RVLocs.size(); ++i)
475       if (RVLocs[i].isRegLoc())
476         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
477   }
478
479   // The chain is always operand #0
480   SDValue Chain = Op.getOperand(0);
481   SDValue Flag;
482
483   // Copy the result values into the output registers.
484   for (unsigned i = 0; i != RVLocs.size(); ++i) {
485     CCValAssign &VA = RVLocs[i];
486     SDValue ResValue = Op.getOperand(i*2+1);
487     assert(VA.isRegLoc() && "Can only return in registers!");
488
489     // If this is an 8/16/32-bit value, it is really should be passed promoted
490     // to 64 bits.
491     if (VA.getLocInfo() == CCValAssign::SExt)
492       ResValue = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ResValue);
493     else if (VA.getLocInfo() == CCValAssign::ZExt)
494       ResValue = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ResValue);
495     else if (VA.getLocInfo() == CCValAssign::AExt)
496       ResValue = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ResValue);
497
498     // ISD::RET => ret chain, (regnum1,val1), ...
499     // So i*2+1 index only the regnums
500     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ResValue, Flag);
501
502     // Guarantee that all emitted copies are stuck together,
503     // avoiding something bad.
504     Flag = Chain.getValue(1);
505   }
506
507   if (Flag.getNode())
508     return DAG.getNode(SystemZISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
509
510   // Return Void
511   return DAG.getNode(SystemZISD::RET_FLAG, dl, MVT::Other, Chain);
512 }
513
514 SDValue SystemZTargetLowering::EmitCmp(SDValue LHS, SDValue RHS,
515                                        ISD::CondCode CC, SDValue &SystemZCC,
516                                        SelectionDAG &DAG) {
517   // FIXME: Emit a test if RHS is zero
518
519   bool isUnsigned = false;
520   SystemZCC::CondCodes TCC;
521   switch (CC) {
522   default: assert(0 && "Invalid integer condition!");
523   case ISD::SETEQ:
524   case ISD::SETOEQ:
525     TCC = SystemZCC::E;
526     break;
527   case ISD::SETUEQ:
528     TCC = SystemZCC::NLH;
529     break;
530   case ISD::SETNE:
531   case ISD::SETONE:
532     TCC = SystemZCC::NE;
533     break;
534   case ISD::SETUNE:
535     TCC = SystemZCC::LH;
536     break;
537   case ISD::SETO:
538     TCC = SystemZCC::O;
539     break;
540   case ISD::SETUO:
541     TCC = SystemZCC::NO;
542     break;
543   case ISD::SETULE:
544     if (LHS.getValueType().isFloatingPoint()) {
545       TCC = SystemZCC::NH;
546       break;
547     }
548     isUnsigned = true;   // FALLTHROUGH
549   case ISD::SETLE:
550   case ISD::SETOLE:
551     TCC = SystemZCC::LE;
552     break;
553   case ISD::SETUGE:
554     if (LHS.getValueType().isFloatingPoint()) {
555       TCC = SystemZCC::NL;
556       break;
557     }
558     isUnsigned = true;   // FALLTHROUGH
559   case ISD::SETGE:
560   case ISD::SETOGE:
561     TCC = SystemZCC::HE;
562     break;
563   case ISD::SETUGT:
564     if (LHS.getValueType().isFloatingPoint()) {
565       TCC = SystemZCC::NLE;
566       break;
567     }
568     isUnsigned = true;  // FALLTHROUGH
569   case ISD::SETGT:
570   case ISD::SETOGT:
571     TCC = SystemZCC::H;
572     break;
573   case ISD::SETULT:
574     if (LHS.getValueType().isFloatingPoint()) {
575       TCC = SystemZCC::NHE;
576       break;
577     }
578     isUnsigned = true;  // FALLTHROUGH
579   case ISD::SETLT:
580   case ISD::SETOLT:
581     TCC = SystemZCC::L;
582     break;
583   }
584
585   SystemZCC = DAG.getConstant(TCC, MVT::i32);
586
587   DebugLoc dl = LHS.getDebugLoc();
588   return DAG.getNode((isUnsigned ? SystemZISD::UCMP : SystemZISD::CMP),
589                      dl, MVT::Flag, LHS, RHS);
590 }
591
592
593 SDValue SystemZTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
594   SDValue Chain = Op.getOperand(0);
595   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
596   SDValue LHS   = Op.getOperand(2);
597   SDValue RHS   = Op.getOperand(3);
598   SDValue Dest  = Op.getOperand(4);
599   DebugLoc dl   = Op.getDebugLoc();
600
601   SDValue SystemZCC;
602   SDValue Flag = EmitCmp(LHS, RHS, CC, SystemZCC, DAG);
603   return DAG.getNode(SystemZISD::BRCOND, dl, Op.getValueType(),
604                      Chain, Dest, SystemZCC, Flag);
605 }
606
607 SDValue SystemZTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
608   SDValue LHS    = Op.getOperand(0);
609   SDValue RHS    = Op.getOperand(1);
610   SDValue TrueV  = Op.getOperand(2);
611   SDValue FalseV = Op.getOperand(3);
612   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
613   DebugLoc dl   = Op.getDebugLoc();
614
615   SDValue SystemZCC;
616   SDValue Flag = EmitCmp(LHS, RHS, CC, SystemZCC, DAG);
617
618   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
619   SmallVector<SDValue, 4> Ops;
620   Ops.push_back(TrueV);
621   Ops.push_back(FalseV);
622   Ops.push_back(SystemZCC);
623   Ops.push_back(Flag);
624
625   return DAG.getNode(SystemZISD::SELECT, dl, VTs, &Ops[0], Ops.size());
626 }
627
628 SDValue SystemZTargetLowering::LowerGlobalAddress(SDValue Op,
629                                                   SelectionDAG &DAG) {
630   DebugLoc dl = Op.getDebugLoc();
631   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
632   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
633
634   bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
635   bool ExtraLoadRequired =
636     Subtarget.GVRequiresExtraLoad(GV, getTargetMachine(), false);
637
638   SDValue Result;
639   if (!IsPic && !ExtraLoadRequired) {
640     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
641     Offset = 0;
642   } else {
643     unsigned char OpFlags = 0;
644     if (ExtraLoadRequired)
645       OpFlags = SystemZII::MO_GOTENT;
646
647     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
648   }
649
650   Result = DAG.getNode(SystemZISD::PCRelativeWrapper, dl,
651                        getPointerTy(), Result);
652
653   if (ExtraLoadRequired)
654     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
655                          PseudoSourceValue::getGOT(), 0);
656
657   // If there was a non-zero offset that we didn't fold, create an explicit
658   // addition for it.
659   if (Offset != 0)
660     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
661                          DAG.getConstant(Offset, getPointerTy()));
662
663   return Result;
664 }
665
666 // FIXME: PIC here
667 SDValue SystemZTargetLowering::LowerJumpTable(SDValue Op,
668                                               SelectionDAG &DAG) {
669   DebugLoc dl = Op.getDebugLoc();
670   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
671   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
672
673   return DAG.getNode(SystemZISD::PCRelativeWrapper, dl, getPointerTy(), Result);
674 }
675
676
677 // FIXME: PIC here
678 // FIXME: This is just dirty hack. We need to lower cpool properly
679 SDValue SystemZTargetLowering::LowerConstantPool(SDValue Op,
680                                                  SelectionDAG &DAG) {
681   DebugLoc dl = Op.getDebugLoc();
682   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
683
684   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
685                                              CP->getAlignment(),
686                                              CP->getOffset());
687
688   return DAG.getNode(SystemZISD::PCRelativeWrapper, dl, getPointerTy(), Result);
689 }
690
691 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
692   switch (Opcode) {
693   case SystemZISD::RET_FLAG:           return "SystemZISD::RET_FLAG";
694   case SystemZISD::CALL:               return "SystemZISD::CALL";
695   case SystemZISD::BRCOND:             return "SystemZISD::BRCOND";
696   case SystemZISD::CMP:                return "SystemZISD::CMP";
697   case SystemZISD::UCMP:               return "SystemZISD::UCMP";
698   case SystemZISD::SELECT:             return "SystemZISD::SELECT";
699   case SystemZISD::PCRelativeWrapper:  return "SystemZISD::PCRelativeWrapper";
700   default: return NULL;
701   }
702 }
703
704 //===----------------------------------------------------------------------===//
705 //  Other Lowering Code
706 //===----------------------------------------------------------------------===//
707
708 MachineBasicBlock*
709 SystemZTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
710                                                    MachineBasicBlock *BB) const {
711   const SystemZInstrInfo &TII = *TM.getInstrInfo();
712   DebugLoc dl = MI->getDebugLoc();
713   assert((MI->getOpcode() == SystemZ::Select32  ||
714           MI->getOpcode() == SystemZ::SelectF32 ||
715           MI->getOpcode() == SystemZ::Select64  ||
716           MI->getOpcode() == SystemZ::SelectF64) &&
717          "Unexpected instr type to insert");
718
719   // To "insert" a SELECT instruction, we actually have to insert the diamond
720   // control-flow pattern.  The incoming instruction knows the destination vreg
721   // to set, the condition code register to branch on, the true/false values to
722   // select between, and a branch opcode to use.
723   const BasicBlock *LLVM_BB = BB->getBasicBlock();
724   MachineFunction::iterator I = BB;
725   ++I;
726
727   //  thisMBB:
728   //  ...
729   //   TrueVal = ...
730   //   cmpTY ccX, r1, r2
731   //   jCC copy1MBB
732   //   fallthrough --> copy0MBB
733   MachineBasicBlock *thisMBB = BB;
734   MachineFunction *F = BB->getParent();
735   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
736   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
737   SystemZCC::CondCodes CC = (SystemZCC::CondCodes)MI->getOperand(3).getImm();
738   BuildMI(BB, dl, TII.getBrCond(CC)).addMBB(copy1MBB);
739   F->insert(I, copy0MBB);
740   F->insert(I, copy1MBB);
741   // Update machine-CFG edges by transferring all successors of the current
742   // block to the new block which will contain the Phi node for the select.
743   copy1MBB->transferSuccessors(BB);
744   // Next, add the true and fallthrough blocks as its successors.
745   BB->addSuccessor(copy0MBB);
746   BB->addSuccessor(copy1MBB);
747
748   //  copy0MBB:
749   //   %FalseValue = ...
750   //   # fallthrough to copy1MBB
751   BB = copy0MBB;
752
753   // Update machine-CFG edges
754   BB->addSuccessor(copy1MBB);
755
756   //  copy1MBB:
757   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
758   //  ...
759   BB = copy1MBB;
760   BuildMI(BB, dl, TII.get(SystemZ::PHI),
761           MI->getOperand(0).getReg())
762     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
763     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
764
765   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
766   return BB;
767 }