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