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