[SystemZ] Extend the use of C(L)GFR
[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 #include <cctype>
27
28 using namespace llvm;
29
30 namespace {
31 // Represents a sequence for extracting a 0/1 value from an IPM result:
32 // (((X ^ XORValue) + AddValue) >> Bit)
33 struct IPMConversion {
34   IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
35     : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
36
37   int64_t XORValue;
38   int64_t AddValue;
39   unsigned Bit;
40 };
41 }
42
43 // Classify VT as either 32 or 64 bit.
44 static bool is32Bit(EVT VT) {
45   switch (VT.getSimpleVT().SimpleTy) {
46   case MVT::i32:
47     return true;
48   case MVT::i64:
49     return false;
50   default:
51     llvm_unreachable("Unsupported type");
52   }
53 }
54
55 // Return a version of MachineOperand that can be safely used before the
56 // final use.
57 static MachineOperand earlyUseOperand(MachineOperand Op) {
58   if (Op.isReg())
59     Op.setIsKill(false);
60   return Op;
61 }
62
63 SystemZTargetLowering::SystemZTargetLowering(SystemZTargetMachine &tm)
64   : TargetLowering(tm, new TargetLoweringObjectFileELF()),
65     Subtarget(*tm.getSubtargetImpl()), TM(tm) {
66   MVT PtrVT = getPointerTy();
67
68   // Set up the register classes.
69   if (Subtarget.hasHighWord())
70     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
71   else
72     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
73   addRegisterClass(MVT::i64,  &SystemZ::GR64BitRegClass);
74   addRegisterClass(MVT::f32,  &SystemZ::FP32BitRegClass);
75   addRegisterClass(MVT::f64,  &SystemZ::FP64BitRegClass);
76   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
77
78   // Compute derived properties from the register classes
79   computeRegisterProperties();
80
81   // Set up special registers.
82   setExceptionPointerRegister(SystemZ::R6D);
83   setExceptionSelectorRegister(SystemZ::R7D);
84   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
85
86   // TODO: It may be better to default to latency-oriented scheduling, however
87   // LLVM's current latency-oriented scheduler can't handle physreg definitions
88   // such as SystemZ has with CC, so set this to the register-pressure
89   // scheduler, because it can.
90   setSchedulingPreference(Sched::RegPressure);
91
92   setBooleanContents(ZeroOrOneBooleanContent);
93   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
94
95   // Instructions are strings of 2-byte aligned 2-byte values.
96   setMinFunctionAlignment(2);
97
98   // Handle operations that are handled in a similar way for all types.
99   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
100        I <= MVT::LAST_FP_VALUETYPE;
101        ++I) {
102     MVT VT = MVT::SimpleValueType(I);
103     if (isTypeLegal(VT)) {
104       // Lower SET_CC into an IPM-based sequence.
105       setOperationAction(ISD::SETCC, VT, Custom);
106
107       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
108       setOperationAction(ISD::SELECT, VT, Expand);
109
110       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
111       setOperationAction(ISD::SELECT_CC, VT, Custom);
112       setOperationAction(ISD::BR_CC,     VT, Custom);
113     }
114   }
115
116   // Expand jump table branches as address arithmetic followed by an
117   // indirect jump.
118   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
119
120   // Expand BRCOND into a BR_CC (see above).
121   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
122
123   // Handle integer types.
124   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
125        I <= MVT::LAST_INTEGER_VALUETYPE;
126        ++I) {
127     MVT VT = MVT::SimpleValueType(I);
128     if (isTypeLegal(VT)) {
129       // Expand individual DIV and REMs into DIVREMs.
130       setOperationAction(ISD::SDIV, VT, Expand);
131       setOperationAction(ISD::UDIV, VT, Expand);
132       setOperationAction(ISD::SREM, VT, Expand);
133       setOperationAction(ISD::UREM, VT, Expand);
134       setOperationAction(ISD::SDIVREM, VT, Custom);
135       setOperationAction(ISD::UDIVREM, VT, Custom);
136
137       // Expand ATOMIC_LOAD and ATOMIC_STORE using ATOMIC_CMP_SWAP.
138       // FIXME: probably much too conservative.
139       setOperationAction(ISD::ATOMIC_LOAD,  VT, Expand);
140       setOperationAction(ISD::ATOMIC_STORE, VT, Expand);
141
142       // No special instructions for these.
143       setOperationAction(ISD::CTPOP,           VT, Expand);
144       setOperationAction(ISD::CTTZ,            VT, Expand);
145       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
146       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
147       setOperationAction(ISD::ROTR,            VT, Expand);
148
149       // Use *MUL_LOHI where possible instead of MULH*.
150       setOperationAction(ISD::MULHS, VT, Expand);
151       setOperationAction(ISD::MULHU, VT, Expand);
152       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
153       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
154
155       // We have instructions for signed but not unsigned FP conversion.
156       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
157     }
158   }
159
160   // Type legalization will convert 8- and 16-bit atomic operations into
161   // forms that operate on i32s (but still keeping the original memory VT).
162   // Lower them into full i32 operations.
163   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
164   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
165   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
166   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
167   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
168   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
169   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
170   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
171   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
172   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
173   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
174   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
175
176   // We have instructions for signed but not unsigned FP conversion.
177   // Handle unsigned 32-bit types as signed 64-bit types.
178   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
179   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
180
181   // We have native support for a 64-bit CTLZ, via FLOGR.
182   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
183   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
184
185   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
186   setOperationAction(ISD::OR, MVT::i64, Custom);
187
188   // FIXME: Can we support these natively?
189   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
190   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
191   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
192
193   // We have native instructions for i8, i16 and i32 extensions, but not i1.
194   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
195   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
196   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
197   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
198
199   // Handle the various types of symbolic address.
200   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
201   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
202   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
203   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
204   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
205
206   // We need to handle dynamic allocations specially because of the
207   // 160-byte area at the bottom of the stack.
208   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
209
210   // Use custom expanders so that we can force the function to use
211   // a frame pointer.
212   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
213   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
214
215   // Handle prefetches with PFD or PFDRL.
216   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
217
218   // Handle floating-point types.
219   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
220        I <= MVT::LAST_FP_VALUETYPE;
221        ++I) {
222     MVT VT = MVT::SimpleValueType(I);
223     if (isTypeLegal(VT)) {
224       // We can use FI for FRINT.
225       setOperationAction(ISD::FRINT, VT, Legal);
226
227       // We can use the extended form of FI for other rounding operations.
228       if (Subtarget.hasFPExtension()) {
229         setOperationAction(ISD::FNEARBYINT, VT, Legal);
230         setOperationAction(ISD::FFLOOR, VT, Legal);
231         setOperationAction(ISD::FCEIL, VT, Legal);
232         setOperationAction(ISD::FTRUNC, VT, Legal);
233         setOperationAction(ISD::FROUND, VT, Legal);
234       }
235
236       // No special instructions for these.
237       setOperationAction(ISD::FSIN, VT, Expand);
238       setOperationAction(ISD::FCOS, VT, Expand);
239       setOperationAction(ISD::FREM, VT, Expand);
240     }
241   }
242
243   // We have fused multiply-addition for f32 and f64 but not f128.
244   setOperationAction(ISD::FMA, MVT::f32,  Legal);
245   setOperationAction(ISD::FMA, MVT::f64,  Legal);
246   setOperationAction(ISD::FMA, MVT::f128, Expand);
247
248   // Needed so that we don't try to implement f128 constant loads using
249   // a load-and-extend of a f80 constant (in cases where the constant
250   // would fit in an f80).
251   setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
252
253   // Floating-point truncation and stores need to be done separately.
254   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
255   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
256   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
257
258   // We have 64-bit FPR<->GPR moves, but need special handling for
259   // 32-bit forms.
260   setOperationAction(ISD::BITCAST, MVT::i32, Custom);
261   setOperationAction(ISD::BITCAST, MVT::f32, Custom);
262
263   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
264   // structure, but VAEND is a no-op.
265   setOperationAction(ISD::VASTART, MVT::Other, Custom);
266   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
267   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
268
269   // We want to use MVC in preference to even a single load/store pair.
270   MaxStoresPerMemcpy = 0;
271   MaxStoresPerMemcpyOptSize = 0;
272
273   // The main memset sequence is a byte store followed by an MVC.
274   // Two STC or MV..I stores win over that, but the kind of fused stores
275   // generated by target-independent code don't when the byte value is
276   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
277   // than "STC;MVC".  Handle the choice in target-specific code instead.
278   MaxStoresPerMemset = 0;
279   MaxStoresPerMemsetOptSize = 0;
280 }
281
282 EVT SystemZTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
283   if (!VT.isVector())
284     return MVT::i32;
285   return VT.changeVectorElementTypeToInteger();
286 }
287
288 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
289   VT = VT.getScalarType();
290
291   if (!VT.isSimple())
292     return false;
293
294   switch (VT.getSimpleVT().SimpleTy) {
295   case MVT::f32:
296   case MVT::f64:
297     return true;
298   case MVT::f128:
299     return false;
300   default:
301     break;
302   }
303
304   return false;
305 }
306
307 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
308   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
309   return Imm.isZero() || Imm.isNegZero();
310 }
311
312 bool SystemZTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
313                                                           bool *Fast) const {
314   // Unaligned accesses should never be slower than the expanded version.
315   // We check specifically for aligned accesses in the few cases where
316   // they are required.
317   if (Fast)
318     *Fast = true;
319   return true;
320 }
321   
322 bool SystemZTargetLowering::isLegalAddressingMode(const AddrMode &AM,
323                                                   Type *Ty) const {
324   // Punt on globals for now, although they can be used in limited
325   // RELATIVE LONG cases.
326   if (AM.BaseGV)
327     return false;
328
329   // Require a 20-bit signed offset.
330   if (!isInt<20>(AM.BaseOffs))
331     return false;
332
333   // Indexing is OK but no scale factor can be applied.
334   return AM.Scale == 0 || AM.Scale == 1;
335 }
336
337 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
338   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
339     return false;
340   unsigned FromBits = FromType->getPrimitiveSizeInBits();
341   unsigned ToBits = ToType->getPrimitiveSizeInBits();
342   return FromBits > ToBits;
343 }
344
345 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
346   if (!FromVT.isInteger() || !ToVT.isInteger())
347     return false;
348   unsigned FromBits = FromVT.getSizeInBits();
349   unsigned ToBits = ToVT.getSizeInBits();
350   return FromBits > ToBits;
351 }
352
353 //===----------------------------------------------------------------------===//
354 // Inline asm support
355 //===----------------------------------------------------------------------===//
356
357 TargetLowering::ConstraintType
358 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
359   if (Constraint.size() == 1) {
360     switch (Constraint[0]) {
361     case 'a': // Address register
362     case 'd': // Data register (equivalent to 'r')
363     case 'f': // Floating-point register
364     case 'h': // High-part register
365     case 'r': // General-purpose register
366       return C_RegisterClass;
367
368     case 'Q': // Memory with base and unsigned 12-bit displacement
369     case 'R': // Likewise, plus an index
370     case 'S': // Memory with base and signed 20-bit displacement
371     case 'T': // Likewise, plus an index
372     case 'm': // Equivalent to 'T'.
373       return C_Memory;
374
375     case 'I': // Unsigned 8-bit constant
376     case 'J': // Unsigned 12-bit constant
377     case 'K': // Signed 16-bit constant
378     case 'L': // Signed 20-bit displacement (on all targets we support)
379     case 'M': // 0x7fffffff
380       return C_Other;
381
382     default:
383       break;
384     }
385   }
386   return TargetLowering::getConstraintType(Constraint);
387 }
388
389 TargetLowering::ConstraintWeight SystemZTargetLowering::
390 getSingleConstraintMatchWeight(AsmOperandInfo &info,
391                                const char *constraint) const {
392   ConstraintWeight weight = CW_Invalid;
393   Value *CallOperandVal = info.CallOperandVal;
394   // If we don't have a value, we can't do a match,
395   // but allow it at the lowest weight.
396   if (CallOperandVal == NULL)
397     return CW_Default;
398   Type *type = CallOperandVal->getType();
399   // Look at the constraint type.
400   switch (*constraint) {
401   default:
402     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
403     break;
404
405   case 'a': // Address register
406   case 'd': // Data register (equivalent to 'r')
407   case 'h': // High-part register
408   case 'r': // General-purpose register
409     if (CallOperandVal->getType()->isIntegerTy())
410       weight = CW_Register;
411     break;
412
413   case 'f': // Floating-point register
414     if (type->isFloatingPointTy())
415       weight = CW_Register;
416     break;
417
418   case 'I': // Unsigned 8-bit constant
419     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
420       if (isUInt<8>(C->getZExtValue()))
421         weight = CW_Constant;
422     break;
423
424   case 'J': // Unsigned 12-bit constant
425     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
426       if (isUInt<12>(C->getZExtValue()))
427         weight = CW_Constant;
428     break;
429
430   case 'K': // Signed 16-bit constant
431     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
432       if (isInt<16>(C->getSExtValue()))
433         weight = CW_Constant;
434     break;
435
436   case 'L': // Signed 20-bit displacement (on all targets we support)
437     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
438       if (isInt<20>(C->getSExtValue()))
439         weight = CW_Constant;
440     break;
441
442   case 'M': // 0x7fffffff
443     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
444       if (C->getZExtValue() == 0x7fffffff)
445         weight = CW_Constant;
446     break;
447   }
448   return weight;
449 }
450
451 // Parse a "{tNNN}" register constraint for which the register type "t"
452 // has already been verified.  MC is the class associated with "t" and
453 // Map maps 0-based register numbers to LLVM register numbers.
454 static std::pair<unsigned, const TargetRegisterClass *>
455 parseRegisterNumber(const std::string &Constraint,
456                     const TargetRegisterClass *RC, const unsigned *Map) {
457   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
458   if (isdigit(Constraint[2])) {
459     std::string Suffix(Constraint.data() + 2, Constraint.size() - 2);
460     unsigned Index = atoi(Suffix.c_str());
461     if (Index < 16 && Map[Index])
462       return std::make_pair(Map[Index], RC);
463   }
464   return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
465 }
466
467 std::pair<unsigned, const TargetRegisterClass *> SystemZTargetLowering::
468 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const {
469   if (Constraint.size() == 1) {
470     // GCC Constraint Letters
471     switch (Constraint[0]) {
472     default: break;
473     case 'd': // Data register (equivalent to 'r')
474     case 'r': // General-purpose register
475       if (VT == MVT::i64)
476         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
477       else if (VT == MVT::i128)
478         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
479       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
480
481     case 'a': // Address register
482       if (VT == MVT::i64)
483         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
484       else if (VT == MVT::i128)
485         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
486       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
487
488     case 'h': // High-part register (an LLVM extension)
489       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
490
491     case 'f': // Floating-point register
492       if (VT == MVT::f64)
493         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
494       else if (VT == MVT::f128)
495         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
496       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
497     }
498   }
499   if (Constraint[0] == '{') {
500     // We need to override the default register parsing for GPRs and FPRs
501     // because the interpretation depends on VT.  The internal names of
502     // the registers are also different from the external names
503     // (F0D and F0S instead of F0, etc.).
504     if (Constraint[1] == 'r') {
505       if (VT == MVT::i32)
506         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
507                                    SystemZMC::GR32Regs);
508       if (VT == MVT::i128)
509         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
510                                    SystemZMC::GR128Regs);
511       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
512                                  SystemZMC::GR64Regs);
513     }
514     if (Constraint[1] == 'f') {
515       if (VT == MVT::f32)
516         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
517                                    SystemZMC::FP32Regs);
518       if (VT == MVT::f128)
519         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
520                                    SystemZMC::FP128Regs);
521       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
522                                  SystemZMC::FP64Regs);
523     }
524   }
525   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
526 }
527
528 void SystemZTargetLowering::
529 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
530                              std::vector<SDValue> &Ops,
531                              SelectionDAG &DAG) const {
532   // Only support length 1 constraints for now.
533   if (Constraint.length() == 1) {
534     switch (Constraint[0]) {
535     case 'I': // Unsigned 8-bit constant
536       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
537         if (isUInt<8>(C->getZExtValue()))
538           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
539                                               Op.getValueType()));
540       return;
541
542     case 'J': // Unsigned 12-bit constant
543       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
544         if (isUInt<12>(C->getZExtValue()))
545           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
546                                               Op.getValueType()));
547       return;
548
549     case 'K': // Signed 16-bit constant
550       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
551         if (isInt<16>(C->getSExtValue()))
552           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
553                                               Op.getValueType()));
554       return;
555
556     case 'L': // Signed 20-bit displacement (on all targets we support)
557       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
558         if (isInt<20>(C->getSExtValue()))
559           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
560                                               Op.getValueType()));
561       return;
562
563     case 'M': // 0x7fffffff
564       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
565         if (C->getZExtValue() == 0x7fffffff)
566           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
567                                               Op.getValueType()));
568       return;
569     }
570   }
571   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
572 }
573
574 //===----------------------------------------------------------------------===//
575 // Calling conventions
576 //===----------------------------------------------------------------------===//
577
578 #include "SystemZGenCallingConv.inc"
579
580 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
581                                                      Type *ToType) const {
582   return isTruncateFree(FromType, ToType);
583 }
584
585 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
586   if (!CI->isTailCall())
587     return false;
588   return true;
589 }
590
591 // Value is a value that has been passed to us in the location described by VA
592 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
593 // any loads onto Chain.
594 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
595                                    CCValAssign &VA, SDValue Chain,
596                                    SDValue Value) {
597   // If the argument has been promoted from a smaller type, insert an
598   // assertion to capture this.
599   if (VA.getLocInfo() == CCValAssign::SExt)
600     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
601                         DAG.getValueType(VA.getValVT()));
602   else if (VA.getLocInfo() == CCValAssign::ZExt)
603     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
604                         DAG.getValueType(VA.getValVT()));
605
606   if (VA.isExtInLoc())
607     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
608   else if (VA.getLocInfo() == CCValAssign::Indirect)
609     Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
610                         MachinePointerInfo(), false, false, false, 0);
611   else
612     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
613   return Value;
614 }
615
616 // Value is a value of type VA.getValVT() that we need to copy into
617 // the location described by VA.  Return a copy of Value converted to
618 // VA.getValVT().  The caller is responsible for handling indirect values.
619 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
620                                    CCValAssign &VA, SDValue Value) {
621   switch (VA.getLocInfo()) {
622   case CCValAssign::SExt:
623     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
624   case CCValAssign::ZExt:
625     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
626   case CCValAssign::AExt:
627     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
628   case CCValAssign::Full:
629     return Value;
630   default:
631     llvm_unreachable("Unhandled getLocInfo()");
632   }
633 }
634
635 SDValue SystemZTargetLowering::
636 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
637                      const SmallVectorImpl<ISD::InputArg> &Ins,
638                      SDLoc DL, SelectionDAG &DAG,
639                      SmallVectorImpl<SDValue> &InVals) const {
640   MachineFunction &MF = DAG.getMachineFunction();
641   MachineFrameInfo *MFI = MF.getFrameInfo();
642   MachineRegisterInfo &MRI = MF.getRegInfo();
643   SystemZMachineFunctionInfo *FuncInfo =
644     MF.getInfo<SystemZMachineFunctionInfo>();
645   const SystemZFrameLowering *TFL =
646     static_cast<const SystemZFrameLowering *>(TM.getFrameLowering());
647
648   // Assign locations to all of the incoming arguments.
649   SmallVector<CCValAssign, 16> ArgLocs;
650   CCState CCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
651   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
652
653   unsigned NumFixedGPRs = 0;
654   unsigned NumFixedFPRs = 0;
655   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
656     SDValue ArgValue;
657     CCValAssign &VA = ArgLocs[I];
658     EVT LocVT = VA.getLocVT();
659     if (VA.isRegLoc()) {
660       // Arguments passed in registers
661       const TargetRegisterClass *RC;
662       switch (LocVT.getSimpleVT().SimpleTy) {
663       default:
664         // Integers smaller than i64 should be promoted to i64.
665         llvm_unreachable("Unexpected argument type");
666       case MVT::i32:
667         NumFixedGPRs += 1;
668         RC = &SystemZ::GR32BitRegClass;
669         break;
670       case MVT::i64:
671         NumFixedGPRs += 1;
672         RC = &SystemZ::GR64BitRegClass;
673         break;
674       case MVT::f32:
675         NumFixedFPRs += 1;
676         RC = &SystemZ::FP32BitRegClass;
677         break;
678       case MVT::f64:
679         NumFixedFPRs += 1;
680         RC = &SystemZ::FP64BitRegClass;
681         break;
682       }
683
684       unsigned VReg = MRI.createVirtualRegister(RC);
685       MRI.addLiveIn(VA.getLocReg(), VReg);
686       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
687     } else {
688       assert(VA.isMemLoc() && "Argument not register or memory");
689
690       // Create the frame index object for this incoming parameter.
691       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
692                                       VA.getLocMemOffset(), true);
693
694       // Create the SelectionDAG nodes corresponding to a load
695       // from this parameter.  Unpromoted ints and floats are
696       // passed as right-justified 8-byte values.
697       EVT PtrVT = getPointerTy();
698       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
699       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
700         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4));
701       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
702                              MachinePointerInfo::getFixedStack(FI),
703                              false, false, false, 0);
704     }
705
706     // Convert the value of the argument register into the value that's
707     // being passed.
708     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
709   }
710
711   if (IsVarArg) {
712     // Save the number of non-varargs registers for later use by va_start, etc.
713     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
714     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
715
716     // Likewise the address (in the form of a frame index) of where the
717     // first stack vararg would be.  The 1-byte size here is arbitrary.
718     int64_t StackSize = CCInfo.getNextStackOffset();
719     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
720
721     // ...and a similar frame index for the caller-allocated save area
722     // that will be used to store the incoming registers.
723     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
724     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
725     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
726
727     // Store the FPR varargs in the reserved frame slots.  (We store the
728     // GPRs as part of the prologue.)
729     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
730       SDValue MemOps[SystemZ::NumArgFPRs];
731       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
732         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
733         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
734         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
735         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
736                                      &SystemZ::FP64BitRegClass);
737         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
738         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
739                                  MachinePointerInfo::getFixedStack(FI),
740                                  false, false, 0);
741
742       }
743       // Join the stores, which are independent of one another.
744       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
745                           &MemOps[NumFixedFPRs],
746                           SystemZ::NumArgFPRs - NumFixedFPRs);
747     }
748   }
749
750   return Chain;
751 }
752
753 static bool canUseSiblingCall(CCState ArgCCInfo,
754                               SmallVectorImpl<CCValAssign> &ArgLocs) {
755   // Punt if there are any indirect or stack arguments, or if the call
756   // needs the call-saved argument register R6.
757   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
758     CCValAssign &VA = ArgLocs[I];
759     if (VA.getLocInfo() == CCValAssign::Indirect)
760       return false;
761     if (!VA.isRegLoc())
762       return false;
763     unsigned Reg = VA.getLocReg();
764     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
765       return false;
766   }
767   return true;
768 }
769
770 SDValue
771 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
772                                  SmallVectorImpl<SDValue> &InVals) const {
773   SelectionDAG &DAG = CLI.DAG;
774   SDLoc &DL = CLI.DL;
775   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
776   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
777   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
778   SDValue Chain = CLI.Chain;
779   SDValue Callee = CLI.Callee;
780   bool &IsTailCall = CLI.IsTailCall;
781   CallingConv::ID CallConv = CLI.CallConv;
782   bool IsVarArg = CLI.IsVarArg;
783   MachineFunction &MF = DAG.getMachineFunction();
784   EVT PtrVT = getPointerTy();
785
786   // Analyze the operands of the call, assigning locations to each operand.
787   SmallVector<CCValAssign, 16> ArgLocs;
788   CCState ArgCCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
789   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
790
791   // We don't support GuaranteedTailCallOpt, only automatically-detected
792   // sibling calls.
793   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
794     IsTailCall = false;
795
796   // Get a count of how many bytes are to be pushed on the stack.
797   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
798
799   // Mark the start of the call.
800   if (!IsTailCall)
801     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, PtrVT, true),
802                                  DL);
803
804   // Copy argument values to their designated locations.
805   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
806   SmallVector<SDValue, 8> MemOpChains;
807   SDValue StackPtr;
808   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
809     CCValAssign &VA = ArgLocs[I];
810     SDValue ArgValue = OutVals[I];
811
812     if (VA.getLocInfo() == CCValAssign::Indirect) {
813       // Store the argument in a stack slot and pass its address.
814       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
815       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
816       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
817                                          MachinePointerInfo::getFixedStack(FI),
818                                          false, false, 0));
819       ArgValue = SpillSlot;
820     } else
821       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
822
823     if (VA.isRegLoc())
824       // Queue up the argument copies and emit them at the end.
825       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
826     else {
827       assert(VA.isMemLoc() && "Argument not register or memory");
828
829       // Work out the address of the stack slot.  Unpromoted ints and
830       // floats are passed as right-justified 8-byte values.
831       if (!StackPtr.getNode())
832         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
833       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
834       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
835         Offset += 4;
836       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
837                                     DAG.getIntPtrConstant(Offset));
838
839       // Emit the store.
840       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
841                                          MachinePointerInfo(),
842                                          false, false, 0));
843     }
844   }
845
846   // Join the stores, which are independent of one another.
847   if (!MemOpChains.empty())
848     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
849                         &MemOpChains[0], MemOpChains.size());
850
851   // Accept direct calls by converting symbolic call addresses to the
852   // associated Target* opcodes.  Force %r1 to be used for indirect
853   // tail calls.
854   SDValue Glue;
855   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
856     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
857     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
858   } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
859     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
860     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
861   } else if (IsTailCall) {
862     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
863     Glue = Chain.getValue(1);
864     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
865   }
866
867   // Build a sequence of copy-to-reg nodes, chained and glued together.
868   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
869     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
870                              RegsToPass[I].second, Glue);
871     Glue = Chain.getValue(1);
872   }
873
874   // The first call operand is the chain and the second is the target address.
875   SmallVector<SDValue, 8> Ops;
876   Ops.push_back(Chain);
877   Ops.push_back(Callee);
878
879   // Add argument registers to the end of the list so that they are
880   // known live into the call.
881   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
882     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
883                                   RegsToPass[I].second.getValueType()));
884
885   // Glue the call to the argument copies, if any.
886   if (Glue.getNode())
887     Ops.push_back(Glue);
888
889   // Emit the call.
890   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
891   if (IsTailCall)
892     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, &Ops[0], Ops.size());
893   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
894   Glue = Chain.getValue(1);
895
896   // Mark the end of the call, which is glued to the call itself.
897   Chain = DAG.getCALLSEQ_END(Chain,
898                              DAG.getConstant(NumBytes, PtrVT, true),
899                              DAG.getConstant(0, PtrVT, true),
900                              Glue, DL);
901   Glue = Chain.getValue(1);
902
903   // Assign locations to each value returned by this call.
904   SmallVector<CCValAssign, 16> RetLocs;
905   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
906   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
907
908   // Copy all of the result registers out of their specified physreg.
909   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
910     CCValAssign &VA = RetLocs[I];
911
912     // Copy the value out, gluing the copy to the end of the call sequence.
913     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
914                                           VA.getLocVT(), Glue);
915     Chain = RetValue.getValue(1);
916     Glue = RetValue.getValue(2);
917
918     // Convert the value of the return register into the value that's
919     // being returned.
920     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
921   }
922
923   return Chain;
924 }
925
926 SDValue
927 SystemZTargetLowering::LowerReturn(SDValue Chain,
928                                    CallingConv::ID CallConv, bool IsVarArg,
929                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
930                                    const SmallVectorImpl<SDValue> &OutVals,
931                                    SDLoc DL, SelectionDAG &DAG) const {
932   MachineFunction &MF = DAG.getMachineFunction();
933
934   // Assign locations to each returned value.
935   SmallVector<CCValAssign, 16> RetLocs;
936   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
937   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
938
939   // Quick exit for void returns
940   if (RetLocs.empty())
941     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
942
943   // Copy the result values into the output registers.
944   SDValue Glue;
945   SmallVector<SDValue, 4> RetOps;
946   RetOps.push_back(Chain);
947   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
948     CCValAssign &VA = RetLocs[I];
949     SDValue RetValue = OutVals[I];
950
951     // Make the return register live on exit.
952     assert(VA.isRegLoc() && "Can only return in registers!");
953
954     // Promote the value as required.
955     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
956
957     // Chain and glue the copies together.
958     unsigned Reg = VA.getLocReg();
959     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
960     Glue = Chain.getValue(1);
961     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
962   }
963
964   // Update chain and glue.
965   RetOps[0] = Chain;
966   if (Glue.getNode())
967     RetOps.push_back(Glue);
968
969   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other,
970                      RetOps.data(), RetOps.size());
971 }
972
973 // CC is a comparison that will be implemented using an integer or
974 // floating-point comparison.  Return the condition code mask for
975 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
976 // unsigned comparisons and clear for signed ones.  In the floating-point
977 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
978 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
979 #define CONV(X) \
980   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
981   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
982   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
983
984   switch (CC) {
985   default:
986     llvm_unreachable("Invalid integer condition!");
987
988   CONV(EQ);
989   CONV(NE);
990   CONV(GT);
991   CONV(GE);
992   CONV(LT);
993   CONV(LE);
994
995   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
996   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
997   }
998 #undef CONV
999 }
1000
1001 // Return a sequence for getting a 1 from an IPM result when CC has a
1002 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1003 // The handling of CC values outside CCValid doesn't matter.
1004 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1005   // Deal with cases where the result can be taken directly from a bit
1006   // of the IPM result.
1007   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1008     return IPMConversion(0, 0, SystemZ::IPM_CC);
1009   if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1010     return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1011
1012   // Deal with cases where we can add a value to force the sign bit
1013   // to contain the right value.  Putting the bit in 31 means we can
1014   // use SRL rather than RISBG(L), and also makes it easier to get a
1015   // 0/-1 value, so it has priority over the other tests below.
1016   //
1017   // These sequences rely on the fact that the upper two bits of the
1018   // IPM result are zero.
1019   uint64_t TopBit = uint64_t(1) << 31;
1020   if (CCMask == (CCValid & SystemZ::CCMASK_0))
1021     return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1022   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1023     return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1024   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1025                             | SystemZ::CCMASK_1
1026                             | SystemZ::CCMASK_2)))
1027     return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1028   if (CCMask == (CCValid & SystemZ::CCMASK_3))
1029     return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1030   if (CCMask == (CCValid & (SystemZ::CCMASK_1
1031                             | SystemZ::CCMASK_2
1032                             | SystemZ::CCMASK_3)))
1033     return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1034
1035   // Next try inverting the value and testing a bit.  0/1 could be
1036   // handled this way too, but we dealt with that case above.
1037   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1038     return IPMConversion(-1, 0, SystemZ::IPM_CC);
1039
1040   // Handle cases where adding a value forces a non-sign bit to contain
1041   // the right value.
1042   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1043     return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1044   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1045     return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1046
1047   // The remaing cases are 1, 2, 0/1/3 and 0/2/3.  All these are
1048   // can be done by inverting the low CC bit and applying one of the
1049   // sign-based extractions above.
1050   if (CCMask == (CCValid & SystemZ::CCMASK_1))
1051     return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1052   if (CCMask == (CCValid & SystemZ::CCMASK_2))
1053     return IPMConversion(1 << SystemZ::IPM_CC,
1054                          TopBit - (3 << SystemZ::IPM_CC), 31);
1055   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1056                             | SystemZ::CCMASK_1
1057                             | SystemZ::CCMASK_3)))
1058     return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1059   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1060                             | SystemZ::CCMASK_2
1061                             | SystemZ::CCMASK_3)))
1062     return IPMConversion(1 << SystemZ::IPM_CC,
1063                          TopBit - (1 << SystemZ::IPM_CC), 31);
1064
1065   llvm_unreachable("Unexpected CC combination");
1066 }
1067
1068 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
1069 // can be converted to a comparison against zero, adjust the operands
1070 // as necessary.
1071 static void adjustZeroCmp(SelectionDAG &DAG, bool &IsUnsigned,
1072                           SDValue &CmpOp0, SDValue &CmpOp1,
1073                           unsigned &CCMask) {
1074   if (IsUnsigned)
1075     return;
1076
1077   ConstantSDNode *ConstOp1 = dyn_cast<ConstantSDNode>(CmpOp1.getNode());
1078   if (!ConstOp1)
1079     return;
1080
1081   int64_t Value = ConstOp1->getSExtValue();
1082   if ((Value == -1 && CCMask == SystemZ::CCMASK_CMP_GT) ||
1083       (Value == -1 && CCMask == SystemZ::CCMASK_CMP_LE) ||
1084       (Value == 1 && CCMask == SystemZ::CCMASK_CMP_LT) ||
1085       (Value == 1 && CCMask == SystemZ::CCMASK_CMP_GE)) {
1086     CCMask ^= SystemZ::CCMASK_CMP_EQ;
1087     CmpOp1 = DAG.getConstant(0, CmpOp1.getValueType());
1088   }
1089 }
1090
1091 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
1092 // is suitable for CLI(Y), CHHSI or CLHHSI, adjust the operands as necessary.
1093 static void adjustSubwordCmp(SelectionDAG &DAG, bool &IsUnsigned,
1094                              SDValue &CmpOp0, SDValue &CmpOp1,
1095                              unsigned &CCMask) {
1096   // For us to make any changes, it must a comparison between a single-use
1097   // load and a constant.
1098   if (!CmpOp0.hasOneUse() ||
1099       CmpOp0.getOpcode() != ISD::LOAD ||
1100       CmpOp1.getOpcode() != ISD::Constant)
1101     return;
1102
1103   // We must have an 8- or 16-bit load.
1104   LoadSDNode *Load = cast<LoadSDNode>(CmpOp0);
1105   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1106   if (NumBits != 8 && NumBits != 16)
1107     return;
1108
1109   // The load must be an extending one and the constant must be within the
1110   // range of the unextended value.
1111   ConstantSDNode *Constant = cast<ConstantSDNode>(CmpOp1);
1112   uint64_t Value = Constant->getZExtValue();
1113   uint64_t Mask = (1 << NumBits) - 1;
1114   if (Load->getExtensionType() == ISD::SEXTLOAD) {
1115     int64_t SignedValue = Constant->getSExtValue();
1116     if (uint64_t(SignedValue) + (1ULL << (NumBits - 1)) > Mask)
1117       return;
1118     // Unsigned comparison between two sign-extended values is equivalent
1119     // to unsigned comparison between two zero-extended values.
1120     if (IsUnsigned)
1121       Value &= Mask;
1122     else if (CCMask == SystemZ::CCMASK_CMP_EQ ||
1123              CCMask == SystemZ::CCMASK_CMP_NE)
1124       // Any choice of IsUnsigned is OK for equality comparisons.
1125       // We could use either CHHSI or CLHHSI for 16-bit comparisons,
1126       // but since we use CLHHSI for zero extensions, it seems better
1127       // to be consistent and do the same here.
1128       Value &= Mask, IsUnsigned = true;
1129     else if (NumBits == 8) {
1130       // Try to treat the comparison as unsigned, so that we can use CLI.
1131       // Adjust CCMask and Value as necessary.
1132       if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_LT)
1133         // Test whether the high bit of the byte is set.
1134         Value = 127, CCMask = SystemZ::CCMASK_CMP_GT, IsUnsigned = true;
1135       else if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_GE)
1136         // Test whether the high bit of the byte is clear.
1137         Value = 128, CCMask = SystemZ::CCMASK_CMP_LT, IsUnsigned = true;
1138       else
1139         // No instruction exists for this combination.
1140         return;
1141     }
1142   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1143     if (Value > Mask)
1144       return;
1145     // Signed comparison between two zero-extended values is equivalent
1146     // to unsigned comparison.
1147     IsUnsigned = true;
1148   } else
1149     return;
1150
1151   // Make sure that the first operand is an i32 of the right extension type.
1152   ISD::LoadExtType ExtType = IsUnsigned ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
1153   if (CmpOp0.getValueType() != MVT::i32 ||
1154       Load->getExtensionType() != ExtType)
1155     CmpOp0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1156                             Load->getChain(), Load->getBasePtr(),
1157                             Load->getPointerInfo(), Load->getMemoryVT(),
1158                             Load->isVolatile(), Load->isNonTemporal(),
1159                             Load->getAlignment());
1160
1161   // Make sure that the second operand is an i32 with the right value.
1162   if (CmpOp1.getValueType() != MVT::i32 ||
1163       Value != Constant->getZExtValue())
1164     CmpOp1 = DAG.getConstant(Value, MVT::i32);
1165 }
1166
1167 // Return true if Op is either an unextended load, or a load suitable
1168 // for integer register-memory comparisons of type ICmpType.
1169 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1170   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op.getNode());
1171   if (Load) {
1172     // There are no instructions to compare a register with a memory byte.
1173     if (Load->getMemoryVT() == MVT::i8)
1174       return false;
1175     // Otherwise decide on extension type.
1176     switch (Load->getExtensionType()) {
1177     case ISD::NON_EXTLOAD:
1178       return true;
1179     case ISD::SEXTLOAD:
1180       return ICmpType != SystemZICMP::UnsignedOnly;
1181     case ISD::ZEXTLOAD:
1182       return ICmpType != SystemZICMP::SignedOnly;
1183     default:
1184       break;
1185     }
1186   }
1187   return false;
1188 }
1189
1190 // Return true if it is better to swap comparison operands Op0 and Op1.
1191 // ICmpType is the type of an integer comparison.
1192 static bool shouldSwapCmpOperands(SDValue Op0, SDValue Op1,
1193                                   unsigned ICmpType) {
1194   // Leave f128 comparisons alone, since they have no memory forms.
1195   if (Op0.getValueType() == MVT::f128)
1196     return false;
1197
1198   // Always keep a floating-point constant second, since comparisons with
1199   // zero can use LOAD TEST and comparisons with other constants make a
1200   // natural memory operand.
1201   if (isa<ConstantFPSDNode>(Op1))
1202     return false;
1203
1204   // Never swap comparisons with zero since there are many ways to optimize
1205   // those later.
1206   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
1207   if (COp1 && COp1->getZExtValue() == 0)
1208     return false;
1209
1210   // Also keep natural memory operands second if the loaded value is
1211   // only used here.  Several comparisons have memory forms.
1212   if (isNaturalMemoryOperand(Op1, ICmpType) && Op1.hasOneUse())
1213     return false;
1214
1215   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1216   // In that case we generally prefer the memory to be second.
1217   if (isNaturalMemoryOperand(Op0, ICmpType) && Op0.hasOneUse()) {
1218     // The only exceptions are when the second operand is a constant and
1219     // we can use things like CHHSI.
1220     if (!COp1)
1221       return true;
1222     // The unsigned memory-immediate instructions can handle 16-bit
1223     // unsigned integers.
1224     if (ICmpType != SystemZICMP::SignedOnly &&
1225         isUInt<16>(COp1->getZExtValue()))
1226       return false;
1227     // The signed memory-immediate instructions can handle 16-bit
1228     // signed integers.
1229     if (ICmpType != SystemZICMP::UnsignedOnly &&
1230         isInt<16>(COp1->getSExtValue()))
1231       return false;
1232     return true;
1233   }
1234
1235   // Try to promote the use of CGFR and CLGFR.
1236   unsigned Opcode0 = Op0.getOpcode();
1237   if (ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1238     return true;
1239   if (ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1240     return true;
1241   if (ICmpType != SystemZICMP::SignedOnly &&
1242       Opcode0 == ISD::AND &&
1243       Op0.getOperand(1).getOpcode() == ISD::Constant &&
1244       cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1245     return true;
1246
1247   return false;
1248 }
1249
1250 // Return true if shift operation N has an in-range constant shift value.
1251 // Store it in ShiftVal if so.
1252 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1253   ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1254   if (!Shift)
1255     return false;
1256
1257   uint64_t Amount = Shift->getZExtValue();
1258   if (Amount >= N.getValueType().getSizeInBits())
1259     return false;
1260
1261   ShiftVal = Amount;
1262   return true;
1263 }
1264
1265 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1266 // instruction and whether the CC value is descriptive enough to handle
1267 // a comparison of type Opcode between the AND result and CmpVal.
1268 // CCMask says which comparison result is being tested and BitSize is
1269 // the number of bits in the operands.  If TEST UNDER MASK can be used,
1270 // return the corresponding CC mask, otherwise return 0.
1271 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1272                                      uint64_t Mask, uint64_t CmpVal,
1273                                      unsigned ICmpType) {
1274   assert(Mask != 0 && "ANDs with zero should have been removed by now");
1275
1276   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1277   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1278       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1279     return 0;
1280
1281   // Work out the masks for the lowest and highest bits.
1282   unsigned HighShift = 63 - countLeadingZeros(Mask);
1283   uint64_t High = uint64_t(1) << HighShift;
1284   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1285
1286   // Signed ordered comparisons are effectively unsigned if the sign
1287   // bit is dropped.
1288   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1289
1290   // Check for equality comparisons with 0, or the equivalent.
1291   if (CmpVal == 0) {
1292     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1293       return SystemZ::CCMASK_TM_ALL_0;
1294     if (CCMask == SystemZ::CCMASK_CMP_NE)
1295       return SystemZ::CCMASK_TM_SOME_1;
1296   }
1297   if (EffectivelyUnsigned && CmpVal <= Low) {
1298     if (CCMask == SystemZ::CCMASK_CMP_LT)
1299       return SystemZ::CCMASK_TM_ALL_0;
1300     if (CCMask == SystemZ::CCMASK_CMP_GE)
1301       return SystemZ::CCMASK_TM_SOME_1;
1302   }
1303   if (EffectivelyUnsigned && CmpVal < Low) {
1304     if (CCMask == SystemZ::CCMASK_CMP_LE)
1305       return SystemZ::CCMASK_TM_ALL_0;
1306     if (CCMask == SystemZ::CCMASK_CMP_GT)
1307       return SystemZ::CCMASK_TM_SOME_1;
1308   }
1309
1310   // Check for equality comparisons with the mask, or the equivalent.
1311   if (CmpVal == Mask) {
1312     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1313       return SystemZ::CCMASK_TM_ALL_1;
1314     if (CCMask == SystemZ::CCMASK_CMP_NE)
1315       return SystemZ::CCMASK_TM_SOME_0;
1316   }
1317   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1318     if (CCMask == SystemZ::CCMASK_CMP_GT)
1319       return SystemZ::CCMASK_TM_ALL_1;
1320     if (CCMask == SystemZ::CCMASK_CMP_LE)
1321       return SystemZ::CCMASK_TM_SOME_0;
1322   }
1323   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1324     if (CCMask == SystemZ::CCMASK_CMP_GE)
1325       return SystemZ::CCMASK_TM_ALL_1;
1326     if (CCMask == SystemZ::CCMASK_CMP_LT)
1327       return SystemZ::CCMASK_TM_SOME_0;
1328   }
1329
1330   // Check for ordered comparisons with the top bit.
1331   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1332     if (CCMask == SystemZ::CCMASK_CMP_LE)
1333       return SystemZ::CCMASK_TM_MSB_0;
1334     if (CCMask == SystemZ::CCMASK_CMP_GT)
1335       return SystemZ::CCMASK_TM_MSB_1;
1336   }
1337   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1338     if (CCMask == SystemZ::CCMASK_CMP_LT)
1339       return SystemZ::CCMASK_TM_MSB_0;
1340     if (CCMask == SystemZ::CCMASK_CMP_GE)
1341       return SystemZ::CCMASK_TM_MSB_1;
1342   }
1343
1344   // If there are just two bits, we can do equality checks for Low and High
1345   // as well.
1346   if (Mask == Low + High) {
1347     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1348       return SystemZ::CCMASK_TM_MIXED_MSB_0;
1349     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1350       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1351     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1352       return SystemZ::CCMASK_TM_MIXED_MSB_1;
1353     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1354       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1355   }
1356
1357   // Looks like we've exhausted our options.
1358   return 0;
1359 }
1360
1361 // See whether the comparison (Opcode CmpOp0, CmpOp1, ICmpType) can be
1362 // implemented as a TEST UNDER MASK instruction when the condition being
1363 // tested is as described by CCValid and CCMask.  Update the arguments
1364 // with the TM version if so.
1365 static void adjustForTestUnderMask(SelectionDAG &DAG, unsigned &Opcode,
1366                                    SDValue &CmpOp0, SDValue &CmpOp1,
1367                                    unsigned &CCValid, unsigned &CCMask,
1368                                    unsigned &ICmpType) {
1369   // Check that we have a comparison with a constant.
1370   ConstantSDNode *ConstCmpOp1 = dyn_cast<ConstantSDNode>(CmpOp1);
1371   if (!ConstCmpOp1)
1372     return;
1373   uint64_t CmpVal = ConstCmpOp1->getZExtValue();
1374
1375   // Check whether the nonconstant input is an AND with a constant mask.
1376   if (CmpOp0.getOpcode() != ISD::AND)
1377     return;
1378   SDValue AndOp0 = CmpOp0.getOperand(0);
1379   SDValue AndOp1 = CmpOp0.getOperand(1);
1380   ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(AndOp1.getNode());
1381   if (!Mask)
1382     return;
1383   uint64_t MaskVal = Mask->getZExtValue();
1384
1385   // Check whether the combination of mask, comparison value and comparison
1386   // type are suitable.
1387   unsigned BitSize = CmpOp0.getValueType().getSizeInBits();
1388   unsigned NewCCMask, ShiftVal;
1389   if (ICmpType != SystemZICMP::SignedOnly &&
1390       AndOp0.getOpcode() == ISD::SHL &&
1391       isSimpleShift(AndOp0, ShiftVal) &&
1392       (NewCCMask = getTestUnderMaskCond(BitSize, CCMask, MaskVal >> ShiftVal,
1393                                         CmpVal >> ShiftVal,
1394                                         SystemZICMP::Any))) {
1395     AndOp0 = AndOp0.getOperand(0);
1396     AndOp1 = DAG.getConstant(MaskVal >> ShiftVal, AndOp0.getValueType());
1397   } else if (ICmpType != SystemZICMP::SignedOnly &&
1398              AndOp0.getOpcode() == ISD::SRL &&
1399              isSimpleShift(AndOp0, ShiftVal) &&
1400              (NewCCMask = getTestUnderMaskCond(BitSize, CCMask,
1401                                                MaskVal << ShiftVal,
1402                                                CmpVal << ShiftVal,
1403                                                SystemZICMP::UnsignedOnly))) {
1404     AndOp0 = AndOp0.getOperand(0);
1405     AndOp1 = DAG.getConstant(MaskVal << ShiftVal, AndOp0.getValueType());
1406   } else {
1407     NewCCMask = getTestUnderMaskCond(BitSize, CCMask, MaskVal, CmpVal,
1408                                      ICmpType);
1409     if (!NewCCMask)
1410       return;
1411   }
1412
1413   // Go ahead and make the change.
1414   Opcode = SystemZISD::TM;
1415   CmpOp0 = AndOp0;
1416   CmpOp1 = AndOp1;
1417   ICmpType = (bool(NewCCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
1418               bool(NewCCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
1419   CCValid = SystemZ::CCMASK_TM;
1420   CCMask = NewCCMask;
1421 }
1422
1423 // Return a target node that compares CmpOp0 with CmpOp1 and stores a
1424 // 2-bit result in CC.  Set CCValid to the CCMASK_* of all possible
1425 // 2-bit results and CCMask to the subset of those results that are
1426 // associated with Cond.
1427 static SDValue emitCmp(const SystemZTargetMachine &TM, SelectionDAG &DAG,
1428                        SDLoc DL, SDValue CmpOp0, SDValue CmpOp1,
1429                        ISD::CondCode Cond, unsigned &CCValid,
1430                        unsigned &CCMask) {
1431   bool IsUnsigned = false;
1432   CCMask = CCMaskForCondCode(Cond);
1433   unsigned Opcode, ICmpType = 0;
1434   if (CmpOp0.getValueType().isFloatingPoint()) {
1435     CCValid = SystemZ::CCMASK_FCMP;
1436     Opcode = SystemZISD::FCMP;
1437   } else {
1438     IsUnsigned = CCMask & SystemZ::CCMASK_CMP_UO;
1439     CCValid = SystemZ::CCMASK_ICMP;
1440     CCMask &= CCValid;
1441     adjustZeroCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
1442     adjustSubwordCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
1443     Opcode = SystemZISD::ICMP;
1444     // Choose the type of comparison.  Equality and inequality tests can
1445     // use either signed or unsigned comparisons.  The choice also doesn't
1446     // matter if both sign bits are known to be clear.  In those cases we
1447     // want to give the main isel code the freedom to choose whichever
1448     // form fits best.
1449     if (CCMask == SystemZ::CCMASK_CMP_EQ ||
1450         CCMask == SystemZ::CCMASK_CMP_NE ||
1451         (DAG.SignBitIsZero(CmpOp0) && DAG.SignBitIsZero(CmpOp1)))
1452       ICmpType = SystemZICMP::Any;
1453     else if (IsUnsigned)
1454       ICmpType = SystemZICMP::UnsignedOnly;
1455     else
1456       ICmpType = SystemZICMP::SignedOnly;
1457   }
1458
1459   if (shouldSwapCmpOperands(CmpOp0, CmpOp1, ICmpType)) {
1460     std::swap(CmpOp0, CmpOp1);
1461     CCMask = ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1462               (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1463               (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1464               (CCMask & SystemZ::CCMASK_CMP_UO));
1465   }
1466
1467   adjustForTestUnderMask(DAG, Opcode, CmpOp0, CmpOp1, CCValid, CCMask,
1468                          ICmpType);
1469   if (Opcode == SystemZISD::ICMP || Opcode == SystemZISD::TM)
1470     return DAG.getNode(Opcode, DL, MVT::Glue, CmpOp0, CmpOp1,
1471                        DAG.getConstant(ICmpType, MVT::i32));
1472   return DAG.getNode(Opcode, DL, MVT::Glue, CmpOp0, CmpOp1);
1473 }
1474
1475 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
1476 // 64 bits.  Extend is the extension type to use.  Store the high part
1477 // in Hi and the low part in Lo.
1478 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
1479                             unsigned Extend, SDValue Op0, SDValue Op1,
1480                             SDValue &Hi, SDValue &Lo) {
1481   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
1482   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
1483   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
1484   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, DAG.getConstant(32, MVT::i64));
1485   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
1486   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
1487 }
1488
1489 // Lower a binary operation that produces two VT results, one in each
1490 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
1491 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
1492 // on the extended Op0 and (unextended) Op1.  Store the even register result
1493 // in Even and the odd register result in Odd.
1494 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1495                              unsigned Extend, unsigned Opcode,
1496                              SDValue Op0, SDValue Op1,
1497                              SDValue &Even, SDValue &Odd) {
1498   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1499   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1500                                SDValue(In128, 0), Op1);
1501   bool Is32Bit = is32Bit(VT);
1502   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
1503   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
1504 }
1505
1506 // Return an i32 value that is 1 if the CC value produced by Glue is
1507 // in the mask CCMask and 0 otherwise.  CC is known to have a value
1508 // in CCValid, so other values can be ignored.
1509 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
1510                          unsigned CCValid, unsigned CCMask) {
1511   IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
1512   SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
1513
1514   if (Conversion.XORValue)
1515     Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
1516                          DAG.getConstant(Conversion.XORValue, MVT::i32));
1517
1518   if (Conversion.AddValue)
1519     Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
1520                          DAG.getConstant(Conversion.AddValue, MVT::i32));
1521
1522   // The SHR/AND sequence should get optimized to an RISBG.
1523   Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
1524                        DAG.getConstant(Conversion.Bit, MVT::i32));
1525   if (Conversion.Bit != 31)
1526     Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
1527                          DAG.getConstant(1, MVT::i32));
1528   return Result;
1529 }
1530
1531 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
1532                                           SelectionDAG &DAG) const {
1533   SDValue CmpOp0   = Op.getOperand(0);
1534   SDValue CmpOp1   = Op.getOperand(1);
1535   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1536   SDLoc DL(Op);
1537
1538   unsigned CCValid, CCMask;
1539   SDValue Glue = emitCmp(TM, DAG, DL, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1540   return emitSETCC(DAG, DL, Glue, CCValid, CCMask);
1541 }
1542
1543 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1544   SDValue Chain    = Op.getOperand(0);
1545   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1546   SDValue CmpOp0   = Op.getOperand(2);
1547   SDValue CmpOp1   = Op.getOperand(3);
1548   SDValue Dest     = Op.getOperand(4);
1549   SDLoc DL(Op);
1550
1551   unsigned CCValid, CCMask;
1552   SDValue Glue = emitCmp(TM, DAG, DL, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1553   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
1554                      Chain, DAG.getConstant(CCValid, MVT::i32),
1555                      DAG.getConstant(CCMask, MVT::i32), Dest, Glue);
1556 }
1557
1558 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
1559                                               SelectionDAG &DAG) const {
1560   SDValue CmpOp0   = Op.getOperand(0);
1561   SDValue CmpOp1   = Op.getOperand(1);
1562   SDValue TrueOp   = Op.getOperand(2);
1563   SDValue FalseOp  = Op.getOperand(3);
1564   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1565   SDLoc DL(Op);
1566
1567   unsigned CCValid, CCMask;
1568   SDValue Glue = emitCmp(TM, DAG, DL, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1569
1570   // Special case for handling -1/0 results.  The shifts we use here
1571   // should get optimized with the IPM conversion sequence.
1572   ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
1573   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
1574   if (TrueC && FalseC) {
1575     int64_t TrueVal = TrueC->getSExtValue();
1576     int64_t FalseVal = FalseC->getSExtValue();
1577     if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
1578       // Invert the condition if we want -1 on false.
1579       if (TrueVal == 0)
1580         CCMask ^= CCValid;
1581       SDValue Result = emitSETCC(DAG, DL, Glue, CCValid, CCMask);
1582       EVT VT = Op.getValueType();
1583       // Extend the result to VT.  Upper bits are ignored.
1584       if (!is32Bit(VT))
1585         Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
1586       // Sign-extend from the low bit.
1587       SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, MVT::i32);
1588       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
1589       return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
1590     }
1591   }
1592
1593   SmallVector<SDValue, 5> Ops;
1594   Ops.push_back(TrueOp);
1595   Ops.push_back(FalseOp);
1596   Ops.push_back(DAG.getConstant(CCValid, MVT::i32));
1597   Ops.push_back(DAG.getConstant(CCMask, MVT::i32));
1598   Ops.push_back(Glue);
1599
1600   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1601   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, &Ops[0], Ops.size());
1602 }
1603
1604 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
1605                                                   SelectionDAG &DAG) const {
1606   SDLoc DL(Node);
1607   const GlobalValue *GV = Node->getGlobal();
1608   int64_t Offset = Node->getOffset();
1609   EVT PtrVT = getPointerTy();
1610   Reloc::Model RM = TM.getRelocationModel();
1611   CodeModel::Model CM = TM.getCodeModel();
1612
1613   SDValue Result;
1614   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
1615     // Assign anchors at 1<<12 byte boundaries.
1616     uint64_t Anchor = Offset & ~uint64_t(0xfff);
1617     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
1618     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1619
1620     // The offset can be folded into the address if it is aligned to a halfword.
1621     Offset -= Anchor;
1622     if (Offset != 0 && (Offset & 1) == 0) {
1623       SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
1624       Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
1625       Offset = 0;
1626     }
1627   } else {
1628     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
1629     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1630     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
1631                          MachinePointerInfo::getGOT(), false, false, false, 0);
1632   }
1633
1634   // If there was a non-zero offset that we didn't fold, create an explicit
1635   // addition for it.
1636   if (Offset != 0)
1637     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
1638                          DAG.getConstant(Offset, PtrVT));
1639
1640   return Result;
1641 }
1642
1643 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
1644                                                      SelectionDAG &DAG) const {
1645   SDLoc DL(Node);
1646   const GlobalValue *GV = Node->getGlobal();
1647   EVT PtrVT = getPointerTy();
1648   TLSModel::Model model = TM.getTLSModel(GV);
1649
1650   if (model != TLSModel::LocalExec)
1651     llvm_unreachable("only local-exec TLS mode supported");
1652
1653   // The high part of the thread pointer is in access register 0.
1654   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1655                              DAG.getConstant(0, MVT::i32));
1656   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
1657
1658   // The low part of the thread pointer is in access register 1.
1659   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1660                              DAG.getConstant(1, MVT::i32));
1661   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
1662
1663   // Merge them into a single 64-bit address.
1664   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
1665                                     DAG.getConstant(32, PtrVT));
1666   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
1667
1668   // Get the offset of GA from the thread pointer.
1669   SystemZConstantPoolValue *CPV =
1670     SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
1671
1672   // Force the offset into the constant pool and load it from there.
1673   SDValue CPAddr = DAG.getConstantPool(CPV, PtrVT, 8);
1674   SDValue Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1675                                CPAddr, MachinePointerInfo::getConstantPool(),
1676                                false, false, false, 0);
1677
1678   // Add the base and offset together.
1679   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
1680 }
1681
1682 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
1683                                                  SelectionDAG &DAG) const {
1684   SDLoc DL(Node);
1685   const BlockAddress *BA = Node->getBlockAddress();
1686   int64_t Offset = Node->getOffset();
1687   EVT PtrVT = getPointerTy();
1688
1689   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
1690   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1691   return Result;
1692 }
1693
1694 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
1695                                               SelectionDAG &DAG) const {
1696   SDLoc DL(JT);
1697   EVT PtrVT = getPointerTy();
1698   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1699
1700   // Use LARL to load the address of the table.
1701   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1702 }
1703
1704 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
1705                                                  SelectionDAG &DAG) const {
1706   SDLoc DL(CP);
1707   EVT PtrVT = getPointerTy();
1708
1709   SDValue Result;
1710   if (CP->isMachineConstantPoolEntry())
1711     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1712                                        CP->getAlignment());
1713   else
1714     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1715                                        CP->getAlignment(), CP->getOffset());
1716
1717   // Use LARL to load the address of the constant pool entry.
1718   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1719 }
1720
1721 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
1722                                             SelectionDAG &DAG) const {
1723   SDLoc DL(Op);
1724   SDValue In = Op.getOperand(0);
1725   EVT InVT = In.getValueType();
1726   EVT ResVT = Op.getValueType();
1727
1728   if (InVT == MVT::i32 && ResVT == MVT::f32) {
1729     SDValue In64;
1730     if (Subtarget.hasHighWord()) {
1731       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
1732                                        MVT::i64);
1733       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
1734                                        MVT::i64, SDValue(U64, 0), In);
1735     } else {
1736       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
1737       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
1738                          DAG.getConstant(32, MVT::i64));
1739     }
1740     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
1741     return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
1742                                       DL, MVT::f32, Out64);
1743   }
1744   if (InVT == MVT::f32 && ResVT == MVT::i32) {
1745     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
1746     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
1747                                              MVT::f64, SDValue(U64, 0), In);
1748     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
1749     if (Subtarget.hasHighWord())
1750       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
1751                                         MVT::i32, Out64);
1752     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
1753                                 DAG.getConstant(32, MVT::i64));
1754     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
1755   }
1756   llvm_unreachable("Unexpected bitcast combination");
1757 }
1758
1759 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
1760                                             SelectionDAG &DAG) const {
1761   MachineFunction &MF = DAG.getMachineFunction();
1762   SystemZMachineFunctionInfo *FuncInfo =
1763     MF.getInfo<SystemZMachineFunctionInfo>();
1764   EVT PtrVT = getPointerTy();
1765
1766   SDValue Chain   = Op.getOperand(0);
1767   SDValue Addr    = Op.getOperand(1);
1768   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1769   SDLoc DL(Op);
1770
1771   // The initial values of each field.
1772   const unsigned NumFields = 4;
1773   SDValue Fields[NumFields] = {
1774     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), PtrVT),
1775     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), PtrVT),
1776     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
1777     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
1778   };
1779
1780   // Store each field into its respective slot.
1781   SDValue MemOps[NumFields];
1782   unsigned Offset = 0;
1783   for (unsigned I = 0; I < NumFields; ++I) {
1784     SDValue FieldAddr = Addr;
1785     if (Offset != 0)
1786       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
1787                               DAG.getIntPtrConstant(Offset));
1788     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
1789                              MachinePointerInfo(SV, Offset),
1790                              false, false, 0);
1791     Offset += 8;
1792   }
1793   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps, NumFields);
1794 }
1795
1796 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
1797                                            SelectionDAG &DAG) const {
1798   SDValue Chain      = Op.getOperand(0);
1799   SDValue DstPtr     = Op.getOperand(1);
1800   SDValue SrcPtr     = Op.getOperand(2);
1801   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
1802   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
1803   SDLoc DL(Op);
1804
1805   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32),
1806                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
1807                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
1808 }
1809
1810 SDValue SystemZTargetLowering::
1811 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
1812   SDValue Chain = Op.getOperand(0);
1813   SDValue Size  = Op.getOperand(1);
1814   SDLoc DL(Op);
1815
1816   unsigned SPReg = getStackPointerRegisterToSaveRestore();
1817
1818   // Get a reference to the stack pointer.
1819   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
1820
1821   // Get the new stack pointer value.
1822   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
1823
1824   // Copy the new stack pointer back.
1825   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
1826
1827   // The allocated data lives above the 160 bytes allocated for the standard
1828   // frame, plus any outgoing stack arguments.  We don't know how much that
1829   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
1830   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
1831   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
1832
1833   SDValue Ops[2] = { Result, Chain };
1834   return DAG.getMergeValues(Ops, 2, DL);
1835 }
1836
1837 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
1838                                               SelectionDAG &DAG) const {
1839   EVT VT = Op.getValueType();
1840   SDLoc DL(Op);
1841   SDValue Ops[2];
1842   if (is32Bit(VT))
1843     // Just do a normal 64-bit multiplication and extract the results.
1844     // We define this so that it can be used for constant division.
1845     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
1846                     Op.getOperand(1), Ops[1], Ops[0]);
1847   else {
1848     // Do a full 128-bit multiplication based on UMUL_LOHI64:
1849     //
1850     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
1851     //
1852     // but using the fact that the upper halves are either all zeros
1853     // or all ones:
1854     //
1855     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
1856     //
1857     // and grouping the right terms together since they are quicker than the
1858     // multiplication:
1859     //
1860     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
1861     SDValue C63 = DAG.getConstant(63, MVT::i64);
1862     SDValue LL = Op.getOperand(0);
1863     SDValue RL = Op.getOperand(1);
1864     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
1865     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
1866     // UMUL_LOHI64 returns the low result in the odd register and the high
1867     // result in the even register.  SMUL_LOHI is defined to return the
1868     // low half first, so the results are in reverse order.
1869     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
1870                      LL, RL, Ops[1], Ops[0]);
1871     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
1872     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
1873     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
1874     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
1875   }
1876   return DAG.getMergeValues(Ops, 2, DL);
1877 }
1878
1879 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
1880                                               SelectionDAG &DAG) const {
1881   EVT VT = Op.getValueType();
1882   SDLoc DL(Op);
1883   SDValue Ops[2];
1884   if (is32Bit(VT))
1885     // Just do a normal 64-bit multiplication and extract the results.
1886     // We define this so that it can be used for constant division.
1887     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
1888                     Op.getOperand(1), Ops[1], Ops[0]);
1889   else
1890     // UMUL_LOHI64 returns the low result in the odd register and the high
1891     // result in the even register.  UMUL_LOHI is defined to return the
1892     // low half first, so the results are in reverse order.
1893     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
1894                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1895   return DAG.getMergeValues(Ops, 2, DL);
1896 }
1897
1898 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
1899                                             SelectionDAG &DAG) const {
1900   SDValue Op0 = Op.getOperand(0);
1901   SDValue Op1 = Op.getOperand(1);
1902   EVT VT = Op.getValueType();
1903   SDLoc DL(Op);
1904   unsigned Opcode;
1905
1906   // We use DSGF for 32-bit division.
1907   if (is32Bit(VT)) {
1908     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
1909     Opcode = SystemZISD::SDIVREM32;
1910   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
1911     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
1912     Opcode = SystemZISD::SDIVREM32;
1913   } else    
1914     Opcode = SystemZISD::SDIVREM64;
1915
1916   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
1917   // input is "don't care".  The instruction returns the remainder in
1918   // the even register and the quotient in the odd register.
1919   SDValue Ops[2];
1920   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
1921                    Op0, Op1, Ops[1], Ops[0]);
1922   return DAG.getMergeValues(Ops, 2, DL);
1923 }
1924
1925 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
1926                                             SelectionDAG &DAG) const {
1927   EVT VT = Op.getValueType();
1928   SDLoc DL(Op);
1929
1930   // DL(G) uses a double-width dividend, so we need to clear the even
1931   // register in the GR128 input.  The instruction returns the remainder
1932   // in the even register and the quotient in the odd register.
1933   SDValue Ops[2];
1934   if (is32Bit(VT))
1935     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
1936                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1937   else
1938     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
1939                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1940   return DAG.getMergeValues(Ops, 2, DL);
1941 }
1942
1943 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
1944   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
1945
1946   // Get the known-zero masks for each operand.
1947   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
1948   APInt KnownZero[2], KnownOne[2];
1949   DAG.ComputeMaskedBits(Ops[0], KnownZero[0], KnownOne[0]);
1950   DAG.ComputeMaskedBits(Ops[1], KnownZero[1], KnownOne[1]);
1951
1952   // See if the upper 32 bits of one operand and the lower 32 bits of the
1953   // other are known zero.  They are the low and high operands respectively.
1954   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
1955                        KnownZero[1].getZExtValue() };
1956   unsigned High, Low;
1957   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
1958     High = 1, Low = 0;
1959   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
1960     High = 0, Low = 1;
1961   else
1962     return Op;
1963
1964   SDValue LowOp = Ops[Low];
1965   SDValue HighOp = Ops[High];
1966
1967   // If the high part is a constant, we're better off using IILH.
1968   if (HighOp.getOpcode() == ISD::Constant)
1969     return Op;
1970
1971   // If the low part is a constant that is outside the range of LHI,
1972   // then we're better off using IILF.
1973   if (LowOp.getOpcode() == ISD::Constant) {
1974     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
1975     if (!isInt<16>(Value))
1976       return Op;
1977   }
1978
1979   // Check whether the high part is an AND that doesn't change the
1980   // high 32 bits and just masks out low bits.  We can skip it if so.
1981   if (HighOp.getOpcode() == ISD::AND &&
1982       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
1983     SDValue HighOp0 = HighOp.getOperand(0);
1984     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
1985     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
1986       HighOp = HighOp0;
1987   }
1988
1989   // Take advantage of the fact that all GR32 operations only change the
1990   // low 32 bits by truncating Low to an i32 and inserting it directly
1991   // using a subreg.  The interesting cases are those where the truncation
1992   // can be folded.
1993   SDLoc DL(Op);
1994   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
1995   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
1996                                    MVT::i64, HighOp, Low32);
1997 }
1998
1999 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
2000 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
2001 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
2002                                                 SelectionDAG &DAG,
2003                                                 unsigned Opcode) const {
2004   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
2005
2006   // 32-bit operations need no code outside the main loop.
2007   EVT NarrowVT = Node->getMemoryVT();
2008   EVT WideVT = MVT::i32;
2009   if (NarrowVT == WideVT)
2010     return Op;
2011
2012   int64_t BitSize = NarrowVT.getSizeInBits();
2013   SDValue ChainIn = Node->getChain();
2014   SDValue Addr = Node->getBasePtr();
2015   SDValue Src2 = Node->getVal();
2016   MachineMemOperand *MMO = Node->getMemOperand();
2017   SDLoc DL(Node);
2018   EVT PtrVT = Addr.getValueType();
2019
2020   // Convert atomic subtracts of constants into additions.
2021   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
2022     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Src2)) {
2023       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
2024       Src2 = DAG.getConstant(-Const->getSExtValue(), Src2.getValueType());
2025     }
2026
2027   // Get the address of the containing word.
2028   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2029                                     DAG.getConstant(-4, PtrVT));
2030
2031   // Get the number of bits that the word must be rotated left in order
2032   // to bring the field to the top bits of a GR32.
2033   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2034                                  DAG.getConstant(3, PtrVT));
2035   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2036
2037   // Get the complementing shift amount, for rotating a field in the top
2038   // bits back to its proper position.
2039   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2040                                     DAG.getConstant(0, WideVT), BitShift);
2041
2042   // Extend the source operand to 32 bits and prepare it for the inner loop.
2043   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
2044   // operations require the source to be shifted in advance.  (This shift
2045   // can be folded if the source is constant.)  For AND and NAND, the lower
2046   // bits must be set, while for other opcodes they should be left clear.
2047   if (Opcode != SystemZISD::ATOMIC_SWAPW)
2048     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
2049                        DAG.getConstant(32 - BitSize, WideVT));
2050   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
2051       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
2052     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
2053                        DAG.getConstant(uint32_t(-1) >> BitSize, WideVT));
2054
2055   // Construct the ATOMIC_LOADW_* node.
2056   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2057   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
2058                     DAG.getConstant(BitSize, WideVT) };
2059   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
2060                                              array_lengthof(Ops),
2061                                              NarrowVT, MMO);
2062
2063   // Rotate the result of the final CS so that the field is in the lower
2064   // bits of a GR32, then truncate it.
2065   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
2066                                     DAG.getConstant(BitSize, WideVT));
2067   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
2068
2069   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
2070   return DAG.getMergeValues(RetOps, 2, DL);
2071 }
2072
2073 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
2074 // into a fullword ATOMIC_CMP_SWAPW operation.
2075 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
2076                                                     SelectionDAG &DAG) const {
2077   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
2078
2079   // We have native support for 32-bit compare and swap.
2080   EVT NarrowVT = Node->getMemoryVT();
2081   EVT WideVT = MVT::i32;
2082   if (NarrowVT == WideVT)
2083     return Op;
2084
2085   int64_t BitSize = NarrowVT.getSizeInBits();
2086   SDValue ChainIn = Node->getOperand(0);
2087   SDValue Addr = Node->getOperand(1);
2088   SDValue CmpVal = Node->getOperand(2);
2089   SDValue SwapVal = Node->getOperand(3);
2090   MachineMemOperand *MMO = Node->getMemOperand();
2091   SDLoc DL(Node);
2092   EVT PtrVT = Addr.getValueType();
2093
2094   // Get the address of the containing word.
2095   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2096                                     DAG.getConstant(-4, PtrVT));
2097
2098   // Get the number of bits that the word must be rotated left in order
2099   // to bring the field to the top bits of a GR32.
2100   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2101                                  DAG.getConstant(3, PtrVT));
2102   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2103
2104   // Get the complementing shift amount, for rotating a field in the top
2105   // bits back to its proper position.
2106   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2107                                     DAG.getConstant(0, WideVT), BitShift);
2108
2109   // Construct the ATOMIC_CMP_SWAPW node.
2110   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2111   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
2112                     NegBitShift, DAG.getConstant(BitSize, WideVT) };
2113   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
2114                                              VTList, Ops, array_lengthof(Ops),
2115                                              NarrowVT, MMO);
2116   return AtomicOp;
2117 }
2118
2119 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
2120                                               SelectionDAG &DAG) const {
2121   MachineFunction &MF = DAG.getMachineFunction();
2122   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2123   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
2124                             SystemZ::R15D, Op.getValueType());
2125 }
2126
2127 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
2128                                                  SelectionDAG &DAG) const {
2129   MachineFunction &MF = DAG.getMachineFunction();
2130   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2131   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
2132                           SystemZ::R15D, Op.getOperand(1));
2133 }
2134
2135 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
2136                                              SelectionDAG &DAG) const {
2137   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2138   if (!IsData)
2139     // Just preserve the chain.
2140     return Op.getOperand(0);
2141
2142   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2143   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
2144   MemIntrinsicSDNode *Node = cast<MemIntrinsicSDNode>(Op.getNode());
2145   SDValue Ops[] = {
2146     Op.getOperand(0),
2147     DAG.getConstant(Code, MVT::i32),
2148     Op.getOperand(1)
2149   };
2150   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, SDLoc(Op),
2151                                  Node->getVTList(), Ops, array_lengthof(Ops),
2152                                  Node->getMemoryVT(), Node->getMemOperand());
2153 }
2154
2155 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
2156                                               SelectionDAG &DAG) const {
2157   switch (Op.getOpcode()) {
2158   case ISD::BR_CC:
2159     return lowerBR_CC(Op, DAG);
2160   case ISD::SELECT_CC:
2161     return lowerSELECT_CC(Op, DAG);
2162   case ISD::SETCC:
2163     return lowerSETCC(Op, DAG);
2164   case ISD::GlobalAddress:
2165     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
2166   case ISD::GlobalTLSAddress:
2167     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
2168   case ISD::BlockAddress:
2169     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
2170   case ISD::JumpTable:
2171     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
2172   case ISD::ConstantPool:
2173     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
2174   case ISD::BITCAST:
2175     return lowerBITCAST(Op, DAG);
2176   case ISD::VASTART:
2177     return lowerVASTART(Op, DAG);
2178   case ISD::VACOPY:
2179     return lowerVACOPY(Op, DAG);
2180   case ISD::DYNAMIC_STACKALLOC:
2181     return lowerDYNAMIC_STACKALLOC(Op, DAG);
2182   case ISD::SMUL_LOHI:
2183     return lowerSMUL_LOHI(Op, DAG);
2184   case ISD::UMUL_LOHI:
2185     return lowerUMUL_LOHI(Op, DAG);
2186   case ISD::SDIVREM:
2187     return lowerSDIVREM(Op, DAG);
2188   case ISD::UDIVREM:
2189     return lowerUDIVREM(Op, DAG);
2190   case ISD::OR:
2191     return lowerOR(Op, DAG);
2192   case ISD::ATOMIC_SWAP:
2193     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_SWAPW);
2194   case ISD::ATOMIC_LOAD_ADD:
2195     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
2196   case ISD::ATOMIC_LOAD_SUB:
2197     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
2198   case ISD::ATOMIC_LOAD_AND:
2199     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
2200   case ISD::ATOMIC_LOAD_OR:
2201     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
2202   case ISD::ATOMIC_LOAD_XOR:
2203     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
2204   case ISD::ATOMIC_LOAD_NAND:
2205     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
2206   case ISD::ATOMIC_LOAD_MIN:
2207     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
2208   case ISD::ATOMIC_LOAD_MAX:
2209     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
2210   case ISD::ATOMIC_LOAD_UMIN:
2211     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
2212   case ISD::ATOMIC_LOAD_UMAX:
2213     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
2214   case ISD::ATOMIC_CMP_SWAP:
2215     return lowerATOMIC_CMP_SWAP(Op, DAG);
2216   case ISD::STACKSAVE:
2217     return lowerSTACKSAVE(Op, DAG);
2218   case ISD::STACKRESTORE:
2219     return lowerSTACKRESTORE(Op, DAG);
2220   case ISD::PREFETCH:
2221     return lowerPREFETCH(Op, DAG);
2222   default:
2223     llvm_unreachable("Unexpected node to lower");
2224   }
2225 }
2226
2227 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
2228 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
2229   switch (Opcode) {
2230     OPCODE(RET_FLAG);
2231     OPCODE(CALL);
2232     OPCODE(SIBCALL);
2233     OPCODE(PCREL_WRAPPER);
2234     OPCODE(PCREL_OFFSET);
2235     OPCODE(ICMP);
2236     OPCODE(FCMP);
2237     OPCODE(TM);
2238     OPCODE(BR_CCMASK);
2239     OPCODE(SELECT_CCMASK);
2240     OPCODE(ADJDYNALLOC);
2241     OPCODE(EXTRACT_ACCESS);
2242     OPCODE(UMUL_LOHI64);
2243     OPCODE(SDIVREM64);
2244     OPCODE(UDIVREM32);
2245     OPCODE(UDIVREM64);
2246     OPCODE(MVC);
2247     OPCODE(MVC_LOOP);
2248     OPCODE(NC);
2249     OPCODE(NC_LOOP);
2250     OPCODE(OC);
2251     OPCODE(OC_LOOP);
2252     OPCODE(XC);
2253     OPCODE(XC_LOOP);
2254     OPCODE(CLC);
2255     OPCODE(CLC_LOOP);
2256     OPCODE(STRCMP);
2257     OPCODE(STPCPY);
2258     OPCODE(SEARCH_STRING);
2259     OPCODE(IPM);
2260     OPCODE(ATOMIC_SWAPW);
2261     OPCODE(ATOMIC_LOADW_ADD);
2262     OPCODE(ATOMIC_LOADW_SUB);
2263     OPCODE(ATOMIC_LOADW_AND);
2264     OPCODE(ATOMIC_LOADW_OR);
2265     OPCODE(ATOMIC_LOADW_XOR);
2266     OPCODE(ATOMIC_LOADW_NAND);
2267     OPCODE(ATOMIC_LOADW_MIN);
2268     OPCODE(ATOMIC_LOADW_MAX);
2269     OPCODE(ATOMIC_LOADW_UMIN);
2270     OPCODE(ATOMIC_LOADW_UMAX);
2271     OPCODE(ATOMIC_CMP_SWAPW);
2272     OPCODE(PREFETCH);
2273   }
2274   return NULL;
2275 #undef OPCODE
2276 }
2277
2278 //===----------------------------------------------------------------------===//
2279 // Custom insertion
2280 //===----------------------------------------------------------------------===//
2281
2282 // Create a new basic block after MBB.
2283 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
2284   MachineFunction &MF = *MBB->getParent();
2285   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
2286   MF.insert(llvm::next(MachineFunction::iterator(MBB)), NewMBB);
2287   return NewMBB;
2288 }
2289
2290 // Split MBB after MI and return the new block (the one that contains
2291 // instructions after MI).
2292 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
2293                                           MachineBasicBlock *MBB) {
2294   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
2295   NewMBB->splice(NewMBB->begin(), MBB,
2296                  llvm::next(MachineBasicBlock::iterator(MI)),
2297                  MBB->end());
2298   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
2299   return NewMBB;
2300 }
2301
2302 // Split MBB before MI and return the new block (the one that contains MI).
2303 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
2304                                            MachineBasicBlock *MBB) {
2305   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
2306   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
2307   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
2308   return NewMBB;
2309 }
2310
2311 // Force base value Base into a register before MI.  Return the register.
2312 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
2313                          const SystemZInstrInfo *TII) {
2314   if (Base.isReg())
2315     return Base.getReg();
2316
2317   MachineBasicBlock *MBB = MI->getParent();
2318   MachineFunction &MF = *MBB->getParent();
2319   MachineRegisterInfo &MRI = MF.getRegInfo();
2320
2321   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2322   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
2323     .addOperand(Base).addImm(0).addReg(0);
2324   return Reg;
2325 }
2326
2327 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
2328 MachineBasicBlock *
2329 SystemZTargetLowering::emitSelect(MachineInstr *MI,
2330                                   MachineBasicBlock *MBB) const {
2331   const SystemZInstrInfo *TII = TM.getInstrInfo();
2332
2333   unsigned DestReg  = MI->getOperand(0).getReg();
2334   unsigned TrueReg  = MI->getOperand(1).getReg();
2335   unsigned FalseReg = MI->getOperand(2).getReg();
2336   unsigned CCValid  = MI->getOperand(3).getImm();
2337   unsigned CCMask   = MI->getOperand(4).getImm();
2338   DebugLoc DL       = MI->getDebugLoc();
2339
2340   MachineBasicBlock *StartMBB = MBB;
2341   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
2342   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
2343
2344   //  StartMBB:
2345   //   BRC CCMask, JoinMBB
2346   //   # fallthrough to FalseMBB
2347   MBB = StartMBB;
2348   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2349     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
2350   MBB->addSuccessor(JoinMBB);
2351   MBB->addSuccessor(FalseMBB);
2352
2353   //  FalseMBB:
2354   //   # fallthrough to JoinMBB
2355   MBB = FalseMBB;
2356   MBB->addSuccessor(JoinMBB);
2357
2358   //  JoinMBB:
2359   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
2360   //  ...
2361   MBB = JoinMBB;
2362   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
2363     .addReg(TrueReg).addMBB(StartMBB)
2364     .addReg(FalseReg).addMBB(FalseMBB);
2365
2366   MI->eraseFromParent();
2367   return JoinMBB;
2368 }
2369
2370 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
2371 // StoreOpcode is the store to use and Invert says whether the store should
2372 // happen when the condition is false rather than true.  If a STORE ON
2373 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
2374 MachineBasicBlock *
2375 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
2376                                      MachineBasicBlock *MBB,
2377                                      unsigned StoreOpcode, unsigned STOCOpcode,
2378                                      bool Invert) const {
2379   const SystemZInstrInfo *TII = TM.getInstrInfo();
2380
2381   unsigned SrcReg     = MI->getOperand(0).getReg();
2382   MachineOperand Base = MI->getOperand(1);
2383   int64_t Disp        = MI->getOperand(2).getImm();
2384   unsigned IndexReg   = MI->getOperand(3).getReg();
2385   unsigned CCValid    = MI->getOperand(4).getImm();
2386   unsigned CCMask     = MI->getOperand(5).getImm();
2387   DebugLoc DL         = MI->getDebugLoc();
2388
2389   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
2390
2391   // Use STOCOpcode if possible.  We could use different store patterns in
2392   // order to avoid matching the index register, but the performance trade-offs
2393   // might be more complicated in that case.
2394   if (STOCOpcode && !IndexReg && TM.getSubtargetImpl()->hasLoadStoreOnCond()) {
2395     if (Invert)
2396       CCMask ^= CCValid;
2397     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
2398       .addReg(SrcReg).addOperand(Base).addImm(Disp)
2399       .addImm(CCValid).addImm(CCMask);
2400     MI->eraseFromParent();
2401     return MBB;
2402   }
2403
2404   // Get the condition needed to branch around the store.
2405   if (!Invert)
2406     CCMask ^= CCValid;
2407
2408   MachineBasicBlock *StartMBB = MBB;
2409   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
2410   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
2411
2412   //  StartMBB:
2413   //   BRC CCMask, JoinMBB
2414   //   # fallthrough to FalseMBB
2415   MBB = StartMBB;
2416   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2417     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
2418   MBB->addSuccessor(JoinMBB);
2419   MBB->addSuccessor(FalseMBB);
2420
2421   //  FalseMBB:
2422   //   store %SrcReg, %Disp(%Index,%Base)
2423   //   # fallthrough to JoinMBB
2424   MBB = FalseMBB;
2425   BuildMI(MBB, DL, TII->get(StoreOpcode))
2426     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
2427   MBB->addSuccessor(JoinMBB);
2428
2429   MI->eraseFromParent();
2430   return JoinMBB;
2431 }
2432
2433 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
2434 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
2435 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
2436 // BitSize is the width of the field in bits, or 0 if this is a partword
2437 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
2438 // is one of the operands.  Invert says whether the field should be
2439 // inverted after performing BinOpcode (e.g. for NAND).
2440 MachineBasicBlock *
2441 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
2442                                             MachineBasicBlock *MBB,
2443                                             unsigned BinOpcode,
2444                                             unsigned BitSize,
2445                                             bool Invert) const {
2446   const SystemZInstrInfo *TII = TM.getInstrInfo();
2447   MachineFunction &MF = *MBB->getParent();
2448   MachineRegisterInfo &MRI = MF.getRegInfo();
2449   bool IsSubWord = (BitSize < 32);
2450
2451   // Extract the operands.  Base can be a register or a frame index.
2452   // Src2 can be a register or immediate.
2453   unsigned Dest        = MI->getOperand(0).getReg();
2454   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2455   int64_t Disp         = MI->getOperand(2).getImm();
2456   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
2457   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2458   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2459   DebugLoc DL          = MI->getDebugLoc();
2460   if (IsSubWord)
2461     BitSize = MI->getOperand(6).getImm();
2462
2463   // Subword operations use 32-bit registers.
2464   const TargetRegisterClass *RC = (BitSize <= 32 ?
2465                                    &SystemZ::GR32BitRegClass :
2466                                    &SystemZ::GR64BitRegClass);
2467   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2468   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2469
2470   // Get the right opcodes for the displacement.
2471   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2472   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2473   assert(LOpcode && CSOpcode && "Displacement out of range");
2474
2475   // Create virtual registers for temporary results.
2476   unsigned OrigVal       = MRI.createVirtualRegister(RC);
2477   unsigned OldVal        = MRI.createVirtualRegister(RC);
2478   unsigned NewVal        = (BinOpcode || IsSubWord ?
2479                             MRI.createVirtualRegister(RC) : Src2.getReg());
2480   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
2481   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
2482
2483   // Insert a basic block for the main loop.
2484   MachineBasicBlock *StartMBB = MBB;
2485   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
2486   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2487
2488   //  StartMBB:
2489   //   ...
2490   //   %OrigVal = L Disp(%Base)
2491   //   # fall through to LoopMMB
2492   MBB = StartMBB;
2493   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
2494     .addOperand(Base).addImm(Disp).addReg(0);
2495   MBB->addSuccessor(LoopMBB);
2496
2497   //  LoopMBB:
2498   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
2499   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
2500   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
2501   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2502   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2503   //   JNE LoopMBB
2504   //   # fall through to DoneMMB
2505   MBB = LoopMBB;
2506   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2507     .addReg(OrigVal).addMBB(StartMBB)
2508     .addReg(Dest).addMBB(LoopMBB);
2509   if (IsSubWord)
2510     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
2511       .addReg(OldVal).addReg(BitShift).addImm(0);
2512   if (Invert) {
2513     // Perform the operation normally and then invert every bit of the field.
2514     unsigned Tmp = MRI.createVirtualRegister(RC);
2515     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
2516       .addReg(RotatedOldVal).addOperand(Src2);
2517     if (BitSize < 32)
2518       // XILF with the upper BitSize bits set.
2519       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
2520         .addReg(Tmp).addImm(uint32_t(~0 << (32 - BitSize)));
2521     else if (BitSize == 32)
2522       // XILF with every bit set.
2523       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
2524         .addReg(Tmp).addImm(~uint32_t(0));
2525     else {
2526       // Use LCGR and add -1 to the result, which is more compact than
2527       // an XILF, XILH pair.
2528       unsigned Tmp2 = MRI.createVirtualRegister(RC);
2529       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
2530       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
2531         .addReg(Tmp2).addImm(-1);
2532     }
2533   } else if (BinOpcode)
2534     // A simply binary operation.
2535     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
2536       .addReg(RotatedOldVal).addOperand(Src2);
2537   else if (IsSubWord)
2538     // Use RISBG to rotate Src2 into position and use it to replace the
2539     // field in RotatedOldVal.
2540     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
2541       .addReg(RotatedOldVal).addReg(Src2.getReg())
2542       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
2543   if (IsSubWord)
2544     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2545       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2546   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2547     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2548   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2549     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2550   MBB->addSuccessor(LoopMBB);
2551   MBB->addSuccessor(DoneMBB);
2552
2553   MI->eraseFromParent();
2554   return DoneMBB;
2555 }
2556
2557 // Implement EmitInstrWithCustomInserter for pseudo
2558 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
2559 // instruction that should be used to compare the current field with the
2560 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
2561 // for when the current field should be kept.  BitSize is the width of
2562 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
2563 MachineBasicBlock *
2564 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
2565                                             MachineBasicBlock *MBB,
2566                                             unsigned CompareOpcode,
2567                                             unsigned KeepOldMask,
2568                                             unsigned BitSize) const {
2569   const SystemZInstrInfo *TII = TM.getInstrInfo();
2570   MachineFunction &MF = *MBB->getParent();
2571   MachineRegisterInfo &MRI = MF.getRegInfo();
2572   bool IsSubWord = (BitSize < 32);
2573
2574   // Extract the operands.  Base can be a register or a frame index.
2575   unsigned Dest        = MI->getOperand(0).getReg();
2576   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2577   int64_t  Disp        = MI->getOperand(2).getImm();
2578   unsigned Src2        = MI->getOperand(3).getReg();
2579   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2580   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2581   DebugLoc DL          = MI->getDebugLoc();
2582   if (IsSubWord)
2583     BitSize = MI->getOperand(6).getImm();
2584
2585   // Subword operations use 32-bit registers.
2586   const TargetRegisterClass *RC = (BitSize <= 32 ?
2587                                    &SystemZ::GR32BitRegClass :
2588                                    &SystemZ::GR64BitRegClass);
2589   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2590   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2591
2592   // Get the right opcodes for the displacement.
2593   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2594   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2595   assert(LOpcode && CSOpcode && "Displacement out of range");
2596
2597   // Create virtual registers for temporary results.
2598   unsigned OrigVal       = MRI.createVirtualRegister(RC);
2599   unsigned OldVal        = MRI.createVirtualRegister(RC);
2600   unsigned NewVal        = MRI.createVirtualRegister(RC);
2601   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
2602   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
2603   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
2604
2605   // Insert 3 basic blocks for the loop.
2606   MachineBasicBlock *StartMBB  = MBB;
2607   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
2608   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
2609   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
2610   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
2611
2612   //  StartMBB:
2613   //   ...
2614   //   %OrigVal     = L Disp(%Base)
2615   //   # fall through to LoopMMB
2616   MBB = StartMBB;
2617   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
2618     .addOperand(Base).addImm(Disp).addReg(0);
2619   MBB->addSuccessor(LoopMBB);
2620
2621   //  LoopMBB:
2622   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
2623   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
2624   //   CompareOpcode %RotatedOldVal, %Src2
2625   //   BRC KeepOldMask, UpdateMBB
2626   MBB = LoopMBB;
2627   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2628     .addReg(OrigVal).addMBB(StartMBB)
2629     .addReg(Dest).addMBB(UpdateMBB);
2630   if (IsSubWord)
2631     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
2632       .addReg(OldVal).addReg(BitShift).addImm(0);
2633   BuildMI(MBB, DL, TII->get(CompareOpcode))
2634     .addReg(RotatedOldVal).addReg(Src2);
2635   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2636     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
2637   MBB->addSuccessor(UpdateMBB);
2638   MBB->addSuccessor(UseAltMBB);
2639
2640   //  UseAltMBB:
2641   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
2642   //   # fall through to UpdateMMB
2643   MBB = UseAltMBB;
2644   if (IsSubWord)
2645     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
2646       .addReg(RotatedOldVal).addReg(Src2)
2647       .addImm(32).addImm(31 + BitSize).addImm(0);
2648   MBB->addSuccessor(UpdateMBB);
2649
2650   //  UpdateMBB:
2651   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
2652   //                        [ %RotatedAltVal, UseAltMBB ]
2653   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2654   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2655   //   JNE LoopMBB
2656   //   # fall through to DoneMMB
2657   MBB = UpdateMBB;
2658   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
2659     .addReg(RotatedOldVal).addMBB(LoopMBB)
2660     .addReg(RotatedAltVal).addMBB(UseAltMBB);
2661   if (IsSubWord)
2662     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2663       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2664   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2665     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2666   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2667     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2668   MBB->addSuccessor(LoopMBB);
2669   MBB->addSuccessor(DoneMBB);
2670
2671   MI->eraseFromParent();
2672   return DoneMBB;
2673 }
2674
2675 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
2676 // instruction MI.
2677 MachineBasicBlock *
2678 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
2679                                           MachineBasicBlock *MBB) const {
2680   const SystemZInstrInfo *TII = TM.getInstrInfo();
2681   MachineFunction &MF = *MBB->getParent();
2682   MachineRegisterInfo &MRI = MF.getRegInfo();
2683
2684   // Extract the operands.  Base can be a register or a frame index.
2685   unsigned Dest        = MI->getOperand(0).getReg();
2686   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2687   int64_t  Disp        = MI->getOperand(2).getImm();
2688   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
2689   unsigned OrigSwapVal = MI->getOperand(4).getReg();
2690   unsigned BitShift    = MI->getOperand(5).getReg();
2691   unsigned NegBitShift = MI->getOperand(6).getReg();
2692   int64_t  BitSize     = MI->getOperand(7).getImm();
2693   DebugLoc DL          = MI->getDebugLoc();
2694
2695   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
2696
2697   // Get the right opcodes for the displacement.
2698   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
2699   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
2700   assert(LOpcode && CSOpcode && "Displacement out of range");
2701
2702   // Create virtual registers for temporary results.
2703   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
2704   unsigned OldVal       = MRI.createVirtualRegister(RC);
2705   unsigned CmpVal       = MRI.createVirtualRegister(RC);
2706   unsigned SwapVal      = MRI.createVirtualRegister(RC);
2707   unsigned StoreVal     = MRI.createVirtualRegister(RC);
2708   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
2709   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
2710   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
2711
2712   // Insert 2 basic blocks for the loop.
2713   MachineBasicBlock *StartMBB = MBB;
2714   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
2715   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2716   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
2717
2718   //  StartMBB:
2719   //   ...
2720   //   %OrigOldVal     = L Disp(%Base)
2721   //   # fall through to LoopMMB
2722   MBB = StartMBB;
2723   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
2724     .addOperand(Base).addImm(Disp).addReg(0);
2725   MBB->addSuccessor(LoopMBB);
2726
2727   //  LoopMBB:
2728   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
2729   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
2730   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
2731   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
2732   //                      ^^ The low BitSize bits contain the field
2733   //                         of interest.
2734   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
2735   //                      ^^ Replace the upper 32-BitSize bits of the
2736   //                         comparison value with those that we loaded,
2737   //                         so that we can use a full word comparison.
2738   //   CR %Dest, %RetryCmpVal
2739   //   JNE DoneMBB
2740   //   # Fall through to SetMBB
2741   MBB = LoopMBB;
2742   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2743     .addReg(OrigOldVal).addMBB(StartMBB)
2744     .addReg(RetryOldVal).addMBB(SetMBB);
2745   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
2746     .addReg(OrigCmpVal).addMBB(StartMBB)
2747     .addReg(RetryCmpVal).addMBB(SetMBB);
2748   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
2749     .addReg(OrigSwapVal).addMBB(StartMBB)
2750     .addReg(RetrySwapVal).addMBB(SetMBB);
2751   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
2752     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
2753   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
2754     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2755   BuildMI(MBB, DL, TII->get(SystemZ::CR))
2756     .addReg(Dest).addReg(RetryCmpVal);
2757   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2758     .addImm(SystemZ::CCMASK_ICMP)
2759     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
2760   MBB->addSuccessor(DoneMBB);
2761   MBB->addSuccessor(SetMBB);
2762
2763   //  SetMBB:
2764   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
2765   //                      ^^ Replace the upper 32-BitSize bits of the new
2766   //                         value with those that we loaded.
2767   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
2768   //                      ^^ Rotate the new field to its proper position.
2769   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
2770   //   JNE LoopMBB
2771   //   # fall through to ExitMMB
2772   MBB = SetMBB;
2773   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
2774     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2775   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
2776     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
2777   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
2778     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
2779   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2780     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2781   MBB->addSuccessor(LoopMBB);
2782   MBB->addSuccessor(DoneMBB);
2783
2784   MI->eraseFromParent();
2785   return DoneMBB;
2786 }
2787
2788 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
2789 // if the high register of the GR128 value must be cleared or false if
2790 // it's "don't care".  SubReg is subreg_l32 when extending a GR32
2791 // and subreg_l64 when extending a GR64.
2792 MachineBasicBlock *
2793 SystemZTargetLowering::emitExt128(MachineInstr *MI,
2794                                   MachineBasicBlock *MBB,
2795                                   bool ClearEven, unsigned SubReg) const {
2796   const SystemZInstrInfo *TII = TM.getInstrInfo();
2797   MachineFunction &MF = *MBB->getParent();
2798   MachineRegisterInfo &MRI = MF.getRegInfo();
2799   DebugLoc DL = MI->getDebugLoc();
2800
2801   unsigned Dest  = MI->getOperand(0).getReg();
2802   unsigned Src   = MI->getOperand(1).getReg();
2803   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2804
2805   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
2806   if (ClearEven) {
2807     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2808     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
2809
2810     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
2811       .addImm(0);
2812     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
2813       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
2814     In128 = NewIn128;
2815   }
2816   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
2817     .addReg(In128).addReg(Src).addImm(SubReg);
2818
2819   MI->eraseFromParent();
2820   return MBB;
2821 }
2822
2823 MachineBasicBlock *
2824 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
2825                                          MachineBasicBlock *MBB,
2826                                          unsigned Opcode) const {
2827   const SystemZInstrInfo *TII = TM.getInstrInfo();
2828   MachineFunction &MF = *MBB->getParent();
2829   MachineRegisterInfo &MRI = MF.getRegInfo();
2830   DebugLoc DL = MI->getDebugLoc();
2831
2832   MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
2833   uint64_t       DestDisp = MI->getOperand(1).getImm();
2834   MachineOperand SrcBase  = earlyUseOperand(MI->getOperand(2));
2835   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
2836   uint64_t       Length   = MI->getOperand(4).getImm();
2837
2838   // When generating more than one CLC, all but the last will need to
2839   // branch to the end when a difference is found.
2840   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
2841                                splitBlockAfter(MI, MBB) : 0);
2842
2843   // Check for the loop form, in which operand 5 is the trip count.
2844   if (MI->getNumExplicitOperands() > 5) {
2845     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
2846
2847     uint64_t StartCountReg = MI->getOperand(5).getReg();
2848     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
2849     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
2850                               forceReg(MI, DestBase, TII));
2851
2852     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
2853     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
2854     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
2855                             MRI.createVirtualRegister(RC));
2856     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
2857     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
2858                             MRI.createVirtualRegister(RC));
2859
2860     RC = &SystemZ::GR64BitRegClass;
2861     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
2862     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
2863
2864     MachineBasicBlock *StartMBB = MBB;
2865     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
2866     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
2867     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
2868
2869     //  StartMBB:
2870     //   # fall through to LoopMMB
2871     MBB->addSuccessor(LoopMBB);
2872
2873     //  LoopMBB:
2874     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
2875     //                      [ %NextDestReg, NextMBB ]
2876     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
2877     //                     [ %NextSrcReg, NextMBB ]
2878     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
2879     //                       [ %NextCountReg, NextMBB ]
2880     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
2881     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
2882     //   ( JLH EndMBB )
2883     //
2884     // The prefetch is used only for MVC.  The JLH is used only for CLC.
2885     MBB = LoopMBB;
2886
2887     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
2888       .addReg(StartDestReg).addMBB(StartMBB)
2889       .addReg(NextDestReg).addMBB(NextMBB);
2890     if (!HaveSingleBase)
2891       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
2892         .addReg(StartSrcReg).addMBB(StartMBB)
2893         .addReg(NextSrcReg).addMBB(NextMBB);
2894     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
2895       .addReg(StartCountReg).addMBB(StartMBB)
2896       .addReg(NextCountReg).addMBB(NextMBB);
2897     if (Opcode == SystemZ::MVC)
2898       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
2899         .addImm(SystemZ::PFD_WRITE)
2900         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
2901     BuildMI(MBB, DL, TII->get(Opcode))
2902       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
2903       .addReg(ThisSrcReg).addImm(SrcDisp);
2904     if (EndMBB) {
2905       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2906         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
2907         .addMBB(EndMBB);
2908       MBB->addSuccessor(EndMBB);
2909       MBB->addSuccessor(NextMBB);
2910     }
2911
2912     // NextMBB:
2913     //   %NextDestReg = LA 256(%ThisDestReg)
2914     //   %NextSrcReg = LA 256(%ThisSrcReg)
2915     //   %NextCountReg = AGHI %ThisCountReg, -1
2916     //   CGHI %NextCountReg, 0
2917     //   JLH LoopMBB
2918     //   # fall through to DoneMMB
2919     //
2920     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
2921     MBB = NextMBB;
2922
2923     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
2924       .addReg(ThisDestReg).addImm(256).addReg(0);
2925     if (!HaveSingleBase)
2926       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
2927         .addReg(ThisSrcReg).addImm(256).addReg(0);
2928     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
2929       .addReg(ThisCountReg).addImm(-1);
2930     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
2931       .addReg(NextCountReg).addImm(0);
2932     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2933       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
2934       .addMBB(LoopMBB);
2935     MBB->addSuccessor(LoopMBB);
2936     MBB->addSuccessor(DoneMBB);
2937
2938     DestBase = MachineOperand::CreateReg(NextDestReg, false);
2939     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
2940     Length &= 255;
2941     MBB = DoneMBB;
2942   }
2943   // Handle any remaining bytes with straight-line code.
2944   while (Length > 0) {
2945     uint64_t ThisLength = std::min(Length, uint64_t(256));
2946     // The previous iteration might have created out-of-range displacements.
2947     // Apply them using LAY if so.
2948     if (!isUInt<12>(DestDisp)) {
2949       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2950       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
2951         .addOperand(DestBase).addImm(DestDisp).addReg(0);
2952       DestBase = MachineOperand::CreateReg(Reg, false);
2953       DestDisp = 0;
2954     }
2955     if (!isUInt<12>(SrcDisp)) {
2956       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2957       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
2958         .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
2959       SrcBase = MachineOperand::CreateReg(Reg, false);
2960       SrcDisp = 0;
2961     }
2962     BuildMI(*MBB, MI, DL, TII->get(Opcode))
2963       .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
2964       .addOperand(SrcBase).addImm(SrcDisp);
2965     DestDisp += ThisLength;
2966     SrcDisp += ThisLength;
2967     Length -= ThisLength;
2968     // If there's another CLC to go, branch to the end if a difference
2969     // was found.
2970     if (EndMBB && Length > 0) {
2971       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
2972       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2973         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
2974         .addMBB(EndMBB);
2975       MBB->addSuccessor(EndMBB);
2976       MBB->addSuccessor(NextMBB);
2977       MBB = NextMBB;
2978     }
2979   }
2980   if (EndMBB) {
2981     MBB->addSuccessor(EndMBB);
2982     MBB = EndMBB;
2983     MBB->addLiveIn(SystemZ::CC);
2984   }
2985
2986   MI->eraseFromParent();
2987   return MBB;
2988 }
2989
2990 // Decompose string pseudo-instruction MI into a loop that continually performs
2991 // Opcode until CC != 3.
2992 MachineBasicBlock *
2993 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
2994                                          MachineBasicBlock *MBB,
2995                                          unsigned Opcode) const {
2996   const SystemZInstrInfo *TII = TM.getInstrInfo();
2997   MachineFunction &MF = *MBB->getParent();
2998   MachineRegisterInfo &MRI = MF.getRegInfo();
2999   DebugLoc DL = MI->getDebugLoc();
3000
3001   uint64_t End1Reg   = MI->getOperand(0).getReg();
3002   uint64_t Start1Reg = MI->getOperand(1).getReg();
3003   uint64_t Start2Reg = MI->getOperand(2).getReg();
3004   uint64_t CharReg   = MI->getOperand(3).getReg();
3005
3006   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
3007   uint64_t This1Reg = MRI.createVirtualRegister(RC);
3008   uint64_t This2Reg = MRI.createVirtualRegister(RC);
3009   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
3010
3011   MachineBasicBlock *StartMBB = MBB;
3012   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
3013   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
3014
3015   //  StartMBB:
3016   //   # fall through to LoopMMB
3017   MBB->addSuccessor(LoopMBB);
3018
3019   //  LoopMBB:
3020   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
3021   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
3022   //   R0L = %CharReg
3023   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
3024   //   JO LoopMBB
3025   //   # fall through to DoneMMB
3026   //
3027   // The load of R0L can be hoisted by post-RA LICM.
3028   MBB = LoopMBB;
3029
3030   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
3031     .addReg(Start1Reg).addMBB(StartMBB)
3032     .addReg(End1Reg).addMBB(LoopMBB);
3033   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
3034     .addReg(Start2Reg).addMBB(StartMBB)
3035     .addReg(End2Reg).addMBB(LoopMBB);
3036   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
3037   BuildMI(MBB, DL, TII->get(Opcode))
3038     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
3039     .addReg(This1Reg).addReg(This2Reg);
3040   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3041     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
3042   MBB->addSuccessor(LoopMBB);
3043   MBB->addSuccessor(DoneMBB);
3044
3045   DoneMBB->addLiveIn(SystemZ::CC);
3046
3047   MI->eraseFromParent();
3048   return DoneMBB;
3049 }
3050
3051 MachineBasicBlock *SystemZTargetLowering::
3052 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
3053   switch (MI->getOpcode()) {
3054   case SystemZ::Select32Mux:
3055   case SystemZ::Select32:
3056   case SystemZ::SelectF32:
3057   case SystemZ::Select64:
3058   case SystemZ::SelectF64:
3059   case SystemZ::SelectF128:
3060     return emitSelect(MI, MBB);
3061
3062   case SystemZ::CondStore8Mux:
3063     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
3064   case SystemZ::CondStore8MuxInv:
3065     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
3066   case SystemZ::CondStore16Mux:
3067     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
3068   case SystemZ::CondStore16MuxInv:
3069     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
3070   case SystemZ::CondStore8:
3071     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
3072   case SystemZ::CondStore8Inv:
3073     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
3074   case SystemZ::CondStore16:
3075     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
3076   case SystemZ::CondStore16Inv:
3077     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
3078   case SystemZ::CondStore32:
3079     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
3080   case SystemZ::CondStore32Inv:
3081     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
3082   case SystemZ::CondStore64:
3083     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
3084   case SystemZ::CondStore64Inv:
3085     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
3086   case SystemZ::CondStoreF32:
3087     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
3088   case SystemZ::CondStoreF32Inv:
3089     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
3090   case SystemZ::CondStoreF64:
3091     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
3092   case SystemZ::CondStoreF64Inv:
3093     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
3094
3095   case SystemZ::AEXT128_64:
3096     return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
3097   case SystemZ::ZEXT128_32:
3098     return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
3099   case SystemZ::ZEXT128_64:
3100     return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
3101
3102   case SystemZ::ATOMIC_SWAPW:
3103     return emitAtomicLoadBinary(MI, MBB, 0, 0);
3104   case SystemZ::ATOMIC_SWAP_32:
3105     return emitAtomicLoadBinary(MI, MBB, 0, 32);
3106   case SystemZ::ATOMIC_SWAP_64:
3107     return emitAtomicLoadBinary(MI, MBB, 0, 64);
3108
3109   case SystemZ::ATOMIC_LOADW_AR:
3110     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
3111   case SystemZ::ATOMIC_LOADW_AFI:
3112     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
3113   case SystemZ::ATOMIC_LOAD_AR:
3114     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
3115   case SystemZ::ATOMIC_LOAD_AHI:
3116     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
3117   case SystemZ::ATOMIC_LOAD_AFI:
3118     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
3119   case SystemZ::ATOMIC_LOAD_AGR:
3120     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
3121   case SystemZ::ATOMIC_LOAD_AGHI:
3122     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
3123   case SystemZ::ATOMIC_LOAD_AGFI:
3124     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
3125
3126   case SystemZ::ATOMIC_LOADW_SR:
3127     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
3128   case SystemZ::ATOMIC_LOAD_SR:
3129     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
3130   case SystemZ::ATOMIC_LOAD_SGR:
3131     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
3132
3133   case SystemZ::ATOMIC_LOADW_NR:
3134     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
3135   case SystemZ::ATOMIC_LOADW_NILH:
3136     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
3137   case SystemZ::ATOMIC_LOAD_NR:
3138     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
3139   case SystemZ::ATOMIC_LOAD_NILL:
3140     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
3141   case SystemZ::ATOMIC_LOAD_NILH:
3142     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
3143   case SystemZ::ATOMIC_LOAD_NILF:
3144     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
3145   case SystemZ::ATOMIC_LOAD_NGR:
3146     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
3147   case SystemZ::ATOMIC_LOAD_NILL64:
3148     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
3149   case SystemZ::ATOMIC_LOAD_NILH64:
3150     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
3151   case SystemZ::ATOMIC_LOAD_NIHL64:
3152     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
3153   case SystemZ::ATOMIC_LOAD_NIHH64:
3154     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
3155   case SystemZ::ATOMIC_LOAD_NILF64:
3156     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
3157   case SystemZ::ATOMIC_LOAD_NIHF64:
3158     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
3159
3160   case SystemZ::ATOMIC_LOADW_OR:
3161     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
3162   case SystemZ::ATOMIC_LOADW_OILH:
3163     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
3164   case SystemZ::ATOMIC_LOAD_OR:
3165     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
3166   case SystemZ::ATOMIC_LOAD_OILL:
3167     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
3168   case SystemZ::ATOMIC_LOAD_OILH:
3169     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
3170   case SystemZ::ATOMIC_LOAD_OILF:
3171     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
3172   case SystemZ::ATOMIC_LOAD_OGR:
3173     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
3174   case SystemZ::ATOMIC_LOAD_OILL64:
3175     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
3176   case SystemZ::ATOMIC_LOAD_OILH64:
3177     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
3178   case SystemZ::ATOMIC_LOAD_OIHL64:
3179     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
3180   case SystemZ::ATOMIC_LOAD_OIHH64:
3181     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
3182   case SystemZ::ATOMIC_LOAD_OILF64:
3183     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
3184   case SystemZ::ATOMIC_LOAD_OIHF64:
3185     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
3186
3187   case SystemZ::ATOMIC_LOADW_XR:
3188     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
3189   case SystemZ::ATOMIC_LOADW_XILF:
3190     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
3191   case SystemZ::ATOMIC_LOAD_XR:
3192     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
3193   case SystemZ::ATOMIC_LOAD_XILF:
3194     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
3195   case SystemZ::ATOMIC_LOAD_XGR:
3196     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
3197   case SystemZ::ATOMIC_LOAD_XILF64:
3198     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
3199   case SystemZ::ATOMIC_LOAD_XIHF64:
3200     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
3201
3202   case SystemZ::ATOMIC_LOADW_NRi:
3203     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
3204   case SystemZ::ATOMIC_LOADW_NILHi:
3205     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
3206   case SystemZ::ATOMIC_LOAD_NRi:
3207     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
3208   case SystemZ::ATOMIC_LOAD_NILLi:
3209     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
3210   case SystemZ::ATOMIC_LOAD_NILHi:
3211     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
3212   case SystemZ::ATOMIC_LOAD_NILFi:
3213     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
3214   case SystemZ::ATOMIC_LOAD_NGRi:
3215     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
3216   case SystemZ::ATOMIC_LOAD_NILL64i:
3217     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
3218   case SystemZ::ATOMIC_LOAD_NILH64i:
3219     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
3220   case SystemZ::ATOMIC_LOAD_NIHL64i:
3221     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
3222   case SystemZ::ATOMIC_LOAD_NIHH64i:
3223     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
3224   case SystemZ::ATOMIC_LOAD_NILF64i:
3225     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
3226   case SystemZ::ATOMIC_LOAD_NIHF64i:
3227     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
3228
3229   case SystemZ::ATOMIC_LOADW_MIN:
3230     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3231                                 SystemZ::CCMASK_CMP_LE, 0);
3232   case SystemZ::ATOMIC_LOAD_MIN_32:
3233     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3234                                 SystemZ::CCMASK_CMP_LE, 32);
3235   case SystemZ::ATOMIC_LOAD_MIN_64:
3236     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
3237                                 SystemZ::CCMASK_CMP_LE, 64);
3238
3239   case SystemZ::ATOMIC_LOADW_MAX:
3240     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3241                                 SystemZ::CCMASK_CMP_GE, 0);
3242   case SystemZ::ATOMIC_LOAD_MAX_32:
3243     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3244                                 SystemZ::CCMASK_CMP_GE, 32);
3245   case SystemZ::ATOMIC_LOAD_MAX_64:
3246     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
3247                                 SystemZ::CCMASK_CMP_GE, 64);
3248
3249   case SystemZ::ATOMIC_LOADW_UMIN:
3250     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3251                                 SystemZ::CCMASK_CMP_LE, 0);
3252   case SystemZ::ATOMIC_LOAD_UMIN_32:
3253     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3254                                 SystemZ::CCMASK_CMP_LE, 32);
3255   case SystemZ::ATOMIC_LOAD_UMIN_64:
3256     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
3257                                 SystemZ::CCMASK_CMP_LE, 64);
3258
3259   case SystemZ::ATOMIC_LOADW_UMAX:
3260     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3261                                 SystemZ::CCMASK_CMP_GE, 0);
3262   case SystemZ::ATOMIC_LOAD_UMAX_32:
3263     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3264                                 SystemZ::CCMASK_CMP_GE, 32);
3265   case SystemZ::ATOMIC_LOAD_UMAX_64:
3266     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
3267                                 SystemZ::CCMASK_CMP_GE, 64);
3268
3269   case SystemZ::ATOMIC_CMP_SWAPW:
3270     return emitAtomicCmpSwapW(MI, MBB);
3271   case SystemZ::MVCSequence:
3272   case SystemZ::MVCLoop:
3273     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
3274   case SystemZ::NCSequence:
3275   case SystemZ::NCLoop:
3276     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
3277   case SystemZ::OCSequence:
3278   case SystemZ::OCLoop:
3279     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
3280   case SystemZ::XCSequence:
3281   case SystemZ::XCLoop:
3282     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
3283   case SystemZ::CLCSequence:
3284   case SystemZ::CLCLoop:
3285     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
3286   case SystemZ::CLSTLoop:
3287     return emitStringWrapper(MI, MBB, SystemZ::CLST);
3288   case SystemZ::MVSTLoop:
3289     return emitStringWrapper(MI, MBB, SystemZ::MVST);
3290   case SystemZ::SRSTLoop:
3291     return emitStringWrapper(MI, MBB, SystemZ::SRST);
3292   default:
3293     llvm_unreachable("Unexpected instr type to insert");
3294   }
3295 }