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