AArch64/PowerPC/SystemZ/X86: This patch fixes the interface, usage, and all
[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 "SystemZCallingConv.h"
18 #include "SystemZConstantPoolValue.h"
19 #include "SystemZMachineFunctionInfo.h"
20 #include "SystemZTargetMachine.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25
26 using namespace llvm;
27
28 // Classify VT as either 32 or 64 bit.
29 static bool is32Bit(EVT VT) {
30   switch (VT.getSimpleVT().SimpleTy) {
31   case MVT::i32:
32     return true;
33   case MVT::i64:
34     return false;
35   default:
36     llvm_unreachable("Unsupported type");
37   }
38 }
39
40 // Return a version of MachineOperand that can be safely used before the
41 // final use.
42 static MachineOperand earlyUseOperand(MachineOperand Op) {
43   if (Op.isReg())
44     Op.setIsKill(false);
45   return Op;
46 }
47
48 SystemZTargetLowering::SystemZTargetLowering(SystemZTargetMachine &tm)
49   : TargetLowering(tm, new TargetLoweringObjectFileELF()),
50     Subtarget(*tm.getSubtargetImpl()), TM(tm) {
51   MVT PtrVT = getPointerTy();
52
53   // Set up the register classes.
54   addRegisterClass(MVT::i32,  &SystemZ::GR32BitRegClass);
55   addRegisterClass(MVT::i64,  &SystemZ::GR64BitRegClass);
56   addRegisterClass(MVT::f32,  &SystemZ::FP32BitRegClass);
57   addRegisterClass(MVT::f64,  &SystemZ::FP64BitRegClass);
58   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
59
60   // Compute derived properties from the register classes
61   computeRegisterProperties();
62
63   // Set up special registers.
64   setExceptionPointerRegister(SystemZ::R6D);
65   setExceptionSelectorRegister(SystemZ::R7D);
66   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
67
68   // TODO: It may be better to default to latency-oriented scheduling, however
69   // LLVM's current latency-oriented scheduler can't handle physreg definitions
70   // such as SystemZ has with CC, so set this to the register-pressure
71   // scheduler, because it can.
72   setSchedulingPreference(Sched::RegPressure);
73
74   setBooleanContents(ZeroOrOneBooleanContent);
75   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
76
77   // Instructions are strings of 2-byte aligned 2-byte values.
78   setMinFunctionAlignment(2);
79
80   // Handle operations that are handled in a similar way for all types.
81   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
82        I <= MVT::LAST_FP_VALUETYPE;
83        ++I) {
84     MVT VT = MVT::SimpleValueType(I);
85     if (isTypeLegal(VT)) {
86       // Expand SETCC(X, Y, COND) into SELECT_CC(X, Y, 1, 0, COND).
87       setOperationAction(ISD::SETCC, VT, Expand);
88
89       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
90       setOperationAction(ISD::SELECT, VT, Expand);
91
92       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
93       setOperationAction(ISD::SELECT_CC, VT, Custom);
94       setOperationAction(ISD::BR_CC,     VT, Custom);
95     }
96   }
97
98   // Expand jump table branches as address arithmetic followed by an
99   // indirect jump.
100   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
101
102   // Expand BRCOND into a BR_CC (see above).
103   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
104
105   // Handle integer types.
106   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
107        I <= MVT::LAST_INTEGER_VALUETYPE;
108        ++I) {
109     MVT VT = MVT::SimpleValueType(I);
110     if (isTypeLegal(VT)) {
111       // Expand individual DIV and REMs into DIVREMs.
112       setOperationAction(ISD::SDIV, VT, Expand);
113       setOperationAction(ISD::UDIV, VT, Expand);
114       setOperationAction(ISD::SREM, VT, Expand);
115       setOperationAction(ISD::UREM, VT, Expand);
116       setOperationAction(ISD::SDIVREM, VT, Custom);
117       setOperationAction(ISD::UDIVREM, VT, Custom);
118
119       // Expand ATOMIC_LOAD and ATOMIC_STORE using ATOMIC_CMP_SWAP.
120       // FIXME: probably much too conservative.
121       setOperationAction(ISD::ATOMIC_LOAD,  VT, Expand);
122       setOperationAction(ISD::ATOMIC_STORE, VT, Expand);
123
124       // No special instructions for these.
125       setOperationAction(ISD::CTPOP,           VT, Expand);
126       setOperationAction(ISD::CTTZ,            VT, Expand);
127       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
128       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
129       setOperationAction(ISD::ROTR,            VT, Expand);
130
131       // Use *MUL_LOHI where possible and a wider multiplication otherwise.
132       setOperationAction(ISD::MULHS, VT, Expand);
133       setOperationAction(ISD::MULHU, VT, Expand);
134
135       // We have instructions for signed but not unsigned FP conversion.
136       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
137     }
138   }
139
140   // Type legalization will convert 8- and 16-bit atomic operations into
141   // forms that operate on i32s (but still keeping the original memory VT).
142   // Lower them into full i32 operations.
143   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
144   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
145   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
146   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
147   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
148   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
149   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
150   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
151   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
152   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
153   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
154   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
155
156   // We have instructions for signed but not unsigned FP conversion.
157   // Handle unsigned 32-bit types as signed 64-bit types.
158   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
159   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
160
161   // We have native support for a 64-bit CTLZ, via FLOGR.
162   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
163   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
164
165   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
166   setOperationAction(ISD::OR, MVT::i64, Custom);
167
168   // The architecture has 32-bit SMUL_LOHI and UMUL_LOHI (MR and MLR),
169   // but they aren't really worth using.  There is no 64-bit SMUL_LOHI,
170   // but there is a 64-bit UMUL_LOHI: MLGR.
171   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
172   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
173   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
174   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Custom);
175
176   // FIXME: Can we support these natively?
177   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
178   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
179   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
180
181   // We have native instructions for i8, i16 and i32 extensions, but not i1.
182   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
183   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
184   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
185   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
186
187   // Handle the various types of symbolic address.
188   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
189   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
190   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
191   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
192   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
193
194   // We need to handle dynamic allocations specially because of the
195   // 160-byte area at the bottom of the stack.
196   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
197
198   // Use custom expanders so that we can force the function to use
199   // a frame pointer.
200   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
201   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
202
203   // Handle floating-point types.
204   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
205        I <= MVT::LAST_FP_VALUETYPE;
206        ++I) {
207     MVT VT = MVT::SimpleValueType(I);
208     if (isTypeLegal(VT)) {
209       // We can use FI for FRINT.
210       setOperationAction(ISD::FRINT, VT, Legal);
211
212       // No special instructions for these.
213       setOperationAction(ISD::FSIN, VT, Expand);
214       setOperationAction(ISD::FCOS, VT, Expand);
215       setOperationAction(ISD::FREM, VT, Expand);
216     }
217   }
218
219   // We have fused multiply-addition for f32 and f64 but not f128.
220   setOperationAction(ISD::FMA, MVT::f32,  Legal);
221   setOperationAction(ISD::FMA, MVT::f64,  Legal);
222   setOperationAction(ISD::FMA, MVT::f128, Expand);
223
224   // Needed so that we don't try to implement f128 constant loads using
225   // a load-and-extend of a f80 constant (in cases where the constant
226   // would fit in an f80).
227   setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
228
229   // Floating-point truncation and stores need to be done separately.
230   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
231   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
232   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
233
234   // We have 64-bit FPR<->GPR moves, but need special handling for
235   // 32-bit forms.
236   setOperationAction(ISD::BITCAST, MVT::i32, Custom);
237   setOperationAction(ISD::BITCAST, MVT::f32, Custom);
238
239   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
240   // structure, but VAEND is a no-op.
241   setOperationAction(ISD::VASTART, MVT::Other, Custom);
242   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
243   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
244
245   // We want to use MVC in preference to even a single load/store pair.
246   MaxStoresPerMemcpy = 0;
247   MaxStoresPerMemcpyOptSize = 0;
248
249   // The main memset sequence is a byte store followed by an MVC.
250   // Two STC or MV..I stores win over that, but the kind of fused stores
251   // generated by target-independent code don't when the byte value is
252   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
253   // than "STC;MVC".  Handle the choice in target-specific code instead.
254   MaxStoresPerMemset = 0;
255   MaxStoresPerMemsetOptSize = 0;
256 }
257
258 bool
259 SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
260   VT = VT.getScalarType();
261
262   if (!VT.isSimple())
263     return false;
264
265   switch (VT.getSimpleVT().SimpleTy) {
266   case MVT::f32:
267   case MVT::f64:
268     return true;
269   case MVT::f128:
270     return false;
271   default:
272     break;
273   }
274
275   return false;
276 }
277
278 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
279   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
280   return Imm.isZero() || Imm.isNegZero();
281 }
282
283 bool SystemZTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
284                                                           bool *Fast) const {
285   // Unaligned accesses should never be slower than the expanded version.
286   // We check specifically for aligned accesses in the few cases where
287   // they are required.
288   if (Fast)
289     *Fast = true;
290   return true;
291 }
292   
293 //===----------------------------------------------------------------------===//
294 // Inline asm support
295 //===----------------------------------------------------------------------===//
296
297 TargetLowering::ConstraintType
298 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
299   if (Constraint.size() == 1) {
300     switch (Constraint[0]) {
301     case 'a': // Address register
302     case 'd': // Data register (equivalent to 'r')
303     case 'f': // Floating-point register
304     case 'r': // General-purpose register
305       return C_RegisterClass;
306
307     case 'Q': // Memory with base and unsigned 12-bit displacement
308     case 'R': // Likewise, plus an index
309     case 'S': // Memory with base and signed 20-bit displacement
310     case 'T': // Likewise, plus an index
311     case 'm': // Equivalent to 'T'.
312       return C_Memory;
313
314     case 'I': // Unsigned 8-bit constant
315     case 'J': // Unsigned 12-bit constant
316     case 'K': // Signed 16-bit constant
317     case 'L': // Signed 20-bit displacement (on all targets we support)
318     case 'M': // 0x7fffffff
319       return C_Other;
320
321     default:
322       break;
323     }
324   }
325   return TargetLowering::getConstraintType(Constraint);
326 }
327
328 TargetLowering::ConstraintWeight SystemZTargetLowering::
329 getSingleConstraintMatchWeight(AsmOperandInfo &info,
330                                const char *constraint) const {
331   ConstraintWeight weight = CW_Invalid;
332   Value *CallOperandVal = info.CallOperandVal;
333   // If we don't have a value, we can't do a match,
334   // but allow it at the lowest weight.
335   if (CallOperandVal == NULL)
336     return CW_Default;
337   Type *type = CallOperandVal->getType();
338   // Look at the constraint type.
339   switch (*constraint) {
340   default:
341     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
342     break;
343
344   case 'a': // Address register
345   case 'd': // Data register (equivalent to 'r')
346   case 'r': // General-purpose register
347     if (CallOperandVal->getType()->isIntegerTy())
348       weight = CW_Register;
349     break;
350
351   case 'f': // Floating-point register
352     if (type->isFloatingPointTy())
353       weight = CW_Register;
354     break;
355
356   case 'I': // Unsigned 8-bit constant
357     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
358       if (isUInt<8>(C->getZExtValue()))
359         weight = CW_Constant;
360     break;
361
362   case 'J': // Unsigned 12-bit constant
363     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
364       if (isUInt<12>(C->getZExtValue()))
365         weight = CW_Constant;
366     break;
367
368   case 'K': // Signed 16-bit constant
369     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
370       if (isInt<16>(C->getSExtValue()))
371         weight = CW_Constant;
372     break;
373
374   case 'L': // Signed 20-bit displacement (on all targets we support)
375     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
376       if (isInt<20>(C->getSExtValue()))
377         weight = CW_Constant;
378     break;
379
380   case 'M': // 0x7fffffff
381     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
382       if (C->getZExtValue() == 0x7fffffff)
383         weight = CW_Constant;
384     break;
385   }
386   return weight;
387 }
388
389 std::pair<unsigned, const TargetRegisterClass *> SystemZTargetLowering::
390 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const {
391   if (Constraint.size() == 1) {
392     // GCC Constraint Letters
393     switch (Constraint[0]) {
394     default: break;
395     case 'd': // Data register (equivalent to 'r')
396     case 'r': // General-purpose register
397       if (VT == MVT::i64)
398         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
399       else if (VT == MVT::i128)
400         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
401       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
402
403     case 'a': // Address register
404       if (VT == MVT::i64)
405         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
406       else if (VT == MVT::i128)
407         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
408       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
409
410     case 'f': // Floating-point register
411       if (VT == MVT::f64)
412         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
413       else if (VT == MVT::f128)
414         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
415       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
416     }
417   }
418   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
419 }
420
421 void SystemZTargetLowering::
422 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
423                              std::vector<SDValue> &Ops,
424                              SelectionDAG &DAG) const {
425   // Only support length 1 constraints for now.
426   if (Constraint.length() == 1) {
427     switch (Constraint[0]) {
428     case 'I': // Unsigned 8-bit constant
429       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
430         if (isUInt<8>(C->getZExtValue()))
431           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
432                                               Op.getValueType()));
433       return;
434
435     case 'J': // Unsigned 12-bit constant
436       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
437         if (isUInt<12>(C->getZExtValue()))
438           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
439                                               Op.getValueType()));
440       return;
441
442     case 'K': // Signed 16-bit constant
443       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
444         if (isInt<16>(C->getSExtValue()))
445           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
446                                               Op.getValueType()));
447       return;
448
449     case 'L': // Signed 20-bit displacement (on all targets we support)
450       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
451         if (isInt<20>(C->getSExtValue()))
452           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
453                                               Op.getValueType()));
454       return;
455
456     case 'M': // 0x7fffffff
457       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
458         if (C->getZExtValue() == 0x7fffffff)
459           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
460                                               Op.getValueType()));
461       return;
462     }
463   }
464   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
465 }
466
467 //===----------------------------------------------------------------------===//
468 // Calling conventions
469 //===----------------------------------------------------------------------===//
470
471 #include "SystemZGenCallingConv.inc"
472
473 // Value is a value that has been passed to us in the location described by VA
474 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
475 // any loads onto Chain.
476 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
477                                    CCValAssign &VA, SDValue Chain,
478                                    SDValue Value) {
479   // If the argument has been promoted from a smaller type, insert an
480   // assertion to capture this.
481   if (VA.getLocInfo() == CCValAssign::SExt)
482     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
483                         DAG.getValueType(VA.getValVT()));
484   else if (VA.getLocInfo() == CCValAssign::ZExt)
485     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
486                         DAG.getValueType(VA.getValVT()));
487
488   if (VA.isExtInLoc())
489     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
490   else if (VA.getLocInfo() == CCValAssign::Indirect)
491     Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
492                         MachinePointerInfo(), false, false, false, 0);
493   else
494     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
495   return Value;
496 }
497
498 // Value is a value of type VA.getValVT() that we need to copy into
499 // the location described by VA.  Return a copy of Value converted to
500 // VA.getValVT().  The caller is responsible for handling indirect values.
501 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
502                                    CCValAssign &VA, SDValue Value) {
503   switch (VA.getLocInfo()) {
504   case CCValAssign::SExt:
505     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
506   case CCValAssign::ZExt:
507     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
508   case CCValAssign::AExt:
509     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
510   case CCValAssign::Full:
511     return Value;
512   default:
513     llvm_unreachable("Unhandled getLocInfo()");
514   }
515 }
516
517 SDValue SystemZTargetLowering::
518 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
519                      const SmallVectorImpl<ISD::InputArg> &Ins,
520                      SDLoc DL, SelectionDAG &DAG,
521                      SmallVectorImpl<SDValue> &InVals) const {
522   MachineFunction &MF = DAG.getMachineFunction();
523   MachineFrameInfo *MFI = MF.getFrameInfo();
524   MachineRegisterInfo &MRI = MF.getRegInfo();
525   SystemZMachineFunctionInfo *FuncInfo =
526     MF.getInfo<SystemZMachineFunctionInfo>();
527   const SystemZFrameLowering *TFL =
528     static_cast<const SystemZFrameLowering *>(TM.getFrameLowering());
529
530   // Assign locations to all of the incoming arguments.
531   SmallVector<CCValAssign, 16> ArgLocs;
532   CCState CCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
533   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
534
535   unsigned NumFixedGPRs = 0;
536   unsigned NumFixedFPRs = 0;
537   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
538     SDValue ArgValue;
539     CCValAssign &VA = ArgLocs[I];
540     EVT LocVT = VA.getLocVT();
541     if (VA.isRegLoc()) {
542       // Arguments passed in registers
543       const TargetRegisterClass *RC;
544       switch (LocVT.getSimpleVT().SimpleTy) {
545       default:
546         // Integers smaller than i64 should be promoted to i64.
547         llvm_unreachable("Unexpected argument type");
548       case MVT::i32:
549         NumFixedGPRs += 1;
550         RC = &SystemZ::GR32BitRegClass;
551         break;
552       case MVT::i64:
553         NumFixedGPRs += 1;
554         RC = &SystemZ::GR64BitRegClass;
555         break;
556       case MVT::f32:
557         NumFixedFPRs += 1;
558         RC = &SystemZ::FP32BitRegClass;
559         break;
560       case MVT::f64:
561         NumFixedFPRs += 1;
562         RC = &SystemZ::FP64BitRegClass;
563         break;
564       }
565
566       unsigned VReg = MRI.createVirtualRegister(RC);
567       MRI.addLiveIn(VA.getLocReg(), VReg);
568       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
569     } else {
570       assert(VA.isMemLoc() && "Argument not register or memory");
571
572       // Create the frame index object for this incoming parameter.
573       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
574                                       VA.getLocMemOffset(), true);
575
576       // Create the SelectionDAG nodes corresponding to a load
577       // from this parameter.  Unpromoted ints and floats are
578       // passed as right-justified 8-byte values.
579       EVT PtrVT = getPointerTy();
580       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
581       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
582         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4));
583       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
584                              MachinePointerInfo::getFixedStack(FI),
585                              false, false, false, 0);
586     }
587
588     // Convert the value of the argument register into the value that's
589     // being passed.
590     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
591   }
592
593   if (IsVarArg) {
594     // Save the number of non-varargs registers for later use by va_start, etc.
595     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
596     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
597
598     // Likewise the address (in the form of a frame index) of where the
599     // first stack vararg would be.  The 1-byte size here is arbitrary.
600     int64_t StackSize = CCInfo.getNextStackOffset();
601     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
602
603     // ...and a similar frame index for the caller-allocated save area
604     // that will be used to store the incoming registers.
605     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
606     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
607     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
608
609     // Store the FPR varargs in the reserved frame slots.  (We store the
610     // GPRs as part of the prologue.)
611     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
612       SDValue MemOps[SystemZ::NumArgFPRs];
613       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
614         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
615         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
616         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
617         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
618                                      &SystemZ::FP64BitRegClass);
619         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
620         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
621                                  MachinePointerInfo::getFixedStack(FI),
622                                  false, false, 0);
623
624       }
625       // Join the stores, which are independent of one another.
626       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
627                           &MemOps[NumFixedFPRs],
628                           SystemZ::NumArgFPRs - NumFixedFPRs);
629     }
630   }
631
632   return Chain;
633 }
634
635 SDValue
636 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
637                                  SmallVectorImpl<SDValue> &InVals) const {
638   SelectionDAG &DAG = CLI.DAG;
639   SDLoc &DL = CLI.DL;
640   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
641   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
642   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
643   SDValue Chain = CLI.Chain;
644   SDValue Callee = CLI.Callee;
645   bool &isTailCall = CLI.IsTailCall;
646   CallingConv::ID CallConv = CLI.CallConv;
647   bool IsVarArg = CLI.IsVarArg;
648   MachineFunction &MF = DAG.getMachineFunction();
649   EVT PtrVT = getPointerTy();
650
651   // SystemZ target does not yet support tail call optimization.
652   isTailCall = false;
653
654   // Analyze the operands of the call, assigning locations to each operand.
655   SmallVector<CCValAssign, 16> ArgLocs;
656   CCState ArgCCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
657   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
658
659   // Get a count of how many bytes are to be pushed on the stack.
660   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
661
662   // Mark the start of the call.
663   Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, PtrVT, true),
664                                DL);
665
666   // Copy argument values to their designated locations.
667   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
668   SmallVector<SDValue, 8> MemOpChains;
669   SDValue StackPtr;
670   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
671     CCValAssign &VA = ArgLocs[I];
672     SDValue ArgValue = OutVals[I];
673
674     if (VA.getLocInfo() == CCValAssign::Indirect) {
675       // Store the argument in a stack slot and pass its address.
676       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
677       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
678       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
679                                          MachinePointerInfo::getFixedStack(FI),
680                                          false, false, 0));
681       ArgValue = SpillSlot;
682     } else
683       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
684
685     if (VA.isRegLoc())
686       // Queue up the argument copies and emit them at the end.
687       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
688     else {
689       assert(VA.isMemLoc() && "Argument not register or memory");
690
691       // Work out the address of the stack slot.  Unpromoted ints and
692       // floats are passed as right-justified 8-byte values.
693       if (!StackPtr.getNode())
694         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
695       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
696       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
697         Offset += 4;
698       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
699                                     DAG.getIntPtrConstant(Offset));
700
701       // Emit the store.
702       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
703                                          MachinePointerInfo(),
704                                          false, false, 0));
705     }
706   }
707
708   // Join the stores, which are independent of one another.
709   if (!MemOpChains.empty())
710     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
711                         &MemOpChains[0], MemOpChains.size());
712
713   // Build a sequence of copy-to-reg nodes, chained and glued together.
714   SDValue Glue;
715   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
716     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
717                              RegsToPass[I].second, Glue);
718     Glue = Chain.getValue(1);
719   }
720
721   // Accept direct calls by converting symbolic call addresses to the
722   // associated Target* opcodes.
723   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
724     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
725     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
726   } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
727     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
728     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
729   }
730
731   // The first call operand is the chain and the second is the target address.
732   SmallVector<SDValue, 8> Ops;
733   Ops.push_back(Chain);
734   Ops.push_back(Callee);
735
736   // Add argument registers to the end of the list so that they are
737   // known live into the call.
738   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
739     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
740                                   RegsToPass[I].second.getValueType()));
741
742   // Glue the call to the argument copies, if any.
743   if (Glue.getNode())
744     Ops.push_back(Glue);
745
746   // Emit the call.
747   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
748   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
749   Glue = Chain.getValue(1);
750
751   // Mark the end of the call, which is glued to the call itself.
752   Chain = DAG.getCALLSEQ_END(Chain,
753                              DAG.getConstant(NumBytes, PtrVT, true),
754                              DAG.getConstant(0, PtrVT, true),
755                              Glue, DL);
756   Glue = Chain.getValue(1);
757
758   // Assign locations to each value returned by this call.
759   SmallVector<CCValAssign, 16> RetLocs;
760   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
761   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
762
763   // Copy all of the result registers out of their specified physreg.
764   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
765     CCValAssign &VA = RetLocs[I];
766
767     // Copy the value out, gluing the copy to the end of the call sequence.
768     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
769                                           VA.getLocVT(), Glue);
770     Chain = RetValue.getValue(1);
771     Glue = RetValue.getValue(2);
772
773     // Convert the value of the return register into the value that's
774     // being returned.
775     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
776   }
777
778   return Chain;
779 }
780
781 SDValue
782 SystemZTargetLowering::LowerReturn(SDValue Chain,
783                                    CallingConv::ID CallConv, bool IsVarArg,
784                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
785                                    const SmallVectorImpl<SDValue> &OutVals,
786                                    SDLoc DL, SelectionDAG &DAG) const {
787   MachineFunction &MF = DAG.getMachineFunction();
788
789   // Assign locations to each returned value.
790   SmallVector<CCValAssign, 16> RetLocs;
791   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
792   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
793
794   // Quick exit for void returns
795   if (RetLocs.empty())
796     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
797
798   // Copy the result values into the output registers.
799   SDValue Glue;
800   SmallVector<SDValue, 4> RetOps;
801   RetOps.push_back(Chain);
802   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
803     CCValAssign &VA = RetLocs[I];
804     SDValue RetValue = OutVals[I];
805
806     // Make the return register live on exit.
807     assert(VA.isRegLoc() && "Can only return in registers!");
808
809     // Promote the value as required.
810     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
811
812     // Chain and glue the copies together.
813     unsigned Reg = VA.getLocReg();
814     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
815     Glue = Chain.getValue(1);
816     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
817   }
818
819   // Update chain and glue.
820   RetOps[0] = Chain;
821   if (Glue.getNode())
822     RetOps.push_back(Glue);
823
824   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other,
825                      RetOps.data(), RetOps.size());
826 }
827
828 // CC is a comparison that will be implemented using an integer or
829 // floating-point comparison.  Return the condition code mask for
830 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
831 // unsigned comparisons and clear for signed ones.  In the floating-point
832 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
833 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
834 #define CONV(X) \
835   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
836   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
837   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
838
839   switch (CC) {
840   default:
841     llvm_unreachable("Invalid integer condition!");
842
843   CONV(EQ);
844   CONV(NE);
845   CONV(GT);
846   CONV(GE);
847   CONV(LT);
848   CONV(LE);
849
850   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
851   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
852   }
853 #undef CONV
854 }
855
856 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
857 // is suitable for CLI(Y), CHHSI or CLHHSI, adjust the operands as necessary.
858 static void adjustSubwordCmp(SelectionDAG &DAG, bool &IsUnsigned,
859                              SDValue &CmpOp0, SDValue &CmpOp1,
860                              unsigned &CCMask) {
861   // For us to make any changes, it must a comparison between a single-use
862   // load and a constant.
863   if (!CmpOp0.hasOneUse() ||
864       CmpOp0.getOpcode() != ISD::LOAD ||
865       CmpOp1.getOpcode() != ISD::Constant)
866     return;
867
868   // We must have an 8- or 16-bit load.
869   LoadSDNode *Load = cast<LoadSDNode>(CmpOp0);
870   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
871   if (NumBits != 8 && NumBits != 16)
872     return;
873
874   // The load must be an extending one and the constant must be within the
875   // range of the unextended value.
876   ConstantSDNode *Constant = cast<ConstantSDNode>(CmpOp1);
877   uint64_t Value = Constant->getZExtValue();
878   uint64_t Mask = (1 << NumBits) - 1;
879   if (Load->getExtensionType() == ISD::SEXTLOAD) {
880     int64_t SignedValue = Constant->getSExtValue();
881     if (uint64_t(SignedValue) + (1ULL << (NumBits - 1)) > Mask)
882       return;
883     // Unsigned comparison between two sign-extended values is equivalent
884     // to unsigned comparison between two zero-extended values.
885     if (IsUnsigned)
886       Value &= Mask;
887     else if (CCMask == SystemZ::CCMASK_CMP_EQ ||
888              CCMask == SystemZ::CCMASK_CMP_NE)
889       // Any choice of IsUnsigned is OK for equality comparisons.
890       // We could use either CHHSI or CLHHSI for 16-bit comparisons,
891       // but since we use CLHHSI for zero extensions, it seems better
892       // to be consistent and do the same here.
893       Value &= Mask, IsUnsigned = true;
894     else if (NumBits == 8) {
895       // Try to treat the comparison as unsigned, so that we can use CLI.
896       // Adjust CCMask and Value as necessary.
897       if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_LT)
898         // Test whether the high bit of the byte is set.
899         Value = 127, CCMask = SystemZ::CCMASK_CMP_GT, IsUnsigned = true;
900       else if (SignedValue == -1 && CCMask == SystemZ::CCMASK_CMP_GT)
901         // Test whether the high bit of the byte is clear.
902         Value = 128, CCMask = SystemZ::CCMASK_CMP_LT, IsUnsigned = true;
903       else
904         // No instruction exists for this combination.
905         return;
906     }
907   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
908     if (Value > Mask)
909       return;
910     // Signed comparison between two zero-extended values is equivalent
911     // to unsigned comparison.
912     IsUnsigned = true;
913   } else
914     return;
915
916   // Make sure that the first operand is an i32 of the right extension type.
917   ISD::LoadExtType ExtType = IsUnsigned ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
918   if (CmpOp0.getValueType() != MVT::i32 ||
919       Load->getExtensionType() != ExtType)
920     CmpOp0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
921                             Load->getChain(), Load->getBasePtr(),
922                             Load->getPointerInfo(), Load->getMemoryVT(),
923                             Load->isVolatile(), Load->isNonTemporal(),
924                             Load->getAlignment());
925
926   // Make sure that the second operand is an i32 with the right value.
927   if (CmpOp1.getValueType() != MVT::i32 ||
928       Value != Constant->getZExtValue())
929     CmpOp1 = DAG.getConstant(Value, MVT::i32);
930 }
931
932 // Return true if a comparison described by CCMask, CmpOp0 and CmpOp1
933 // is an equality comparison that is better implemented using unsigned
934 // rather than signed comparison instructions.
935 static bool preferUnsignedComparison(SelectionDAG &DAG, SDValue CmpOp0,
936                                      SDValue CmpOp1, unsigned CCMask) {
937   // The test must be for equality or inequality.
938   if (CCMask != SystemZ::CCMASK_CMP_EQ && CCMask != SystemZ::CCMASK_CMP_NE)
939     return false;
940
941   if (CmpOp1.getOpcode() == ISD::Constant) {
942     uint64_t Value = cast<ConstantSDNode>(CmpOp1)->getSExtValue();
943
944     // If we're comparing with memory, prefer unsigned comparisons for
945     // values that are in the unsigned 16-bit range but not the signed
946     // 16-bit range.  We want to use CLFHSI and CLGHSI.
947     if (CmpOp0.hasOneUse() &&
948         ISD::isNormalLoad(CmpOp0.getNode()) &&
949         (Value >= 32768 && Value < 65536))
950       return true;
951
952     // Use unsigned comparisons for values that are in the CLGFI range
953     // but not in the CGFI range.
954     if (CmpOp0.getValueType() == MVT::i64 && (Value >> 31) == 1)
955       return true;
956
957     return false;
958   }
959
960   // Prefer CL for zero-extended loads.
961   if (CmpOp1.getOpcode() == ISD::ZERO_EXTEND ||
962       ISD::isZEXTLoad(CmpOp1.getNode()))
963     return true;
964
965   // ...and for "in-register" zero extensions.
966   if (CmpOp1.getOpcode() == ISD::AND && CmpOp1.getValueType() == MVT::i64) {
967     SDValue Mask = CmpOp1.getOperand(1);
968     if (Mask.getOpcode() == ISD::Constant &&
969         cast<ConstantSDNode>(Mask)->getZExtValue() == 0xffffffff)
970       return true;
971   }
972
973   return false;
974 }
975
976 // Return a target node that compares CmpOp0 and CmpOp1.  Set CCMask to the
977 // 4-bit condition-code mask for CC.
978 static SDValue emitCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
979                        ISD::CondCode CC, unsigned &CCMask) {
980   bool IsUnsigned = false;
981   CCMask = CCMaskForCondCode(CC);
982   if (!CmpOp0.getValueType().isFloatingPoint()) {
983     IsUnsigned = CCMask & SystemZ::CCMASK_CMP_UO;
984     CCMask &= ~SystemZ::CCMASK_CMP_UO;
985     adjustSubwordCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
986     if (preferUnsignedComparison(DAG, CmpOp0, CmpOp1, CCMask))
987       IsUnsigned = true;
988   }
989
990   SDLoc DL(CmpOp0);
991   return DAG.getNode((IsUnsigned ? SystemZISD::UCMP : SystemZISD::CMP),
992                      DL, MVT::Glue, CmpOp0, CmpOp1);
993 }
994
995 // Lower a binary operation that produces two VT results, one in each
996 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
997 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
998 // on the extended Op0 and (unextended) Op1.  Store the even register result
999 // in Even and the odd register result in Odd.
1000 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1001                              unsigned Extend, unsigned Opcode,
1002                              SDValue Op0, SDValue Op1,
1003                              SDValue &Even, SDValue &Odd) {
1004   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1005   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1006                                SDValue(In128, 0), Op1);
1007   bool Is32Bit = is32Bit(VT);
1008   SDValue SubReg0 = DAG.getTargetConstant(SystemZ::even128(Is32Bit), VT);
1009   SDValue SubReg1 = DAG.getTargetConstant(SystemZ::odd128(Is32Bit), VT);
1010   SDNode *Reg0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1011                                     VT, Result, SubReg0);
1012   SDNode *Reg1 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1013                                     VT, Result, SubReg1);
1014   Even = SDValue(Reg0, 0);
1015   Odd = SDValue(Reg1, 0);
1016 }
1017
1018 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1019   SDValue Chain    = Op.getOperand(0);
1020   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1021   SDValue CmpOp0   = Op.getOperand(2);
1022   SDValue CmpOp1   = Op.getOperand(3);
1023   SDValue Dest     = Op.getOperand(4);
1024   SDLoc DL(Op);
1025
1026   unsigned CCMask;
1027   SDValue Flags = emitCmp(DAG, CmpOp0, CmpOp1, CC, CCMask);
1028   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
1029                      Chain, DAG.getConstant(CCMask, MVT::i32), Dest, Flags);
1030 }
1031
1032 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
1033                                               SelectionDAG &DAG) const {
1034   SDValue CmpOp0   = Op.getOperand(0);
1035   SDValue CmpOp1   = Op.getOperand(1);
1036   SDValue TrueOp   = Op.getOperand(2);
1037   SDValue FalseOp  = Op.getOperand(3);
1038   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1039   SDLoc DL(Op);
1040
1041   unsigned CCMask;
1042   SDValue Flags = emitCmp(DAG, CmpOp0, CmpOp1, CC, CCMask);
1043
1044   SmallVector<SDValue, 4> Ops;
1045   Ops.push_back(TrueOp);
1046   Ops.push_back(FalseOp);
1047   Ops.push_back(DAG.getConstant(CCMask, MVT::i32));
1048   Ops.push_back(Flags);
1049
1050   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1051   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, &Ops[0], Ops.size());
1052 }
1053
1054 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
1055                                                   SelectionDAG &DAG) const {
1056   SDLoc DL(Node);
1057   const GlobalValue *GV = Node->getGlobal();
1058   int64_t Offset = Node->getOffset();
1059   EVT PtrVT = getPointerTy();
1060   Reloc::Model RM = TM.getRelocationModel();
1061   CodeModel::Model CM = TM.getCodeModel();
1062
1063   SDValue Result;
1064   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
1065     // Make sure that the offset is aligned to a halfword.  If it isn't,
1066     // create an "anchor" at the previous 12-bit boundary.
1067     // FIXME check whether there is a better way of handling this.
1068     if (Offset & 1) {
1069       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1070                                           Offset & ~uint64_t(0xfff));
1071       Offset &= 0xfff;
1072     } else {
1073       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Offset);
1074       Offset = 0;
1075     }
1076     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1077   } else {
1078     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
1079     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1080     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
1081                          MachinePointerInfo::getGOT(), false, false, false, 0);
1082   }
1083
1084   // If there was a non-zero offset that we didn't fold, create an explicit
1085   // addition for it.
1086   if (Offset != 0)
1087     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
1088                          DAG.getConstant(Offset, PtrVT));
1089
1090   return Result;
1091 }
1092
1093 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
1094                                                      SelectionDAG &DAG) const {
1095   SDLoc DL(Node);
1096   const GlobalValue *GV = Node->getGlobal();
1097   EVT PtrVT = getPointerTy();
1098   TLSModel::Model model = TM.getTLSModel(GV);
1099
1100   if (model != TLSModel::LocalExec)
1101     llvm_unreachable("only local-exec TLS mode supported");
1102
1103   // The high part of the thread pointer is in access register 0.
1104   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1105                              DAG.getConstant(0, MVT::i32));
1106   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
1107
1108   // The low part of the thread pointer is in access register 1.
1109   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1110                              DAG.getConstant(1, MVT::i32));
1111   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
1112
1113   // Merge them into a single 64-bit address.
1114   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
1115                                     DAG.getConstant(32, PtrVT));
1116   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
1117
1118   // Get the offset of GA from the thread pointer.
1119   SystemZConstantPoolValue *CPV =
1120     SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
1121
1122   // Force the offset into the constant pool and load it from there.
1123   SDValue CPAddr = DAG.getConstantPool(CPV, PtrVT, 8);
1124   SDValue Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1125                                CPAddr, MachinePointerInfo::getConstantPool(),
1126                                false, false, false, 0);
1127
1128   // Add the base and offset together.
1129   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
1130 }
1131
1132 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
1133                                                  SelectionDAG &DAG) const {
1134   SDLoc DL(Node);
1135   const BlockAddress *BA = Node->getBlockAddress();
1136   int64_t Offset = Node->getOffset();
1137   EVT PtrVT = getPointerTy();
1138
1139   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
1140   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1141   return Result;
1142 }
1143
1144 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
1145                                               SelectionDAG &DAG) const {
1146   SDLoc DL(JT);
1147   EVT PtrVT = getPointerTy();
1148   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1149
1150   // Use LARL to load the address of the table.
1151   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1152 }
1153
1154 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
1155                                                  SelectionDAG &DAG) const {
1156   SDLoc DL(CP);
1157   EVT PtrVT = getPointerTy();
1158
1159   SDValue Result;
1160   if (CP->isMachineConstantPoolEntry())
1161     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1162                                        CP->getAlignment());
1163   else
1164     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1165                                        CP->getAlignment(), CP->getOffset());
1166
1167   // Use LARL to load the address of the constant pool entry.
1168   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1169 }
1170
1171 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
1172                                             SelectionDAG &DAG) const {
1173   SDLoc DL(Op);
1174   SDValue In = Op.getOperand(0);
1175   EVT InVT = In.getValueType();
1176   EVT ResVT = Op.getValueType();
1177
1178   SDValue SubReg32 = DAG.getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
1179   SDValue Shift32 = DAG.getConstant(32, MVT::i64);
1180   if (InVT == MVT::i32 && ResVT == MVT::f32) {
1181     SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
1182     SDValue Shift = DAG.getNode(ISD::SHL, DL, MVT::i64, In64, Shift32);
1183     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shift);
1184     SDNode *Out = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1185                                      MVT::f32, Out64, SubReg32);
1186     return SDValue(Out, 0);
1187   }
1188   if (InVT == MVT::f32 && ResVT == MVT::i32) {
1189     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
1190     SDNode *In64 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
1191                                       MVT::f64, SDValue(U64, 0), In, SubReg32);
1192     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, SDValue(In64, 0));
1193     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64, Shift32);
1194     SDValue Out = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
1195     return Out;
1196   }
1197   llvm_unreachable("Unexpected bitcast combination");
1198 }
1199
1200 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
1201                                             SelectionDAG &DAG) const {
1202   MachineFunction &MF = DAG.getMachineFunction();
1203   SystemZMachineFunctionInfo *FuncInfo =
1204     MF.getInfo<SystemZMachineFunctionInfo>();
1205   EVT PtrVT = getPointerTy();
1206
1207   SDValue Chain   = Op.getOperand(0);
1208   SDValue Addr    = Op.getOperand(1);
1209   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1210   SDLoc DL(Op);
1211
1212   // The initial values of each field.
1213   const unsigned NumFields = 4;
1214   SDValue Fields[NumFields] = {
1215     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), PtrVT),
1216     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), PtrVT),
1217     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
1218     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
1219   };
1220
1221   // Store each field into its respective slot.
1222   SDValue MemOps[NumFields];
1223   unsigned Offset = 0;
1224   for (unsigned I = 0; I < NumFields; ++I) {
1225     SDValue FieldAddr = Addr;
1226     if (Offset != 0)
1227       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
1228                               DAG.getIntPtrConstant(Offset));
1229     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
1230                              MachinePointerInfo(SV, Offset),
1231                              false, false, 0);
1232     Offset += 8;
1233   }
1234   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps, NumFields);
1235 }
1236
1237 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
1238                                            SelectionDAG &DAG) const {
1239   SDValue Chain      = Op.getOperand(0);
1240   SDValue DstPtr     = Op.getOperand(1);
1241   SDValue SrcPtr     = Op.getOperand(2);
1242   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
1243   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
1244   SDLoc DL(Op);
1245
1246   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32),
1247                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
1248                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
1249 }
1250
1251 SDValue SystemZTargetLowering::
1252 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
1253   SDValue Chain = Op.getOperand(0);
1254   SDValue Size  = Op.getOperand(1);
1255   SDLoc DL(Op);
1256
1257   unsigned SPReg = getStackPointerRegisterToSaveRestore();
1258
1259   // Get a reference to the stack pointer.
1260   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
1261
1262   // Get the new stack pointer value.
1263   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
1264
1265   // Copy the new stack pointer back.
1266   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
1267
1268   // The allocated data lives above the 160 bytes allocated for the standard
1269   // frame, plus any outgoing stack arguments.  We don't know how much that
1270   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
1271   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
1272   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
1273
1274   SDValue Ops[2] = { Result, Chain };
1275   return DAG.getMergeValues(Ops, 2, DL);
1276 }
1277
1278 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
1279                                               SelectionDAG &DAG) const {
1280   EVT VT = Op.getValueType();
1281   SDLoc DL(Op);
1282   assert(!is32Bit(VT) && "Only support 64-bit UMUL_LOHI");
1283
1284   // UMUL_LOHI64 returns the low result in the odd register and the high
1285   // result in the even register.  UMUL_LOHI is defined to return the
1286   // low half first, so the results are in reverse order.
1287   SDValue Ops[2];
1288   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
1289                    Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1290   return DAG.getMergeValues(Ops, 2, DL);
1291 }
1292
1293 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
1294                                             SelectionDAG &DAG) const {
1295   SDValue Op0 = Op.getOperand(0);
1296   SDValue Op1 = Op.getOperand(1);
1297   EVT VT = Op.getValueType();
1298   SDLoc DL(Op);
1299   unsigned Opcode;
1300
1301   // We use DSGF for 32-bit division.
1302   if (is32Bit(VT)) {
1303     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
1304     Opcode = SystemZISD::SDIVREM32;
1305   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
1306     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
1307     Opcode = SystemZISD::SDIVREM32;
1308   } else    
1309     Opcode = SystemZISD::SDIVREM64;
1310
1311   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
1312   // input is "don't care".  The instruction returns the remainder in
1313   // the even register and the quotient in the odd register.
1314   SDValue Ops[2];
1315   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
1316                    Op0, Op1, Ops[1], Ops[0]);
1317   return DAG.getMergeValues(Ops, 2, DL);
1318 }
1319
1320 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
1321                                             SelectionDAG &DAG) const {
1322   EVT VT = Op.getValueType();
1323   SDLoc DL(Op);
1324
1325   // DL(G) uses a double-width dividend, so we need to clear the even
1326   // register in the GR128 input.  The instruction returns the remainder
1327   // in the even register and the quotient in the odd register.
1328   SDValue Ops[2];
1329   if (is32Bit(VT))
1330     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
1331                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1332   else
1333     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
1334                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1335   return DAG.getMergeValues(Ops, 2, DL);
1336 }
1337
1338 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
1339   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
1340
1341   // Get the known-zero masks for each operand.
1342   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
1343   APInt KnownZero[2], KnownOne[2];
1344   DAG.ComputeMaskedBits(Ops[0], KnownZero[0], KnownOne[0]);
1345   DAG.ComputeMaskedBits(Ops[1], KnownZero[1], KnownOne[1]);
1346
1347   // See if the upper 32 bits of one operand and the lower 32 bits of the
1348   // other are known zero.  They are the low and high operands respectively.
1349   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
1350                        KnownZero[1].getZExtValue() };
1351   unsigned High, Low;
1352   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
1353     High = 1, Low = 0;
1354   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
1355     High = 0, Low = 1;
1356   else
1357     return Op;
1358
1359   SDValue LowOp = Ops[Low];
1360   SDValue HighOp = Ops[High];
1361
1362   // If the high part is a constant, we're better off using IILH.
1363   if (HighOp.getOpcode() == ISD::Constant)
1364     return Op;
1365
1366   // If the low part is a constant that is outside the range of LHI,
1367   // then we're better off using IILF.
1368   if (LowOp.getOpcode() == ISD::Constant) {
1369     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
1370     if (!isInt<16>(Value))
1371       return Op;
1372   }
1373
1374   // Check whether the high part is an AND that doesn't change the
1375   // high 32 bits and just masks out low bits.  We can skip it if so.
1376   if (HighOp.getOpcode() == ISD::AND &&
1377       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
1378     ConstantSDNode *MaskNode = cast<ConstantSDNode>(HighOp.getOperand(1));
1379     uint64_t Mask = MaskNode->getZExtValue() | Masks[High];
1380     if ((Mask >> 32) == 0xffffffff)
1381       HighOp = HighOp.getOperand(0);
1382   }
1383
1384   // Take advantage of the fact that all GR32 operations only change the
1385   // low 32 bits by truncating Low to an i32 and inserting it directly
1386   // using a subreg.  The interesting cases are those where the truncation
1387   // can be folded.
1388   SDLoc DL(Op);
1389   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
1390   SDValue SubReg32 = DAG.getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
1391   SDNode *Result = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
1392                                       MVT::i64, HighOp, Low32, SubReg32);
1393   return SDValue(Result, 0);
1394 }
1395
1396 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
1397 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
1398 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
1399                                                 SelectionDAG &DAG,
1400                                                 unsigned Opcode) const {
1401   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
1402
1403   // 32-bit operations need no code outside the main loop.
1404   EVT NarrowVT = Node->getMemoryVT();
1405   EVT WideVT = MVT::i32;
1406   if (NarrowVT == WideVT)
1407     return Op;
1408
1409   int64_t BitSize = NarrowVT.getSizeInBits();
1410   SDValue ChainIn = Node->getChain();
1411   SDValue Addr = Node->getBasePtr();
1412   SDValue Src2 = Node->getVal();
1413   MachineMemOperand *MMO = Node->getMemOperand();
1414   SDLoc DL(Node);
1415   EVT PtrVT = Addr.getValueType();
1416
1417   // Convert atomic subtracts of constants into additions.
1418   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
1419     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Src2)) {
1420       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
1421       Src2 = DAG.getConstant(-Const->getSExtValue(), Src2.getValueType());
1422     }
1423
1424   // Get the address of the containing word.
1425   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
1426                                     DAG.getConstant(-4, PtrVT));
1427
1428   // Get the number of bits that the word must be rotated left in order
1429   // to bring the field to the top bits of a GR32.
1430   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
1431                                  DAG.getConstant(3, PtrVT));
1432   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
1433
1434   // Get the complementing shift amount, for rotating a field in the top
1435   // bits back to its proper position.
1436   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
1437                                     DAG.getConstant(0, WideVT), BitShift);
1438
1439   // Extend the source operand to 32 bits and prepare it for the inner loop.
1440   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
1441   // operations require the source to be shifted in advance.  (This shift
1442   // can be folded if the source is constant.)  For AND and NAND, the lower
1443   // bits must be set, while for other opcodes they should be left clear.
1444   if (Opcode != SystemZISD::ATOMIC_SWAPW)
1445     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
1446                        DAG.getConstant(32 - BitSize, WideVT));
1447   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
1448       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
1449     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
1450                        DAG.getConstant(uint32_t(-1) >> BitSize, WideVT));
1451
1452   // Construct the ATOMIC_LOADW_* node.
1453   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
1454   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
1455                     DAG.getConstant(BitSize, WideVT) };
1456   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
1457                                              array_lengthof(Ops),
1458                                              NarrowVT, MMO);
1459
1460   // Rotate the result of the final CS so that the field is in the lower
1461   // bits of a GR32, then truncate it.
1462   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
1463                                     DAG.getConstant(BitSize, WideVT));
1464   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
1465
1466   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
1467   return DAG.getMergeValues(RetOps, 2, DL);
1468 }
1469
1470 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
1471 // into a fullword ATOMIC_CMP_SWAPW operation.
1472 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
1473                                                     SelectionDAG &DAG) const {
1474   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
1475
1476   // We have native support for 32-bit compare and swap.
1477   EVT NarrowVT = Node->getMemoryVT();
1478   EVT WideVT = MVT::i32;
1479   if (NarrowVT == WideVT)
1480     return Op;
1481
1482   int64_t BitSize = NarrowVT.getSizeInBits();
1483   SDValue ChainIn = Node->getOperand(0);
1484   SDValue Addr = Node->getOperand(1);
1485   SDValue CmpVal = Node->getOperand(2);
1486   SDValue SwapVal = Node->getOperand(3);
1487   MachineMemOperand *MMO = Node->getMemOperand();
1488   SDLoc DL(Node);
1489   EVT PtrVT = Addr.getValueType();
1490
1491   // Get the address of the containing word.
1492   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
1493                                     DAG.getConstant(-4, PtrVT));
1494
1495   // Get the number of bits that the word must be rotated left in order
1496   // to bring the field to the top bits of a GR32.
1497   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
1498                                  DAG.getConstant(3, PtrVT));
1499   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
1500
1501   // Get the complementing shift amount, for rotating a field in the top
1502   // bits back to its proper position.
1503   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
1504                                     DAG.getConstant(0, WideVT), BitShift);
1505
1506   // Construct the ATOMIC_CMP_SWAPW node.
1507   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
1508   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
1509                     NegBitShift, DAG.getConstant(BitSize, WideVT) };
1510   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
1511                                              VTList, Ops, array_lengthof(Ops),
1512                                              NarrowVT, MMO);
1513   return AtomicOp;
1514 }
1515
1516 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
1517                                               SelectionDAG &DAG) const {
1518   MachineFunction &MF = DAG.getMachineFunction();
1519   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
1520   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
1521                             SystemZ::R15D, Op.getValueType());
1522 }
1523
1524 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
1525                                                  SelectionDAG &DAG) const {
1526   MachineFunction &MF = DAG.getMachineFunction();
1527   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
1528   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
1529                           SystemZ::R15D, Op.getOperand(1));
1530 }
1531
1532 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
1533                                               SelectionDAG &DAG) const {
1534   switch (Op.getOpcode()) {
1535   case ISD::BR_CC:
1536     return lowerBR_CC(Op, DAG);
1537   case ISD::SELECT_CC:
1538     return lowerSELECT_CC(Op, DAG);
1539   case ISD::GlobalAddress:
1540     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
1541   case ISD::GlobalTLSAddress:
1542     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
1543   case ISD::BlockAddress:
1544     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
1545   case ISD::JumpTable:
1546     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
1547   case ISD::ConstantPool:
1548     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
1549   case ISD::BITCAST:
1550     return lowerBITCAST(Op, DAG);
1551   case ISD::VASTART:
1552     return lowerVASTART(Op, DAG);
1553   case ISD::VACOPY:
1554     return lowerVACOPY(Op, DAG);
1555   case ISD::DYNAMIC_STACKALLOC:
1556     return lowerDYNAMIC_STACKALLOC(Op, DAG);
1557   case ISD::UMUL_LOHI:
1558     return lowerUMUL_LOHI(Op, DAG);
1559   case ISD::SDIVREM:
1560     return lowerSDIVREM(Op, DAG);
1561   case ISD::UDIVREM:
1562     return lowerUDIVREM(Op, DAG);
1563   case ISD::OR:
1564     return lowerOR(Op, DAG);
1565   case ISD::ATOMIC_SWAP:
1566     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_SWAPW);
1567   case ISD::ATOMIC_LOAD_ADD:
1568     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
1569   case ISD::ATOMIC_LOAD_SUB:
1570     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
1571   case ISD::ATOMIC_LOAD_AND:
1572     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
1573   case ISD::ATOMIC_LOAD_OR:
1574     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
1575   case ISD::ATOMIC_LOAD_XOR:
1576     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
1577   case ISD::ATOMIC_LOAD_NAND:
1578     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
1579   case ISD::ATOMIC_LOAD_MIN:
1580     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
1581   case ISD::ATOMIC_LOAD_MAX:
1582     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
1583   case ISD::ATOMIC_LOAD_UMIN:
1584     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
1585   case ISD::ATOMIC_LOAD_UMAX:
1586     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
1587   case ISD::ATOMIC_CMP_SWAP:
1588     return lowerATOMIC_CMP_SWAP(Op, DAG);
1589   case ISD::STACKSAVE:
1590     return lowerSTACKSAVE(Op, DAG);
1591   case ISD::STACKRESTORE:
1592     return lowerSTACKRESTORE(Op, DAG);
1593   default:
1594     llvm_unreachable("Unexpected node to lower");
1595   }
1596 }
1597
1598 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
1599 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
1600   switch (Opcode) {
1601     OPCODE(RET_FLAG);
1602     OPCODE(CALL);
1603     OPCODE(PCREL_WRAPPER);
1604     OPCODE(CMP);
1605     OPCODE(UCMP);
1606     OPCODE(BR_CCMASK);
1607     OPCODE(SELECT_CCMASK);
1608     OPCODE(ADJDYNALLOC);
1609     OPCODE(EXTRACT_ACCESS);
1610     OPCODE(UMUL_LOHI64);
1611     OPCODE(SDIVREM64);
1612     OPCODE(UDIVREM32);
1613     OPCODE(UDIVREM64);
1614     OPCODE(MVC);
1615     OPCODE(ATOMIC_SWAPW);
1616     OPCODE(ATOMIC_LOADW_ADD);
1617     OPCODE(ATOMIC_LOADW_SUB);
1618     OPCODE(ATOMIC_LOADW_AND);
1619     OPCODE(ATOMIC_LOADW_OR);
1620     OPCODE(ATOMIC_LOADW_XOR);
1621     OPCODE(ATOMIC_LOADW_NAND);
1622     OPCODE(ATOMIC_LOADW_MIN);
1623     OPCODE(ATOMIC_LOADW_MAX);
1624     OPCODE(ATOMIC_LOADW_UMIN);
1625     OPCODE(ATOMIC_LOADW_UMAX);
1626     OPCODE(ATOMIC_CMP_SWAPW);
1627   }
1628   return NULL;
1629 #undef OPCODE
1630 }
1631
1632 //===----------------------------------------------------------------------===//
1633 // Custom insertion
1634 //===----------------------------------------------------------------------===//
1635
1636 // Create a new basic block after MBB.
1637 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
1638   MachineFunction &MF = *MBB->getParent();
1639   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
1640   MF.insert(llvm::next(MachineFunction::iterator(MBB)), NewMBB);
1641   return NewMBB;
1642 }
1643
1644 // Split MBB after MI and return the new block (the one that contains
1645 // instructions after MI).
1646 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
1647                                           MachineBasicBlock *MBB) {
1648   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
1649   NewMBB->splice(NewMBB->begin(), MBB,
1650                  llvm::next(MachineBasicBlock::iterator(MI)),
1651                  MBB->end());
1652   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
1653   return NewMBB;
1654 }
1655
1656 bool SystemZTargetLowering::
1657 convertPrevCompareToBranch(MachineBasicBlock *MBB,
1658                            MachineBasicBlock::iterator MBBI,
1659                            unsigned CCMask, MachineBasicBlock *Target) const {
1660   MachineBasicBlock::iterator Compare = MBBI;
1661   MachineBasicBlock::iterator Begin = MBB->begin();
1662   do
1663     {
1664       if (Compare == Begin)
1665         return false;
1666       --Compare;
1667     }
1668   while (Compare->isDebugValue());
1669
1670   const SystemZInstrInfo *TII = TM.getInstrInfo();
1671   unsigned FusedOpcode = TII->getCompareAndBranch(Compare->getOpcode(),
1672                                                   Compare);
1673   if (!FusedOpcode)
1674     return false;
1675
1676   DebugLoc DL = Compare->getDebugLoc();
1677   BuildMI(*MBB, MBBI, DL, TII->get(FusedOpcode))
1678     .addOperand(Compare->getOperand(0)).addOperand(Compare->getOperand(1))
1679     .addImm(CCMask).addMBB(Target);
1680   Compare->removeFromParent();
1681   return true;
1682 }
1683
1684 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
1685 MachineBasicBlock *
1686 SystemZTargetLowering::emitSelect(MachineInstr *MI,
1687                                   MachineBasicBlock *MBB) const {
1688   const SystemZInstrInfo *TII = TM.getInstrInfo();
1689
1690   unsigned DestReg  = MI->getOperand(0).getReg();
1691   unsigned TrueReg  = MI->getOperand(1).getReg();
1692   unsigned FalseReg = MI->getOperand(2).getReg();
1693   unsigned CCMask   = MI->getOperand(3).getImm();
1694   DebugLoc DL       = MI->getDebugLoc();
1695
1696   MachineBasicBlock *StartMBB = MBB;
1697   MachineBasicBlock *JoinMBB  = splitBlockAfter(MI, MBB);
1698   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
1699
1700   //  StartMBB:
1701   //   BRC CCMask, JoinMBB
1702   //   # fallthrough to FalseMBB
1703   //
1704   // The original DAG glues comparisons to their uses, both to ensure
1705   // that no CC-clobbering instructions are inserted between them, and
1706   // to ensure that comparison results are not reused.  This means that
1707   // this Select is the sole user of any preceding comparison instruction
1708   // and that we can try to use a fused compare and branch instead.
1709   MBB = StartMBB;
1710   if (!convertPrevCompareToBranch(MBB, MI, CCMask, JoinMBB))
1711     BuildMI(MBB, DL, TII->get(SystemZ::BRC)).addImm(CCMask).addMBB(JoinMBB);
1712   MBB->addSuccessor(JoinMBB);
1713   MBB->addSuccessor(FalseMBB);
1714
1715   //  FalseMBB:
1716   //   # fallthrough to JoinMBB
1717   MBB = FalseMBB;
1718   MBB->addSuccessor(JoinMBB);
1719
1720   //  JoinMBB:
1721   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
1722   //  ...
1723   MBB = JoinMBB;
1724   BuildMI(*MBB, MBB->begin(), DL, TII->get(SystemZ::PHI), DestReg)
1725     .addReg(TrueReg).addMBB(StartMBB)
1726     .addReg(FalseReg).addMBB(FalseMBB);
1727
1728   MI->eraseFromParent();
1729   return JoinMBB;
1730 }
1731
1732 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
1733 // StoreOpcode is the store to use and Invert says whether the store should
1734 // happen when the condition is false rather than true.
1735 MachineBasicBlock *
1736 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
1737                                      MachineBasicBlock *MBB,
1738                                      unsigned StoreOpcode, bool Invert) const {
1739   const SystemZInstrInfo *TII = TM.getInstrInfo();
1740
1741   MachineOperand Base = MI->getOperand(0);
1742   int64_t Disp        = MI->getOperand(1).getImm();
1743   unsigned IndexReg   = MI->getOperand(2).getReg();
1744   unsigned SrcReg     = MI->getOperand(3).getReg();
1745   unsigned CCMask     = MI->getOperand(4).getImm();
1746   DebugLoc DL         = MI->getDebugLoc();
1747
1748   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
1749
1750   // Get the condition needed to branch around the store.
1751   if (!Invert)
1752     CCMask = CCMask ^ SystemZ::CCMASK_ANY;
1753
1754   MachineBasicBlock *StartMBB = MBB;
1755   MachineBasicBlock *JoinMBB  = splitBlockAfter(MI, MBB);
1756   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
1757
1758   //  StartMBB:
1759   //   BRC CCMask, JoinMBB
1760   //   # fallthrough to FalseMBB
1761   //
1762   // The original DAG glues comparisons to their uses, both to ensure
1763   // that no CC-clobbering instructions are inserted between them, and
1764   // to ensure that comparison results are not reused.  This means that
1765   // this CondStore is the sole user of any preceding comparison instruction
1766   // and that we can try to use a fused compare and branch instead.
1767   MBB = StartMBB;
1768   if (!convertPrevCompareToBranch(MBB, MI, CCMask, JoinMBB))
1769     BuildMI(MBB, DL, TII->get(SystemZ::BRC)).addImm(CCMask).addMBB(JoinMBB);
1770   MBB->addSuccessor(JoinMBB);
1771   MBB->addSuccessor(FalseMBB);
1772
1773   //  FalseMBB:
1774   //   store %SrcReg, %Disp(%Index,%Base)
1775   //   # fallthrough to JoinMBB
1776   MBB = FalseMBB;
1777   BuildMI(MBB, DL, TII->get(StoreOpcode))
1778     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
1779   MBB->addSuccessor(JoinMBB);
1780
1781   MI->eraseFromParent();
1782   return JoinMBB;
1783 }
1784
1785 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
1786 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
1787 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
1788 // BitSize is the width of the field in bits, or 0 if this is a partword
1789 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
1790 // is one of the operands.  Invert says whether the field should be
1791 // inverted after performing BinOpcode (e.g. for NAND).
1792 MachineBasicBlock *
1793 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
1794                                             MachineBasicBlock *MBB,
1795                                             unsigned BinOpcode,
1796                                             unsigned BitSize,
1797                                             bool Invert) const {
1798   const SystemZInstrInfo *TII = TM.getInstrInfo();
1799   MachineFunction &MF = *MBB->getParent();
1800   MachineRegisterInfo &MRI = MF.getRegInfo();
1801   unsigned MaskNE = CCMaskForCondCode(ISD::SETNE);
1802   bool IsSubWord = (BitSize < 32);
1803
1804   // Extract the operands.  Base can be a register or a frame index.
1805   // Src2 can be a register or immediate.
1806   unsigned Dest        = MI->getOperand(0).getReg();
1807   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
1808   int64_t Disp         = MI->getOperand(2).getImm();
1809   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
1810   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
1811   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
1812   DebugLoc DL          = MI->getDebugLoc();
1813   if (IsSubWord)
1814     BitSize = MI->getOperand(6).getImm();
1815
1816   // Subword operations use 32-bit registers.
1817   const TargetRegisterClass *RC = (BitSize <= 32 ?
1818                                    &SystemZ::GR32BitRegClass :
1819                                    &SystemZ::GR64BitRegClass);
1820   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
1821   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
1822
1823   // Get the right opcodes for the displacement.
1824   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
1825   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
1826   assert(LOpcode && CSOpcode && "Displacement out of range");
1827
1828   // Create virtual registers for temporary results.
1829   unsigned OrigVal       = MRI.createVirtualRegister(RC);
1830   unsigned OldVal        = MRI.createVirtualRegister(RC);
1831   unsigned NewVal        = (BinOpcode || IsSubWord ?
1832                             MRI.createVirtualRegister(RC) : Src2.getReg());
1833   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
1834   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
1835
1836   // Insert a basic block for the main loop.
1837   MachineBasicBlock *StartMBB = MBB;
1838   MachineBasicBlock *DoneMBB  = splitBlockAfter(MI, MBB);
1839   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
1840
1841   //  StartMBB:
1842   //   ...
1843   //   %OrigVal = L Disp(%Base)
1844   //   # fall through to LoopMMB
1845   MBB = StartMBB;
1846   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
1847     .addOperand(Base).addImm(Disp).addReg(0);
1848   MBB->addSuccessor(LoopMBB);
1849
1850   //  LoopMBB:
1851   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
1852   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
1853   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
1854   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
1855   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
1856   //   JNE LoopMBB
1857   //   # fall through to DoneMMB
1858   MBB = LoopMBB;
1859   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
1860     .addReg(OrigVal).addMBB(StartMBB)
1861     .addReg(Dest).addMBB(LoopMBB);
1862   if (IsSubWord)
1863     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
1864       .addReg(OldVal).addReg(BitShift).addImm(0);
1865   if (Invert) {
1866     // Perform the operation normally and then invert every bit of the field.
1867     unsigned Tmp = MRI.createVirtualRegister(RC);
1868     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
1869       .addReg(RotatedOldVal).addOperand(Src2);
1870     if (BitSize < 32)
1871       // XILF with the upper BitSize bits set.
1872       BuildMI(MBB, DL, TII->get(SystemZ::XILF32), RotatedNewVal)
1873         .addReg(Tmp).addImm(uint32_t(~0 << (32 - BitSize)));
1874     else if (BitSize == 32)
1875       // XILF with every bit set.
1876       BuildMI(MBB, DL, TII->get(SystemZ::XILF32), RotatedNewVal)
1877         .addReg(Tmp).addImm(~uint32_t(0));
1878     else {
1879       // Use LCGR and add -1 to the result, which is more compact than
1880       // an XILF, XILH pair.
1881       unsigned Tmp2 = MRI.createVirtualRegister(RC);
1882       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
1883       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
1884         .addReg(Tmp2).addImm(-1);
1885     }
1886   } else if (BinOpcode)
1887     // A simply binary operation.
1888     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
1889       .addReg(RotatedOldVal).addOperand(Src2);
1890   else if (IsSubWord)
1891     // Use RISBG to rotate Src2 into position and use it to replace the
1892     // field in RotatedOldVal.
1893     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
1894       .addReg(RotatedOldVal).addReg(Src2.getReg())
1895       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
1896   if (IsSubWord)
1897     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
1898       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
1899   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
1900     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
1901   BuildMI(MBB, DL, TII->get(SystemZ::BRC)).addImm(MaskNE).addMBB(LoopMBB);
1902   MBB->addSuccessor(LoopMBB);
1903   MBB->addSuccessor(DoneMBB);
1904
1905   MI->eraseFromParent();
1906   return DoneMBB;
1907 }
1908
1909 // Implement EmitInstrWithCustomInserter for pseudo
1910 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
1911 // instruction that should be used to compare the current field with the
1912 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
1913 // for when the current field should be kept.  BitSize is the width of
1914 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
1915 MachineBasicBlock *
1916 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
1917                                             MachineBasicBlock *MBB,
1918                                             unsigned CompareOpcode,
1919                                             unsigned KeepOldMask,
1920                                             unsigned BitSize) const {
1921   const SystemZInstrInfo *TII = TM.getInstrInfo();
1922   MachineFunction &MF = *MBB->getParent();
1923   MachineRegisterInfo &MRI = MF.getRegInfo();
1924   unsigned MaskNE = CCMaskForCondCode(ISD::SETNE);
1925   bool IsSubWord = (BitSize < 32);
1926
1927   // Extract the operands.  Base can be a register or a frame index.
1928   unsigned Dest        = MI->getOperand(0).getReg();
1929   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
1930   int64_t  Disp        = MI->getOperand(2).getImm();
1931   unsigned Src2        = MI->getOperand(3).getReg();
1932   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
1933   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
1934   DebugLoc DL          = MI->getDebugLoc();
1935   if (IsSubWord)
1936     BitSize = MI->getOperand(6).getImm();
1937
1938   // Subword operations use 32-bit registers.
1939   const TargetRegisterClass *RC = (BitSize <= 32 ?
1940                                    &SystemZ::GR32BitRegClass :
1941                                    &SystemZ::GR64BitRegClass);
1942   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
1943   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
1944
1945   // Get the right opcodes for the displacement.
1946   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
1947   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
1948   assert(LOpcode && CSOpcode && "Displacement out of range");
1949
1950   // Create virtual registers for temporary results.
1951   unsigned OrigVal       = MRI.createVirtualRegister(RC);
1952   unsigned OldVal        = MRI.createVirtualRegister(RC);
1953   unsigned NewVal        = MRI.createVirtualRegister(RC);
1954   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
1955   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
1956   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
1957
1958   // Insert 3 basic blocks for the loop.
1959   MachineBasicBlock *StartMBB  = MBB;
1960   MachineBasicBlock *DoneMBB   = splitBlockAfter(MI, MBB);
1961   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
1962   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
1963   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
1964
1965   //  StartMBB:
1966   //   ...
1967   //   %OrigVal     = L Disp(%Base)
1968   //   # fall through to LoopMMB
1969   MBB = StartMBB;
1970   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
1971     .addOperand(Base).addImm(Disp).addReg(0);
1972   MBB->addSuccessor(LoopMBB);
1973
1974   //  LoopMBB:
1975   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
1976   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
1977   //   CompareOpcode %RotatedOldVal, %Src2
1978   //   BRC KeepOldMask, UpdateMBB
1979   MBB = LoopMBB;
1980   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
1981     .addReg(OrigVal).addMBB(StartMBB)
1982     .addReg(Dest).addMBB(UpdateMBB);
1983   if (IsSubWord)
1984     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
1985       .addReg(OldVal).addReg(BitShift).addImm(0);
1986   unsigned FusedOpcode = TII->getCompareAndBranch(CompareOpcode);
1987   if (FusedOpcode)
1988     BuildMI(MBB, DL, TII->get(FusedOpcode))
1989       .addReg(RotatedOldVal).addReg(Src2)
1990       .addImm(KeepOldMask).addMBB(UpdateMBB);
1991   else {
1992     BuildMI(MBB, DL, TII->get(CompareOpcode))
1993       .addReg(RotatedOldVal).addReg(Src2);
1994     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
1995       .addImm(KeepOldMask).addMBB(UpdateMBB);
1996   }
1997   MBB->addSuccessor(UpdateMBB);
1998   MBB->addSuccessor(UseAltMBB);
1999
2000   //  UseAltMBB:
2001   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
2002   //   # fall through to UpdateMMB
2003   MBB = UseAltMBB;
2004   if (IsSubWord)
2005     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
2006       .addReg(RotatedOldVal).addReg(Src2)
2007       .addImm(32).addImm(31 + BitSize).addImm(0);
2008   MBB->addSuccessor(UpdateMBB);
2009
2010   //  UpdateMBB:
2011   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
2012   //                        [ %RotatedAltVal, UseAltMBB ]
2013   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2014   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2015   //   JNE LoopMBB
2016   //   # fall through to DoneMMB
2017   MBB = UpdateMBB;
2018   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
2019     .addReg(RotatedOldVal).addMBB(LoopMBB)
2020     .addReg(RotatedAltVal).addMBB(UseAltMBB);
2021   if (IsSubWord)
2022     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2023       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2024   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2025     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2026   BuildMI(MBB, DL, TII->get(SystemZ::BRC)).addImm(MaskNE).addMBB(LoopMBB);
2027   MBB->addSuccessor(LoopMBB);
2028   MBB->addSuccessor(DoneMBB);
2029
2030   MI->eraseFromParent();
2031   return DoneMBB;
2032 }
2033
2034 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
2035 // instruction MI.
2036 MachineBasicBlock *
2037 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
2038                                           MachineBasicBlock *MBB) const {
2039   const SystemZInstrInfo *TII = TM.getInstrInfo();
2040   MachineFunction &MF = *MBB->getParent();
2041   MachineRegisterInfo &MRI = MF.getRegInfo();
2042   unsigned MaskNE = CCMaskForCondCode(ISD::SETNE);
2043
2044   // Extract the operands.  Base can be a register or a frame index.
2045   unsigned Dest        = MI->getOperand(0).getReg();
2046   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2047   int64_t  Disp        = MI->getOperand(2).getImm();
2048   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
2049   unsigned OrigSwapVal = MI->getOperand(4).getReg();
2050   unsigned BitShift    = MI->getOperand(5).getReg();
2051   unsigned NegBitShift = MI->getOperand(6).getReg();
2052   int64_t  BitSize     = MI->getOperand(7).getImm();
2053   DebugLoc DL          = MI->getDebugLoc();
2054
2055   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
2056
2057   // Get the right opcodes for the displacement.
2058   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
2059   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
2060   assert(LOpcode && CSOpcode && "Displacement out of range");
2061
2062   // Create virtual registers for temporary results.
2063   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
2064   unsigned OldVal       = MRI.createVirtualRegister(RC);
2065   unsigned CmpVal       = MRI.createVirtualRegister(RC);
2066   unsigned SwapVal      = MRI.createVirtualRegister(RC);
2067   unsigned StoreVal     = MRI.createVirtualRegister(RC);
2068   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
2069   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
2070   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
2071
2072   // Insert 2 basic blocks for the loop.
2073   MachineBasicBlock *StartMBB = MBB;
2074   MachineBasicBlock *DoneMBB  = splitBlockAfter(MI, MBB);
2075   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2076   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
2077
2078   //  StartMBB:
2079   //   ...
2080   //   %OrigOldVal     = L Disp(%Base)
2081   //   # fall through to LoopMMB
2082   MBB = StartMBB;
2083   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
2084     .addOperand(Base).addImm(Disp).addReg(0);
2085   MBB->addSuccessor(LoopMBB);
2086
2087   //  LoopMBB:
2088   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
2089   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
2090   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
2091   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
2092   //                      ^^ The low BitSize bits contain the field
2093   //                         of interest.
2094   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
2095   //                      ^^ Replace the upper 32-BitSize bits of the
2096   //                         comparison value with those that we loaded,
2097   //                         so that we can use a full word comparison.
2098   //   CRJNE %Dest, %RetryCmpVal, DoneMBB
2099   //   # Fall through to SetMBB
2100   MBB = LoopMBB;
2101   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2102     .addReg(OrigOldVal).addMBB(StartMBB)
2103     .addReg(RetryOldVal).addMBB(SetMBB);
2104   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
2105     .addReg(OrigCmpVal).addMBB(StartMBB)
2106     .addReg(RetryCmpVal).addMBB(SetMBB);
2107   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
2108     .addReg(OrigSwapVal).addMBB(StartMBB)
2109     .addReg(RetrySwapVal).addMBB(SetMBB);
2110   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
2111     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
2112   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
2113     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2114   BuildMI(MBB, DL, TII->get(SystemZ::CRJ))
2115     .addReg(Dest).addReg(RetryCmpVal)
2116     .addImm(MaskNE).addMBB(DoneMBB);
2117   MBB->addSuccessor(DoneMBB);
2118   MBB->addSuccessor(SetMBB);
2119
2120   //  SetMBB:
2121   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
2122   //                      ^^ Replace the upper 32-BitSize bits of the new
2123   //                         value with those that we loaded.
2124   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
2125   //                      ^^ Rotate the new field to its proper position.
2126   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
2127   //   JNE LoopMBB
2128   //   # fall through to ExitMMB
2129   MBB = SetMBB;
2130   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
2131     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2132   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
2133     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
2134   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
2135     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
2136   BuildMI(MBB, DL, TII->get(SystemZ::BRC)).addImm(MaskNE).addMBB(LoopMBB);
2137   MBB->addSuccessor(LoopMBB);
2138   MBB->addSuccessor(DoneMBB);
2139
2140   MI->eraseFromParent();
2141   return DoneMBB;
2142 }
2143
2144 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
2145 // if the high register of the GR128 value must be cleared or false if
2146 // it's "don't care".  SubReg is subreg_odd32 when extending a GR32
2147 // and subreg_odd when extending a GR64.
2148 MachineBasicBlock *
2149 SystemZTargetLowering::emitExt128(MachineInstr *MI,
2150                                   MachineBasicBlock *MBB,
2151                                   bool ClearEven, unsigned SubReg) const {
2152   const SystemZInstrInfo *TII = TM.getInstrInfo();
2153   MachineFunction &MF = *MBB->getParent();
2154   MachineRegisterInfo &MRI = MF.getRegInfo();
2155   DebugLoc DL = MI->getDebugLoc();
2156
2157   unsigned Dest  = MI->getOperand(0).getReg();
2158   unsigned Src   = MI->getOperand(1).getReg();
2159   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2160
2161   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
2162   if (ClearEven) {
2163     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2164     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
2165
2166     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
2167       .addImm(0);
2168     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
2169       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_high);
2170     In128 = NewIn128;
2171   }
2172   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
2173     .addReg(In128).addReg(Src).addImm(SubReg);
2174
2175   MI->eraseFromParent();
2176   return MBB;
2177 }
2178
2179 MachineBasicBlock *
2180 SystemZTargetLowering::emitMVCWrapper(MachineInstr *MI,
2181                                       MachineBasicBlock *MBB) const {
2182   const SystemZInstrInfo *TII = TM.getInstrInfo();
2183   DebugLoc DL = MI->getDebugLoc();
2184
2185   MachineOperand DestBase = MI->getOperand(0);
2186   uint64_t       DestDisp = MI->getOperand(1).getImm();
2187   MachineOperand SrcBase  = MI->getOperand(2);
2188   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
2189   uint64_t       Length   = MI->getOperand(4).getImm();
2190
2191   BuildMI(*MBB, MI, DL, TII->get(SystemZ::MVC))
2192     .addOperand(DestBase).addImm(DestDisp).addImm(Length)
2193     .addOperand(SrcBase).addImm(SrcDisp);
2194
2195   MI->eraseFromParent();
2196   return MBB;
2197 }
2198
2199 MachineBasicBlock *SystemZTargetLowering::
2200 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
2201   switch (MI->getOpcode()) {
2202   case SystemZ::Select32:
2203   case SystemZ::SelectF32:
2204   case SystemZ::Select64:
2205   case SystemZ::SelectF64:
2206   case SystemZ::SelectF128:
2207     return emitSelect(MI, MBB);
2208
2209   case SystemZ::CondStore8_32:
2210     return emitCondStore(MI, MBB, SystemZ::STC32, false);
2211   case SystemZ::CondStore8_32Inv:
2212     return emitCondStore(MI, MBB, SystemZ::STC32, true);
2213   case SystemZ::CondStore16_32:
2214     return emitCondStore(MI, MBB, SystemZ::STH32, false);
2215   case SystemZ::CondStore16_32Inv:
2216     return emitCondStore(MI, MBB, SystemZ::STH32, true);
2217   case SystemZ::CondStore32_32:
2218     return emitCondStore(MI, MBB, SystemZ::ST32, false);
2219   case SystemZ::CondStore32_32Inv:
2220     return emitCondStore(MI, MBB, SystemZ::ST32, true);
2221   case SystemZ::CondStore8:
2222     return emitCondStore(MI, MBB, SystemZ::STC, false);
2223   case SystemZ::CondStore8Inv:
2224     return emitCondStore(MI, MBB, SystemZ::STC, true);
2225   case SystemZ::CondStore16:
2226     return emitCondStore(MI, MBB, SystemZ::STH, false);
2227   case SystemZ::CondStore16Inv:
2228     return emitCondStore(MI, MBB, SystemZ::STH, true);
2229   case SystemZ::CondStore32:
2230     return emitCondStore(MI, MBB, SystemZ::ST, false);
2231   case SystemZ::CondStore32Inv:
2232     return emitCondStore(MI, MBB, SystemZ::ST, true);
2233   case SystemZ::CondStore64:
2234     return emitCondStore(MI, MBB, SystemZ::STG, false);
2235   case SystemZ::CondStore64Inv:
2236     return emitCondStore(MI, MBB, SystemZ::STG, true);
2237   case SystemZ::CondStoreF32:
2238     return emitCondStore(MI, MBB, SystemZ::STE, false);
2239   case SystemZ::CondStoreF32Inv:
2240     return emitCondStore(MI, MBB, SystemZ::STE, true);
2241   case SystemZ::CondStoreF64:
2242     return emitCondStore(MI, MBB, SystemZ::STD, false);
2243   case SystemZ::CondStoreF64Inv:
2244     return emitCondStore(MI, MBB, SystemZ::STD, true);
2245
2246   case SystemZ::AEXT128_64:
2247     return emitExt128(MI, MBB, false, SystemZ::subreg_low);
2248   case SystemZ::ZEXT128_32:
2249     return emitExt128(MI, MBB, true, SystemZ::subreg_low32);
2250   case SystemZ::ZEXT128_64:
2251     return emitExt128(MI, MBB, true, SystemZ::subreg_low);
2252
2253   case SystemZ::ATOMIC_SWAPW:
2254     return emitAtomicLoadBinary(MI, MBB, 0, 0);
2255   case SystemZ::ATOMIC_SWAP_32:
2256     return emitAtomicLoadBinary(MI, MBB, 0, 32);
2257   case SystemZ::ATOMIC_SWAP_64:
2258     return emitAtomicLoadBinary(MI, MBB, 0, 64);
2259
2260   case SystemZ::ATOMIC_LOADW_AR:
2261     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
2262   case SystemZ::ATOMIC_LOADW_AFI:
2263     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
2264   case SystemZ::ATOMIC_LOAD_AR:
2265     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
2266   case SystemZ::ATOMIC_LOAD_AHI:
2267     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
2268   case SystemZ::ATOMIC_LOAD_AFI:
2269     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
2270   case SystemZ::ATOMIC_LOAD_AGR:
2271     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
2272   case SystemZ::ATOMIC_LOAD_AGHI:
2273     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
2274   case SystemZ::ATOMIC_LOAD_AGFI:
2275     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
2276
2277   case SystemZ::ATOMIC_LOADW_SR:
2278     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
2279   case SystemZ::ATOMIC_LOAD_SR:
2280     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
2281   case SystemZ::ATOMIC_LOAD_SGR:
2282     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
2283
2284   case SystemZ::ATOMIC_LOADW_NR:
2285     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
2286   case SystemZ::ATOMIC_LOADW_NILH:
2287     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 0);
2288   case SystemZ::ATOMIC_LOAD_NR:
2289     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
2290   case SystemZ::ATOMIC_LOAD_NILL32:
2291     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL32, 32);
2292   case SystemZ::ATOMIC_LOAD_NILH32:
2293     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 32);
2294   case SystemZ::ATOMIC_LOAD_NILF32:
2295     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF32, 32);
2296   case SystemZ::ATOMIC_LOAD_NGR:
2297     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
2298   case SystemZ::ATOMIC_LOAD_NILL:
2299     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 64);
2300   case SystemZ::ATOMIC_LOAD_NILH:
2301     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 64);
2302   case SystemZ::ATOMIC_LOAD_NIHL:
2303     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL, 64);
2304   case SystemZ::ATOMIC_LOAD_NIHH:
2305     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH, 64);
2306   case SystemZ::ATOMIC_LOAD_NILF:
2307     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 64);
2308   case SystemZ::ATOMIC_LOAD_NIHF:
2309     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF, 64);
2310
2311   case SystemZ::ATOMIC_LOADW_OR:
2312     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
2313   case SystemZ::ATOMIC_LOADW_OILH:
2314     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH32, 0);
2315   case SystemZ::ATOMIC_LOAD_OR:
2316     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
2317   case SystemZ::ATOMIC_LOAD_OILL32:
2318     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL32, 32);
2319   case SystemZ::ATOMIC_LOAD_OILH32:
2320     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH32, 32);
2321   case SystemZ::ATOMIC_LOAD_OILF32:
2322     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF32, 32);
2323   case SystemZ::ATOMIC_LOAD_OGR:
2324     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
2325   case SystemZ::ATOMIC_LOAD_OILL:
2326     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 64);
2327   case SystemZ::ATOMIC_LOAD_OILH:
2328     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 64);
2329   case SystemZ::ATOMIC_LOAD_OIHL:
2330     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL, 64);
2331   case SystemZ::ATOMIC_LOAD_OIHH:
2332     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH, 64);
2333   case SystemZ::ATOMIC_LOAD_OILF:
2334     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 64);
2335   case SystemZ::ATOMIC_LOAD_OIHF:
2336     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF, 64);
2337
2338   case SystemZ::ATOMIC_LOADW_XR:
2339     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
2340   case SystemZ::ATOMIC_LOADW_XILF:
2341     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF32, 0);
2342   case SystemZ::ATOMIC_LOAD_XR:
2343     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
2344   case SystemZ::ATOMIC_LOAD_XILF32:
2345     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF32, 32);
2346   case SystemZ::ATOMIC_LOAD_XGR:
2347     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
2348   case SystemZ::ATOMIC_LOAD_XILF:
2349     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 64);
2350   case SystemZ::ATOMIC_LOAD_XIHF:
2351     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF, 64);
2352
2353   case SystemZ::ATOMIC_LOADW_NRi:
2354     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
2355   case SystemZ::ATOMIC_LOADW_NILHi:
2356     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 0, true);
2357   case SystemZ::ATOMIC_LOAD_NRi:
2358     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
2359   case SystemZ::ATOMIC_LOAD_NILL32i:
2360     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL32, 32, true);
2361   case SystemZ::ATOMIC_LOAD_NILH32i:
2362     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 32, true);
2363   case SystemZ::ATOMIC_LOAD_NILF32i:
2364     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF32, 32, true);
2365   case SystemZ::ATOMIC_LOAD_NGRi:
2366     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
2367   case SystemZ::ATOMIC_LOAD_NILLi:
2368     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 64, true);
2369   case SystemZ::ATOMIC_LOAD_NILHi:
2370     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 64, true);
2371   case SystemZ::ATOMIC_LOAD_NIHLi:
2372     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL, 64, true);
2373   case SystemZ::ATOMIC_LOAD_NIHHi:
2374     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH, 64, true);
2375   case SystemZ::ATOMIC_LOAD_NILFi:
2376     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 64, true);
2377   case SystemZ::ATOMIC_LOAD_NIHFi:
2378     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF, 64, true);
2379
2380   case SystemZ::ATOMIC_LOADW_MIN:
2381     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
2382                                 SystemZ::CCMASK_CMP_LE, 0);
2383   case SystemZ::ATOMIC_LOAD_MIN_32:
2384     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
2385                                 SystemZ::CCMASK_CMP_LE, 32);
2386   case SystemZ::ATOMIC_LOAD_MIN_64:
2387     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
2388                                 SystemZ::CCMASK_CMP_LE, 64);
2389
2390   case SystemZ::ATOMIC_LOADW_MAX:
2391     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
2392                                 SystemZ::CCMASK_CMP_GE, 0);
2393   case SystemZ::ATOMIC_LOAD_MAX_32:
2394     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
2395                                 SystemZ::CCMASK_CMP_GE, 32);
2396   case SystemZ::ATOMIC_LOAD_MAX_64:
2397     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
2398                                 SystemZ::CCMASK_CMP_GE, 64);
2399
2400   case SystemZ::ATOMIC_LOADW_UMIN:
2401     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
2402                                 SystemZ::CCMASK_CMP_LE, 0);
2403   case SystemZ::ATOMIC_LOAD_UMIN_32:
2404     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
2405                                 SystemZ::CCMASK_CMP_LE, 32);
2406   case SystemZ::ATOMIC_LOAD_UMIN_64:
2407     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
2408                                 SystemZ::CCMASK_CMP_LE, 64);
2409
2410   case SystemZ::ATOMIC_LOADW_UMAX:
2411     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
2412                                 SystemZ::CCMASK_CMP_GE, 0);
2413   case SystemZ::ATOMIC_LOAD_UMAX_32:
2414     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
2415                                 SystemZ::CCMASK_CMP_GE, 32);
2416   case SystemZ::ATOMIC_LOAD_UMAX_64:
2417     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
2418                                 SystemZ::CCMASK_CMP_GE, 64);
2419
2420   case SystemZ::ATOMIC_CMP_SWAPW:
2421     return emitAtomicCmpSwapW(MI, MBB);
2422   case SystemZ::BRC:
2423     // The original DAG glues comparisons to their uses, both to ensure
2424     // that no CC-clobbering instructions are inserted between them, and
2425     // to ensure that comparison results are not reused.  This means that
2426     // a BRC is the sole user of a preceding comparison and that we can
2427     // try to use a fused compare and branch instead.
2428     if (convertPrevCompareToBranch(MBB, MI, MI->getOperand(0).getImm(),
2429                                    MI->getOperand(1).getMBB()))
2430       MI->eraseFromParent();
2431     return MBB;
2432   case SystemZ::MVCWrapper:
2433     return emitMVCWrapper(MI, MBB);
2434   default:
2435     llvm_unreachable("Unexpected instr type to insert");
2436   }
2437 }