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