[SystemZ] Make more use of LTGFR
[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       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
138       // stores, putting a serialization instruction after the stores.
139       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
140       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
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 SDValue SystemZTargetLowering::
974 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
975   return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
976 }
977
978 // CC is a comparison that will be implemented using an integer or
979 // floating-point comparison.  Return the condition code mask for
980 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
981 // unsigned comparisons and clear for signed ones.  In the floating-point
982 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
983 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
984 #define CONV(X) \
985   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
986   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
987   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
988
989   switch (CC) {
990   default:
991     llvm_unreachable("Invalid integer condition!");
992
993   CONV(EQ);
994   CONV(NE);
995   CONV(GT);
996   CONV(GE);
997   CONV(LT);
998   CONV(LE);
999
1000   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
1001   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1002   }
1003 #undef CONV
1004 }
1005
1006 // Return a sequence for getting a 1 from an IPM result when CC has a
1007 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1008 // The handling of CC values outside CCValid doesn't matter.
1009 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1010   // Deal with cases where the result can be taken directly from a bit
1011   // of the IPM result.
1012   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1013     return IPMConversion(0, 0, SystemZ::IPM_CC);
1014   if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1015     return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1016
1017   // Deal with cases where we can add a value to force the sign bit
1018   // to contain the right value.  Putting the bit in 31 means we can
1019   // use SRL rather than RISBG(L), and also makes it easier to get a
1020   // 0/-1 value, so it has priority over the other tests below.
1021   //
1022   // These sequences rely on the fact that the upper two bits of the
1023   // IPM result are zero.
1024   uint64_t TopBit = uint64_t(1) << 31;
1025   if (CCMask == (CCValid & SystemZ::CCMASK_0))
1026     return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1027   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1028     return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1029   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1030                             | SystemZ::CCMASK_1
1031                             | SystemZ::CCMASK_2)))
1032     return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1033   if (CCMask == (CCValid & SystemZ::CCMASK_3))
1034     return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1035   if (CCMask == (CCValid & (SystemZ::CCMASK_1
1036                             | SystemZ::CCMASK_2
1037                             | SystemZ::CCMASK_3)))
1038     return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1039
1040   // Next try inverting the value and testing a bit.  0/1 could be
1041   // handled this way too, but we dealt with that case above.
1042   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1043     return IPMConversion(-1, 0, SystemZ::IPM_CC);
1044
1045   // Handle cases where adding a value forces a non-sign bit to contain
1046   // the right value.
1047   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1048     return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1049   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1050     return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1051
1052   // The remaing cases are 1, 2, 0/1/3 and 0/2/3.  All these are
1053   // can be done by inverting the low CC bit and applying one of the
1054   // sign-based extractions above.
1055   if (CCMask == (CCValid & SystemZ::CCMASK_1))
1056     return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1057   if (CCMask == (CCValid & SystemZ::CCMASK_2))
1058     return IPMConversion(1 << SystemZ::IPM_CC,
1059                          TopBit - (3 << SystemZ::IPM_CC), 31);
1060   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1061                             | SystemZ::CCMASK_1
1062                             | SystemZ::CCMASK_3)))
1063     return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1064   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1065                             | SystemZ::CCMASK_2
1066                             | SystemZ::CCMASK_3)))
1067     return IPMConversion(1 << SystemZ::IPM_CC,
1068                          TopBit - (1 << SystemZ::IPM_CC), 31);
1069
1070   llvm_unreachable("Unexpected CC combination");
1071 }
1072
1073 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
1074 // can be converted to a comparison against zero, adjust the operands
1075 // as necessary.
1076 static void adjustZeroCmp(SelectionDAG &DAG, bool &IsUnsigned,
1077                           SDValue &CmpOp0, SDValue &CmpOp1,
1078                           unsigned &CCMask) {
1079   if (IsUnsigned)
1080     return;
1081
1082   ConstantSDNode *ConstOp1 = dyn_cast<ConstantSDNode>(CmpOp1.getNode());
1083   if (!ConstOp1)
1084     return;
1085
1086   int64_t Value = ConstOp1->getSExtValue();
1087   if ((Value == -1 && CCMask == SystemZ::CCMASK_CMP_GT) ||
1088       (Value == -1 && CCMask == SystemZ::CCMASK_CMP_LE) ||
1089       (Value == 1 && CCMask == SystemZ::CCMASK_CMP_LT) ||
1090       (Value == 1 && CCMask == SystemZ::CCMASK_CMP_GE)) {
1091     CCMask ^= SystemZ::CCMASK_CMP_EQ;
1092     CmpOp1 = DAG.getConstant(0, CmpOp1.getValueType());
1093   }
1094 }
1095
1096 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
1097 // is suitable for CLI(Y), CHHSI or CLHHSI, adjust the operands as necessary.
1098 static void adjustSubwordCmp(SelectionDAG &DAG, bool &IsUnsigned,
1099                              SDValue &CmpOp0, SDValue &CmpOp1,
1100                              unsigned &CCMask) {
1101   // For us to make any changes, it must a comparison between a single-use
1102   // load and a constant.
1103   if (!CmpOp0.hasOneUse() ||
1104       CmpOp0.getOpcode() != ISD::LOAD ||
1105       CmpOp1.getOpcode() != ISD::Constant)
1106     return;
1107
1108   // We must have an 8- or 16-bit load.
1109   LoadSDNode *Load = cast<LoadSDNode>(CmpOp0);
1110   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1111   if (NumBits != 8 && NumBits != 16)
1112     return;
1113
1114   // The load must be an extending one and the constant must be within the
1115   // range of the unextended value.
1116   ConstantSDNode *Constant = cast<ConstantSDNode>(CmpOp1);
1117   uint64_t Value = Constant->getZExtValue();
1118   uint64_t Mask = (1 << NumBits) - 1;
1119   if (Load->getExtensionType() == ISD::SEXTLOAD) {
1120     int64_t SignedValue = Constant->getSExtValue();
1121     if (uint64_t(SignedValue) + (1ULL << (NumBits - 1)) > Mask)
1122       return;
1123     // Unsigned comparison between two sign-extended values is equivalent
1124     // to unsigned comparison between two zero-extended values.
1125     if (IsUnsigned)
1126       Value &= Mask;
1127     else if (CCMask == SystemZ::CCMASK_CMP_EQ ||
1128              CCMask == SystemZ::CCMASK_CMP_NE)
1129       // Any choice of IsUnsigned is OK for equality comparisons.
1130       // We could use either CHHSI or CLHHSI for 16-bit comparisons,
1131       // but since we use CLHHSI for zero extensions, it seems better
1132       // to be consistent and do the same here.
1133       Value &= Mask, IsUnsigned = true;
1134     else if (NumBits == 8) {
1135       // Try to treat the comparison as unsigned, so that we can use CLI.
1136       // Adjust CCMask and Value as necessary.
1137       if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_LT)
1138         // Test whether the high bit of the byte is set.
1139         Value = 127, CCMask = SystemZ::CCMASK_CMP_GT, IsUnsigned = true;
1140       else if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_GE)
1141         // Test whether the high bit of the byte is clear.
1142         Value = 128, CCMask = SystemZ::CCMASK_CMP_LT, IsUnsigned = true;
1143       else
1144         // No instruction exists for this combination.
1145         return;
1146     }
1147   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1148     if (Value > Mask)
1149       return;
1150     // Signed comparison between two zero-extended values is equivalent
1151     // to unsigned comparison.
1152     IsUnsigned = true;
1153   } else
1154     return;
1155
1156   // Make sure that the first operand is an i32 of the right extension type.
1157   ISD::LoadExtType ExtType = IsUnsigned ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
1158   if (CmpOp0.getValueType() != MVT::i32 ||
1159       Load->getExtensionType() != ExtType)
1160     CmpOp0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1161                             Load->getChain(), Load->getBasePtr(),
1162                             Load->getPointerInfo(), Load->getMemoryVT(),
1163                             Load->isVolatile(), Load->isNonTemporal(),
1164                             Load->getAlignment());
1165
1166   // Make sure that the second operand is an i32 with the right value.
1167   if (CmpOp1.getValueType() != MVT::i32 ||
1168       Value != Constant->getZExtValue())
1169     CmpOp1 = DAG.getConstant(Value, MVT::i32);
1170 }
1171
1172 // Return true if Op is either an unextended load, or a load suitable
1173 // for integer register-memory comparisons of type ICmpType.
1174 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1175   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op.getNode());
1176   if (Load) {
1177     // There are no instructions to compare a register with a memory byte.
1178     if (Load->getMemoryVT() == MVT::i8)
1179       return false;
1180     // Otherwise decide on extension type.
1181     switch (Load->getExtensionType()) {
1182     case ISD::NON_EXTLOAD:
1183       return true;
1184     case ISD::SEXTLOAD:
1185       return ICmpType != SystemZICMP::UnsignedOnly;
1186     case ISD::ZEXTLOAD:
1187       return ICmpType != SystemZICMP::SignedOnly;
1188     default:
1189       break;
1190     }
1191   }
1192   return false;
1193 }
1194
1195 // Return true if it is better to swap comparison operands Op0 and Op1.
1196 // ICmpType is the type of an integer comparison.
1197 static bool shouldSwapCmpOperands(SDValue Op0, SDValue Op1,
1198                                   unsigned ICmpType) {
1199   // Leave f128 comparisons alone, since they have no memory forms.
1200   if (Op0.getValueType() == MVT::f128)
1201     return false;
1202
1203   // Always keep a floating-point constant second, since comparisons with
1204   // zero can use LOAD TEST and comparisons with other constants make a
1205   // natural memory operand.
1206   if (isa<ConstantFPSDNode>(Op1))
1207     return false;
1208
1209   // Never swap comparisons with zero since there are many ways to optimize
1210   // those later.
1211   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
1212   if (COp1 && COp1->getZExtValue() == 0)
1213     return false;
1214
1215   // Also keep natural memory operands second if the loaded value is
1216   // only used here.  Several comparisons have memory forms.
1217   if (isNaturalMemoryOperand(Op1, ICmpType) && Op1.hasOneUse())
1218     return false;
1219
1220   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1221   // In that case we generally prefer the memory to be second.
1222   if (isNaturalMemoryOperand(Op0, ICmpType) && Op0.hasOneUse()) {
1223     // The only exceptions are when the second operand is a constant and
1224     // we can use things like CHHSI.
1225     if (!COp1)
1226       return true;
1227     // The unsigned memory-immediate instructions can handle 16-bit
1228     // unsigned integers.
1229     if (ICmpType != SystemZICMP::SignedOnly &&
1230         isUInt<16>(COp1->getZExtValue()))
1231       return false;
1232     // The signed memory-immediate instructions can handle 16-bit
1233     // signed integers.
1234     if (ICmpType != SystemZICMP::UnsignedOnly &&
1235         isInt<16>(COp1->getSExtValue()))
1236       return false;
1237     return true;
1238   }
1239
1240   // Try to promote the use of CGFR and CLGFR.
1241   unsigned Opcode0 = Op0.getOpcode();
1242   if (ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1243     return true;
1244   if (ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1245     return true;
1246   if (ICmpType != SystemZICMP::SignedOnly &&
1247       Opcode0 == ISD::AND &&
1248       Op0.getOperand(1).getOpcode() == ISD::Constant &&
1249       cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1250     return true;
1251
1252   return false;
1253 }
1254
1255 // Return a version of comparison CC mask CCMask in which the LT and GT
1256 // actions are swapped.
1257 static unsigned reverseCCMask(unsigned CCMask) {
1258   return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1259           (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1260           (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1261           (CCMask & SystemZ::CCMASK_CMP_UO));
1262 }
1263
1264 // CmpOp0 and CmpOp1 are being compared using CC mask CCMask.  Check whether
1265 // CmpOp0 is a floating-point result that is also negated and if CmpOp1
1266 // is zero.  In this case we can use the negation to set CC, so avoiding
1267 // separate LOAD AND TEST and LOAD (NEGATIVE/COMPLEMENT) instructions.
1268 static void adjustForFNeg(SDValue &CmpOp0, SDValue &CmpOp1, unsigned &CCMask) {
1269   ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(CmpOp1);
1270   if (C1 && C1->isZero()) {
1271     for (SDNode::use_iterator I = CmpOp0->use_begin(), E = CmpOp0->use_end();
1272          I != E; ++I) {
1273       SDNode *N = *I;
1274       if (N->getOpcode() == ISD::FNEG) {
1275         CmpOp0 = SDValue(N, 0);
1276         CCMask = reverseCCMask(CCMask);
1277         return;
1278       }
1279     }
1280   }
1281 }
1282
1283 // Check whether CmpOp0 is (shl X, 32), CmpOp1 is 0, and whether X is
1284 // also sign-extended.  In that case it is better to test the result
1285 // of the sign extension using LTGFR.
1286 //
1287 // This case is important because InstCombine transforms a comparison
1288 // with (sext (trunc X)) into a comparison with (shl X, 32).
1289 static void adjustForLTGFR(SDValue &CmpOp0, SDValue &CmpOp1,
1290                            unsigned &IcmpType) {
1291   // Check for a comparison between (shl X, 32) and 0.
1292   if (CmpOp0.getOpcode() == ISD::SHL &&
1293       CmpOp0.getValueType() == MVT::i64 &&
1294       CmpOp1.getOpcode() == ISD::Constant &&
1295       cast<ConstantSDNode>(CmpOp1)->getZExtValue() == 0) {
1296     ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(CmpOp0.getOperand(1));
1297     if (C1 && C1->getZExtValue() == 32) {
1298       SDValue ShlOp0 = CmpOp0.getOperand(0);
1299       // See whether X has any SIGN_EXTEND_INREG uses.
1300       for (SDNode::use_iterator I = ShlOp0->use_begin(), E = ShlOp0->use_end();
1301            I != E; ++I) {
1302         SDNode *N = *I;
1303         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1304             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1305           CmpOp0 = SDValue(N, 0);
1306           return;
1307         }
1308       }
1309     }
1310   }
1311 }
1312
1313 // Return true if shift operation N has an in-range constant shift value.
1314 // Store it in ShiftVal if so.
1315 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1316   ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1317   if (!Shift)
1318     return false;
1319
1320   uint64_t Amount = Shift->getZExtValue();
1321   if (Amount >= N.getValueType().getSizeInBits())
1322     return false;
1323
1324   ShiftVal = Amount;
1325   return true;
1326 }
1327
1328 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1329 // instruction and whether the CC value is descriptive enough to handle
1330 // a comparison of type Opcode between the AND result and CmpVal.
1331 // CCMask says which comparison result is being tested and BitSize is
1332 // the number of bits in the operands.  If TEST UNDER MASK can be used,
1333 // return the corresponding CC mask, otherwise return 0.
1334 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1335                                      uint64_t Mask, uint64_t CmpVal,
1336                                      unsigned ICmpType) {
1337   assert(Mask != 0 && "ANDs with zero should have been removed by now");
1338
1339   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1340   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1341       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1342     return 0;
1343
1344   // Work out the masks for the lowest and highest bits.
1345   unsigned HighShift = 63 - countLeadingZeros(Mask);
1346   uint64_t High = uint64_t(1) << HighShift;
1347   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1348
1349   // Signed ordered comparisons are effectively unsigned if the sign
1350   // bit is dropped.
1351   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1352
1353   // Check for equality comparisons with 0, or the equivalent.
1354   if (CmpVal == 0) {
1355     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1356       return SystemZ::CCMASK_TM_ALL_0;
1357     if (CCMask == SystemZ::CCMASK_CMP_NE)
1358       return SystemZ::CCMASK_TM_SOME_1;
1359   }
1360   if (EffectivelyUnsigned && CmpVal <= Low) {
1361     if (CCMask == SystemZ::CCMASK_CMP_LT)
1362       return SystemZ::CCMASK_TM_ALL_0;
1363     if (CCMask == SystemZ::CCMASK_CMP_GE)
1364       return SystemZ::CCMASK_TM_SOME_1;
1365   }
1366   if (EffectivelyUnsigned && CmpVal < Low) {
1367     if (CCMask == SystemZ::CCMASK_CMP_LE)
1368       return SystemZ::CCMASK_TM_ALL_0;
1369     if (CCMask == SystemZ::CCMASK_CMP_GT)
1370       return SystemZ::CCMASK_TM_SOME_1;
1371   }
1372
1373   // Check for equality comparisons with the mask, or the equivalent.
1374   if (CmpVal == Mask) {
1375     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1376       return SystemZ::CCMASK_TM_ALL_1;
1377     if (CCMask == SystemZ::CCMASK_CMP_NE)
1378       return SystemZ::CCMASK_TM_SOME_0;
1379   }
1380   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1381     if (CCMask == SystemZ::CCMASK_CMP_GT)
1382       return SystemZ::CCMASK_TM_ALL_1;
1383     if (CCMask == SystemZ::CCMASK_CMP_LE)
1384       return SystemZ::CCMASK_TM_SOME_0;
1385   }
1386   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1387     if (CCMask == SystemZ::CCMASK_CMP_GE)
1388       return SystemZ::CCMASK_TM_ALL_1;
1389     if (CCMask == SystemZ::CCMASK_CMP_LT)
1390       return SystemZ::CCMASK_TM_SOME_0;
1391   }
1392
1393   // Check for ordered comparisons with the top bit.
1394   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1395     if (CCMask == SystemZ::CCMASK_CMP_LE)
1396       return SystemZ::CCMASK_TM_MSB_0;
1397     if (CCMask == SystemZ::CCMASK_CMP_GT)
1398       return SystemZ::CCMASK_TM_MSB_1;
1399   }
1400   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1401     if (CCMask == SystemZ::CCMASK_CMP_LT)
1402       return SystemZ::CCMASK_TM_MSB_0;
1403     if (CCMask == SystemZ::CCMASK_CMP_GE)
1404       return SystemZ::CCMASK_TM_MSB_1;
1405   }
1406
1407   // If there are just two bits, we can do equality checks for Low and High
1408   // as well.
1409   if (Mask == Low + High) {
1410     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1411       return SystemZ::CCMASK_TM_MIXED_MSB_0;
1412     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1413       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1414     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1415       return SystemZ::CCMASK_TM_MIXED_MSB_1;
1416     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1417       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1418   }
1419
1420   // Looks like we've exhausted our options.
1421   return 0;
1422 }
1423
1424 // See whether the comparison (Opcode CmpOp0, CmpOp1, ICmpType) can be
1425 // implemented as a TEST UNDER MASK instruction when the condition being
1426 // tested is as described by CCValid and CCMask.  Update the arguments
1427 // with the TM version if so.
1428 static void adjustForTestUnderMask(SelectionDAG &DAG, unsigned &Opcode,
1429                                    SDValue &CmpOp0, SDValue &CmpOp1,
1430                                    unsigned &CCValid, unsigned &CCMask,
1431                                    unsigned &ICmpType) {
1432   // Check that we have a comparison with a constant.
1433   ConstantSDNode *ConstCmpOp1 = dyn_cast<ConstantSDNode>(CmpOp1);
1434   if (!ConstCmpOp1)
1435     return;
1436   uint64_t CmpVal = ConstCmpOp1->getZExtValue();
1437
1438   // Check whether the nonconstant input is an AND with a constant mask.
1439   if (CmpOp0.getOpcode() != ISD::AND)
1440     return;
1441   SDValue AndOp0 = CmpOp0.getOperand(0);
1442   SDValue AndOp1 = CmpOp0.getOperand(1);
1443   ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(AndOp1.getNode());
1444   if (!Mask)
1445     return;
1446   uint64_t MaskVal = Mask->getZExtValue();
1447
1448   // Check whether the combination of mask, comparison value and comparison
1449   // type are suitable.
1450   unsigned BitSize = CmpOp0.getValueType().getSizeInBits();
1451   unsigned NewCCMask, ShiftVal;
1452   if (ICmpType != SystemZICMP::SignedOnly &&
1453       AndOp0.getOpcode() == ISD::SHL &&
1454       isSimpleShift(AndOp0, ShiftVal) &&
1455       (NewCCMask = getTestUnderMaskCond(BitSize, CCMask, MaskVal >> ShiftVal,
1456                                         CmpVal >> ShiftVal,
1457                                         SystemZICMP::Any))) {
1458     AndOp0 = AndOp0.getOperand(0);
1459     AndOp1 = DAG.getConstant(MaskVal >> ShiftVal, AndOp0.getValueType());
1460   } else if (ICmpType != SystemZICMP::SignedOnly &&
1461              AndOp0.getOpcode() == ISD::SRL &&
1462              isSimpleShift(AndOp0, ShiftVal) &&
1463              (NewCCMask = getTestUnderMaskCond(BitSize, CCMask,
1464                                                MaskVal << ShiftVal,
1465                                                CmpVal << ShiftVal,
1466                                                SystemZICMP::UnsignedOnly))) {
1467     AndOp0 = AndOp0.getOperand(0);
1468     AndOp1 = DAG.getConstant(MaskVal << ShiftVal, AndOp0.getValueType());
1469   } else {
1470     NewCCMask = getTestUnderMaskCond(BitSize, CCMask, MaskVal, CmpVal,
1471                                      ICmpType);
1472     if (!NewCCMask)
1473       return;
1474   }
1475
1476   // Go ahead and make the change.
1477   Opcode = SystemZISD::TM;
1478   CmpOp0 = AndOp0;
1479   CmpOp1 = AndOp1;
1480   ICmpType = (bool(NewCCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
1481               bool(NewCCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
1482   CCValid = SystemZ::CCMASK_TM;
1483   CCMask = NewCCMask;
1484 }
1485
1486 // Return a target node that compares CmpOp0 with CmpOp1 and stores a
1487 // 2-bit result in CC.  Set CCValid to the CCMASK_* of all possible
1488 // 2-bit results and CCMask to the subset of those results that are
1489 // associated with Cond.
1490 static SDValue emitCmp(const SystemZTargetMachine &TM, SelectionDAG &DAG,
1491                        SDLoc DL, SDValue CmpOp0, SDValue CmpOp1,
1492                        ISD::CondCode Cond, unsigned &CCValid,
1493                        unsigned &CCMask) {
1494   bool IsUnsigned = false;
1495   CCMask = CCMaskForCondCode(Cond);
1496   unsigned Opcode, ICmpType = 0;
1497   if (CmpOp0.getValueType().isFloatingPoint()) {
1498     CCValid = SystemZ::CCMASK_FCMP;
1499     Opcode = SystemZISD::FCMP;
1500   } else {
1501     IsUnsigned = CCMask & SystemZ::CCMASK_CMP_UO;
1502     CCValid = SystemZ::CCMASK_ICMP;
1503     CCMask &= CCValid;
1504     adjustZeroCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
1505     adjustSubwordCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
1506     Opcode = SystemZISD::ICMP;
1507     // Choose the type of comparison.  Equality and inequality tests can
1508     // use either signed or unsigned comparisons.  The choice also doesn't
1509     // matter if both sign bits are known to be clear.  In those cases we
1510     // want to give the main isel code the freedom to choose whichever
1511     // form fits best.
1512     if (CCMask == SystemZ::CCMASK_CMP_EQ ||
1513         CCMask == SystemZ::CCMASK_CMP_NE ||
1514         (DAG.SignBitIsZero(CmpOp0) && DAG.SignBitIsZero(CmpOp1)))
1515       ICmpType = SystemZICMP::Any;
1516     else if (IsUnsigned)
1517       ICmpType = SystemZICMP::UnsignedOnly;
1518     else
1519       ICmpType = SystemZICMP::SignedOnly;
1520   }
1521
1522   if (shouldSwapCmpOperands(CmpOp0, CmpOp1, ICmpType)) {
1523     std::swap(CmpOp0, CmpOp1);
1524     CCMask = reverseCCMask(CCMask);
1525   }
1526
1527   adjustForTestUnderMask(DAG, Opcode, CmpOp0, CmpOp1, CCValid, CCMask,
1528                          ICmpType);
1529   adjustForFNeg(CmpOp0, CmpOp1, CCMask);
1530   adjustForLTGFR(CmpOp0, CmpOp1, ICmpType);
1531   if (Opcode == SystemZISD::ICMP || Opcode == SystemZISD::TM)
1532     return DAG.getNode(Opcode, DL, MVT::Glue, CmpOp0, CmpOp1,
1533                        DAG.getConstant(ICmpType, MVT::i32));
1534   return DAG.getNode(Opcode, DL, MVT::Glue, CmpOp0, CmpOp1);
1535 }
1536
1537 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
1538 // 64 bits.  Extend is the extension type to use.  Store the high part
1539 // in Hi and the low part in Lo.
1540 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
1541                             unsigned Extend, SDValue Op0, SDValue Op1,
1542                             SDValue &Hi, SDValue &Lo) {
1543   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
1544   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
1545   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
1546   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, DAG.getConstant(32, MVT::i64));
1547   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
1548   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
1549 }
1550
1551 // Lower a binary operation that produces two VT results, one in each
1552 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
1553 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
1554 // on the extended Op0 and (unextended) Op1.  Store the even register result
1555 // in Even and the odd register result in Odd.
1556 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1557                              unsigned Extend, unsigned Opcode,
1558                              SDValue Op0, SDValue Op1,
1559                              SDValue &Even, SDValue &Odd) {
1560   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1561   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1562                                SDValue(In128, 0), Op1);
1563   bool Is32Bit = is32Bit(VT);
1564   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
1565   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
1566 }
1567
1568 // Return an i32 value that is 1 if the CC value produced by Glue is
1569 // in the mask CCMask and 0 otherwise.  CC is known to have a value
1570 // in CCValid, so other values can be ignored.
1571 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
1572                          unsigned CCValid, unsigned CCMask) {
1573   IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
1574   SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
1575
1576   if (Conversion.XORValue)
1577     Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
1578                          DAG.getConstant(Conversion.XORValue, MVT::i32));
1579
1580   if (Conversion.AddValue)
1581     Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
1582                          DAG.getConstant(Conversion.AddValue, MVT::i32));
1583
1584   // The SHR/AND sequence should get optimized to an RISBG.
1585   Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
1586                        DAG.getConstant(Conversion.Bit, MVT::i32));
1587   if (Conversion.Bit != 31)
1588     Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
1589                          DAG.getConstant(1, MVT::i32));
1590   return Result;
1591 }
1592
1593 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
1594                                           SelectionDAG &DAG) const {
1595   SDValue CmpOp0   = Op.getOperand(0);
1596   SDValue CmpOp1   = Op.getOperand(1);
1597   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1598   SDLoc DL(Op);
1599
1600   unsigned CCValid, CCMask;
1601   SDValue Glue = emitCmp(TM, DAG, DL, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1602   return emitSETCC(DAG, DL, Glue, CCValid, CCMask);
1603 }
1604
1605 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1606   SDValue Chain    = Op.getOperand(0);
1607   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1608   SDValue CmpOp0   = Op.getOperand(2);
1609   SDValue CmpOp1   = Op.getOperand(3);
1610   SDValue Dest     = Op.getOperand(4);
1611   SDLoc DL(Op);
1612
1613   unsigned CCValid, CCMask;
1614   SDValue Glue = emitCmp(TM, DAG, DL, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1615   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
1616                      Chain, DAG.getConstant(CCValid, MVT::i32),
1617                      DAG.getConstant(CCMask, MVT::i32), Dest, Glue);
1618 }
1619
1620 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
1621                                               SelectionDAG &DAG) const {
1622   SDValue CmpOp0   = Op.getOperand(0);
1623   SDValue CmpOp1   = Op.getOperand(1);
1624   SDValue TrueOp   = Op.getOperand(2);
1625   SDValue FalseOp  = Op.getOperand(3);
1626   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1627   SDLoc DL(Op);
1628
1629   unsigned CCValid, CCMask;
1630   SDValue Glue = emitCmp(TM, DAG, DL, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1631
1632   // Special case for handling -1/0 results.  The shifts we use here
1633   // should get optimized with the IPM conversion sequence.
1634   ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
1635   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
1636   if (TrueC && FalseC) {
1637     int64_t TrueVal = TrueC->getSExtValue();
1638     int64_t FalseVal = FalseC->getSExtValue();
1639     if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
1640       // Invert the condition if we want -1 on false.
1641       if (TrueVal == 0)
1642         CCMask ^= CCValid;
1643       SDValue Result = emitSETCC(DAG, DL, Glue, CCValid, CCMask);
1644       EVT VT = Op.getValueType();
1645       // Extend the result to VT.  Upper bits are ignored.
1646       if (!is32Bit(VT))
1647         Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
1648       // Sign-extend from the low bit.
1649       SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, MVT::i32);
1650       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
1651       return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
1652     }
1653   }
1654
1655   SmallVector<SDValue, 5> Ops;
1656   Ops.push_back(TrueOp);
1657   Ops.push_back(FalseOp);
1658   Ops.push_back(DAG.getConstant(CCValid, MVT::i32));
1659   Ops.push_back(DAG.getConstant(CCMask, MVT::i32));
1660   Ops.push_back(Glue);
1661
1662   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1663   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, &Ops[0], Ops.size());
1664 }
1665
1666 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
1667                                                   SelectionDAG &DAG) const {
1668   SDLoc DL(Node);
1669   const GlobalValue *GV = Node->getGlobal();
1670   int64_t Offset = Node->getOffset();
1671   EVT PtrVT = getPointerTy();
1672   Reloc::Model RM = TM.getRelocationModel();
1673   CodeModel::Model CM = TM.getCodeModel();
1674
1675   SDValue Result;
1676   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
1677     // Assign anchors at 1<<12 byte boundaries.
1678     uint64_t Anchor = Offset & ~uint64_t(0xfff);
1679     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
1680     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1681
1682     // The offset can be folded into the address if it is aligned to a halfword.
1683     Offset -= Anchor;
1684     if (Offset != 0 && (Offset & 1) == 0) {
1685       SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
1686       Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
1687       Offset = 0;
1688     }
1689   } else {
1690     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
1691     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1692     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
1693                          MachinePointerInfo::getGOT(), false, false, false, 0);
1694   }
1695
1696   // If there was a non-zero offset that we didn't fold, create an explicit
1697   // addition for it.
1698   if (Offset != 0)
1699     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
1700                          DAG.getConstant(Offset, PtrVT));
1701
1702   return Result;
1703 }
1704
1705 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
1706                                                      SelectionDAG &DAG) const {
1707   SDLoc DL(Node);
1708   const GlobalValue *GV = Node->getGlobal();
1709   EVT PtrVT = getPointerTy();
1710   TLSModel::Model model = TM.getTLSModel(GV);
1711
1712   if (model != TLSModel::LocalExec)
1713     llvm_unreachable("only local-exec TLS mode supported");
1714
1715   // The high part of the thread pointer is in access register 0.
1716   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1717                              DAG.getConstant(0, MVT::i32));
1718   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
1719
1720   // The low part of the thread pointer is in access register 1.
1721   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1722                              DAG.getConstant(1, MVT::i32));
1723   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
1724
1725   // Merge them into a single 64-bit address.
1726   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
1727                                     DAG.getConstant(32, PtrVT));
1728   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
1729
1730   // Get the offset of GA from the thread pointer.
1731   SystemZConstantPoolValue *CPV =
1732     SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
1733
1734   // Force the offset into the constant pool and load it from there.
1735   SDValue CPAddr = DAG.getConstantPool(CPV, PtrVT, 8);
1736   SDValue Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1737                                CPAddr, MachinePointerInfo::getConstantPool(),
1738                                false, false, false, 0);
1739
1740   // Add the base and offset together.
1741   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
1742 }
1743
1744 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
1745                                                  SelectionDAG &DAG) const {
1746   SDLoc DL(Node);
1747   const BlockAddress *BA = Node->getBlockAddress();
1748   int64_t Offset = Node->getOffset();
1749   EVT PtrVT = getPointerTy();
1750
1751   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
1752   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1753   return Result;
1754 }
1755
1756 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
1757                                               SelectionDAG &DAG) const {
1758   SDLoc DL(JT);
1759   EVT PtrVT = getPointerTy();
1760   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1761
1762   // Use LARL to load the address of the table.
1763   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1764 }
1765
1766 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
1767                                                  SelectionDAG &DAG) const {
1768   SDLoc DL(CP);
1769   EVT PtrVT = getPointerTy();
1770
1771   SDValue Result;
1772   if (CP->isMachineConstantPoolEntry())
1773     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1774                                        CP->getAlignment());
1775   else
1776     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1777                                        CP->getAlignment(), CP->getOffset());
1778
1779   // Use LARL to load the address of the constant pool entry.
1780   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1781 }
1782
1783 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
1784                                             SelectionDAG &DAG) const {
1785   SDLoc DL(Op);
1786   SDValue In = Op.getOperand(0);
1787   EVT InVT = In.getValueType();
1788   EVT ResVT = Op.getValueType();
1789
1790   if (InVT == MVT::i32 && ResVT == MVT::f32) {
1791     SDValue In64;
1792     if (Subtarget.hasHighWord()) {
1793       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
1794                                        MVT::i64);
1795       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
1796                                        MVT::i64, SDValue(U64, 0), In);
1797     } else {
1798       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
1799       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
1800                          DAG.getConstant(32, MVT::i64));
1801     }
1802     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
1803     return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
1804                                       DL, MVT::f32, Out64);
1805   }
1806   if (InVT == MVT::f32 && ResVT == MVT::i32) {
1807     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
1808     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
1809                                              MVT::f64, SDValue(U64, 0), In);
1810     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
1811     if (Subtarget.hasHighWord())
1812       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
1813                                         MVT::i32, Out64);
1814     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
1815                                 DAG.getConstant(32, MVT::i64));
1816     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
1817   }
1818   llvm_unreachable("Unexpected bitcast combination");
1819 }
1820
1821 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
1822                                             SelectionDAG &DAG) const {
1823   MachineFunction &MF = DAG.getMachineFunction();
1824   SystemZMachineFunctionInfo *FuncInfo =
1825     MF.getInfo<SystemZMachineFunctionInfo>();
1826   EVT PtrVT = getPointerTy();
1827
1828   SDValue Chain   = Op.getOperand(0);
1829   SDValue Addr    = Op.getOperand(1);
1830   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1831   SDLoc DL(Op);
1832
1833   // The initial values of each field.
1834   const unsigned NumFields = 4;
1835   SDValue Fields[NumFields] = {
1836     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), PtrVT),
1837     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), PtrVT),
1838     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
1839     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
1840   };
1841
1842   // Store each field into its respective slot.
1843   SDValue MemOps[NumFields];
1844   unsigned Offset = 0;
1845   for (unsigned I = 0; I < NumFields; ++I) {
1846     SDValue FieldAddr = Addr;
1847     if (Offset != 0)
1848       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
1849                               DAG.getIntPtrConstant(Offset));
1850     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
1851                              MachinePointerInfo(SV, Offset),
1852                              false, false, 0);
1853     Offset += 8;
1854   }
1855   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps, NumFields);
1856 }
1857
1858 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
1859                                            SelectionDAG &DAG) const {
1860   SDValue Chain      = Op.getOperand(0);
1861   SDValue DstPtr     = Op.getOperand(1);
1862   SDValue SrcPtr     = Op.getOperand(2);
1863   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
1864   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
1865   SDLoc DL(Op);
1866
1867   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32),
1868                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
1869                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
1870 }
1871
1872 SDValue SystemZTargetLowering::
1873 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
1874   SDValue Chain = Op.getOperand(0);
1875   SDValue Size  = Op.getOperand(1);
1876   SDLoc DL(Op);
1877
1878   unsigned SPReg = getStackPointerRegisterToSaveRestore();
1879
1880   // Get a reference to the stack pointer.
1881   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
1882
1883   // Get the new stack pointer value.
1884   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
1885
1886   // Copy the new stack pointer back.
1887   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
1888
1889   // The allocated data lives above the 160 bytes allocated for the standard
1890   // frame, plus any outgoing stack arguments.  We don't know how much that
1891   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
1892   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
1893   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
1894
1895   SDValue Ops[2] = { Result, Chain };
1896   return DAG.getMergeValues(Ops, 2, DL);
1897 }
1898
1899 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
1900                                               SelectionDAG &DAG) const {
1901   EVT VT = Op.getValueType();
1902   SDLoc DL(Op);
1903   SDValue Ops[2];
1904   if (is32Bit(VT))
1905     // Just do a normal 64-bit multiplication and extract the results.
1906     // We define this so that it can be used for constant division.
1907     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
1908                     Op.getOperand(1), Ops[1], Ops[0]);
1909   else {
1910     // Do a full 128-bit multiplication based on UMUL_LOHI64:
1911     //
1912     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
1913     //
1914     // but using the fact that the upper halves are either all zeros
1915     // or all ones:
1916     //
1917     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
1918     //
1919     // and grouping the right terms together since they are quicker than the
1920     // multiplication:
1921     //
1922     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
1923     SDValue C63 = DAG.getConstant(63, MVT::i64);
1924     SDValue LL = Op.getOperand(0);
1925     SDValue RL = Op.getOperand(1);
1926     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
1927     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
1928     // UMUL_LOHI64 returns the low result in the odd register and the high
1929     // result in the even register.  SMUL_LOHI is defined to return the
1930     // low half first, so the results are in reverse order.
1931     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
1932                      LL, RL, Ops[1], Ops[0]);
1933     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
1934     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
1935     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
1936     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
1937   }
1938   return DAG.getMergeValues(Ops, 2, DL);
1939 }
1940
1941 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
1942                                               SelectionDAG &DAG) const {
1943   EVT VT = Op.getValueType();
1944   SDLoc DL(Op);
1945   SDValue Ops[2];
1946   if (is32Bit(VT))
1947     // Just do a normal 64-bit multiplication and extract the results.
1948     // We define this so that it can be used for constant division.
1949     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
1950                     Op.getOperand(1), Ops[1], Ops[0]);
1951   else
1952     // UMUL_LOHI64 returns the low result in the odd register and the high
1953     // result in the even register.  UMUL_LOHI is defined to return the
1954     // low half first, so the results are in reverse order.
1955     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
1956                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1957   return DAG.getMergeValues(Ops, 2, DL);
1958 }
1959
1960 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
1961                                             SelectionDAG &DAG) const {
1962   SDValue Op0 = Op.getOperand(0);
1963   SDValue Op1 = Op.getOperand(1);
1964   EVT VT = Op.getValueType();
1965   SDLoc DL(Op);
1966   unsigned Opcode;
1967
1968   // We use DSGF for 32-bit division.
1969   if (is32Bit(VT)) {
1970     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
1971     Opcode = SystemZISD::SDIVREM32;
1972   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
1973     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
1974     Opcode = SystemZISD::SDIVREM32;
1975   } else    
1976     Opcode = SystemZISD::SDIVREM64;
1977
1978   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
1979   // input is "don't care".  The instruction returns the remainder in
1980   // the even register and the quotient in the odd register.
1981   SDValue Ops[2];
1982   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
1983                    Op0, Op1, Ops[1], Ops[0]);
1984   return DAG.getMergeValues(Ops, 2, DL);
1985 }
1986
1987 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
1988                                             SelectionDAG &DAG) const {
1989   EVT VT = Op.getValueType();
1990   SDLoc DL(Op);
1991
1992   // DL(G) uses a double-width dividend, so we need to clear the even
1993   // register in the GR128 input.  The instruction returns the remainder
1994   // in the even register and the quotient in the odd register.
1995   SDValue Ops[2];
1996   if (is32Bit(VT))
1997     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
1998                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1999   else
2000     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
2001                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2002   return DAG.getMergeValues(Ops, 2, DL);
2003 }
2004
2005 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
2006   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
2007
2008   // Get the known-zero masks for each operand.
2009   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
2010   APInt KnownZero[2], KnownOne[2];
2011   DAG.ComputeMaskedBits(Ops[0], KnownZero[0], KnownOne[0]);
2012   DAG.ComputeMaskedBits(Ops[1], KnownZero[1], KnownOne[1]);
2013
2014   // See if the upper 32 bits of one operand and the lower 32 bits of the
2015   // other are known zero.  They are the low and high operands respectively.
2016   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
2017                        KnownZero[1].getZExtValue() };
2018   unsigned High, Low;
2019   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
2020     High = 1, Low = 0;
2021   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
2022     High = 0, Low = 1;
2023   else
2024     return Op;
2025
2026   SDValue LowOp = Ops[Low];
2027   SDValue HighOp = Ops[High];
2028
2029   // If the high part is a constant, we're better off using IILH.
2030   if (HighOp.getOpcode() == ISD::Constant)
2031     return Op;
2032
2033   // If the low part is a constant that is outside the range of LHI,
2034   // then we're better off using IILF.
2035   if (LowOp.getOpcode() == ISD::Constant) {
2036     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
2037     if (!isInt<16>(Value))
2038       return Op;
2039   }
2040
2041   // Check whether the high part is an AND that doesn't change the
2042   // high 32 bits and just masks out low bits.  We can skip it if so.
2043   if (HighOp.getOpcode() == ISD::AND &&
2044       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
2045     SDValue HighOp0 = HighOp.getOperand(0);
2046     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
2047     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
2048       HighOp = HighOp0;
2049   }
2050
2051   // Take advantage of the fact that all GR32 operations only change the
2052   // low 32 bits by truncating Low to an i32 and inserting it directly
2053   // using a subreg.  The interesting cases are those where the truncation
2054   // can be folded.
2055   SDLoc DL(Op);
2056   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
2057   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
2058                                    MVT::i64, HighOp, Low32);
2059 }
2060
2061 // Op is an atomic load.  Lower it into a normal volatile load.
2062 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
2063                                                 SelectionDAG &DAG) const {
2064   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
2065   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
2066                         Node->getChain(), Node->getBasePtr(),
2067                         Node->getMemoryVT(), Node->getMemOperand());
2068 }
2069
2070 // Op is an atomic store.  Lower it into a normal volatile store followed
2071 // by a serialization.
2072 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
2073                                                  SelectionDAG &DAG) const {
2074   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
2075   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
2076                                     Node->getBasePtr(), Node->getMemoryVT(),
2077                                     Node->getMemOperand());
2078   return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
2079                                     Chain), 0);
2080 }
2081
2082 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
2083 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
2084 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
2085                                                    SelectionDAG &DAG,
2086                                                    unsigned Opcode) const {
2087   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
2088
2089   // 32-bit operations need no code outside the main loop.
2090   EVT NarrowVT = Node->getMemoryVT();
2091   EVT WideVT = MVT::i32;
2092   if (NarrowVT == WideVT)
2093     return Op;
2094
2095   int64_t BitSize = NarrowVT.getSizeInBits();
2096   SDValue ChainIn = Node->getChain();
2097   SDValue Addr = Node->getBasePtr();
2098   SDValue Src2 = Node->getVal();
2099   MachineMemOperand *MMO = Node->getMemOperand();
2100   SDLoc DL(Node);
2101   EVT PtrVT = Addr.getValueType();
2102
2103   // Convert atomic subtracts of constants into additions.
2104   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
2105     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Src2)) {
2106       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
2107       Src2 = DAG.getConstant(-Const->getSExtValue(), Src2.getValueType());
2108     }
2109
2110   // Get the address of the containing word.
2111   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2112                                     DAG.getConstant(-4, PtrVT));
2113
2114   // Get the number of bits that the word must be rotated left in order
2115   // to bring the field to the top bits of a GR32.
2116   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2117                                  DAG.getConstant(3, PtrVT));
2118   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2119
2120   // Get the complementing shift amount, for rotating a field in the top
2121   // bits back to its proper position.
2122   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2123                                     DAG.getConstant(0, WideVT), BitShift);
2124
2125   // Extend the source operand to 32 bits and prepare it for the inner loop.
2126   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
2127   // operations require the source to be shifted in advance.  (This shift
2128   // can be folded if the source is constant.)  For AND and NAND, the lower
2129   // bits must be set, while for other opcodes they should be left clear.
2130   if (Opcode != SystemZISD::ATOMIC_SWAPW)
2131     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
2132                        DAG.getConstant(32 - BitSize, WideVT));
2133   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
2134       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
2135     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
2136                        DAG.getConstant(uint32_t(-1) >> BitSize, WideVT));
2137
2138   // Construct the ATOMIC_LOADW_* node.
2139   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2140   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
2141                     DAG.getConstant(BitSize, WideVT) };
2142   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
2143                                              array_lengthof(Ops),
2144                                              NarrowVT, MMO);
2145
2146   // Rotate the result of the final CS so that the field is in the lower
2147   // bits of a GR32, then truncate it.
2148   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
2149                                     DAG.getConstant(BitSize, WideVT));
2150   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
2151
2152   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
2153   return DAG.getMergeValues(RetOps, 2, DL);
2154 }
2155
2156 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
2157 // into a fullword ATOMIC_CMP_SWAPW operation.
2158 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
2159                                                     SelectionDAG &DAG) const {
2160   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
2161
2162   // We have native support for 32-bit compare and swap.
2163   EVT NarrowVT = Node->getMemoryVT();
2164   EVT WideVT = MVT::i32;
2165   if (NarrowVT == WideVT)
2166     return Op;
2167
2168   int64_t BitSize = NarrowVT.getSizeInBits();
2169   SDValue ChainIn = Node->getOperand(0);
2170   SDValue Addr = Node->getOperand(1);
2171   SDValue CmpVal = Node->getOperand(2);
2172   SDValue SwapVal = Node->getOperand(3);
2173   MachineMemOperand *MMO = Node->getMemOperand();
2174   SDLoc DL(Node);
2175   EVT PtrVT = Addr.getValueType();
2176
2177   // Get the address of the containing word.
2178   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2179                                     DAG.getConstant(-4, PtrVT));
2180
2181   // Get the number of bits that the word must be rotated left in order
2182   // to bring the field to the top bits of a GR32.
2183   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2184                                  DAG.getConstant(3, PtrVT));
2185   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2186
2187   // Get the complementing shift amount, for rotating a field in the top
2188   // bits back to its proper position.
2189   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2190                                     DAG.getConstant(0, WideVT), BitShift);
2191
2192   // Construct the ATOMIC_CMP_SWAPW node.
2193   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2194   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
2195                     NegBitShift, DAG.getConstant(BitSize, WideVT) };
2196   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
2197                                              VTList, Ops, array_lengthof(Ops),
2198                                              NarrowVT, MMO);
2199   return AtomicOp;
2200 }
2201
2202 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
2203                                               SelectionDAG &DAG) const {
2204   MachineFunction &MF = DAG.getMachineFunction();
2205   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2206   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
2207                             SystemZ::R15D, Op.getValueType());
2208 }
2209
2210 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
2211                                                  SelectionDAG &DAG) const {
2212   MachineFunction &MF = DAG.getMachineFunction();
2213   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2214   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
2215                           SystemZ::R15D, Op.getOperand(1));
2216 }
2217
2218 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
2219                                              SelectionDAG &DAG) const {
2220   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2221   if (!IsData)
2222     // Just preserve the chain.
2223     return Op.getOperand(0);
2224
2225   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2226   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
2227   MemIntrinsicSDNode *Node = cast<MemIntrinsicSDNode>(Op.getNode());
2228   SDValue Ops[] = {
2229     Op.getOperand(0),
2230     DAG.getConstant(Code, MVT::i32),
2231     Op.getOperand(1)
2232   };
2233   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, SDLoc(Op),
2234                                  Node->getVTList(), Ops, array_lengthof(Ops),
2235                                  Node->getMemoryVT(), Node->getMemOperand());
2236 }
2237
2238 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
2239                                               SelectionDAG &DAG) const {
2240   switch (Op.getOpcode()) {
2241   case ISD::BR_CC:
2242     return lowerBR_CC(Op, DAG);
2243   case ISD::SELECT_CC:
2244     return lowerSELECT_CC(Op, DAG);
2245   case ISD::SETCC:
2246     return lowerSETCC(Op, DAG);
2247   case ISD::GlobalAddress:
2248     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
2249   case ISD::GlobalTLSAddress:
2250     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
2251   case ISD::BlockAddress:
2252     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
2253   case ISD::JumpTable:
2254     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
2255   case ISD::ConstantPool:
2256     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
2257   case ISD::BITCAST:
2258     return lowerBITCAST(Op, DAG);
2259   case ISD::VASTART:
2260     return lowerVASTART(Op, DAG);
2261   case ISD::VACOPY:
2262     return lowerVACOPY(Op, DAG);
2263   case ISD::DYNAMIC_STACKALLOC:
2264     return lowerDYNAMIC_STACKALLOC(Op, DAG);
2265   case ISD::SMUL_LOHI:
2266     return lowerSMUL_LOHI(Op, DAG);
2267   case ISD::UMUL_LOHI:
2268     return lowerUMUL_LOHI(Op, DAG);
2269   case ISD::SDIVREM:
2270     return lowerSDIVREM(Op, DAG);
2271   case ISD::UDIVREM:
2272     return lowerUDIVREM(Op, DAG);
2273   case ISD::OR:
2274     return lowerOR(Op, DAG);
2275   case ISD::ATOMIC_SWAP:
2276     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
2277   case ISD::ATOMIC_STORE:
2278     return lowerATOMIC_STORE(Op, DAG);
2279   case ISD::ATOMIC_LOAD:
2280     return lowerATOMIC_LOAD(Op, DAG);
2281   case ISD::ATOMIC_LOAD_ADD:
2282     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
2283   case ISD::ATOMIC_LOAD_SUB:
2284     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
2285   case ISD::ATOMIC_LOAD_AND:
2286     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
2287   case ISD::ATOMIC_LOAD_OR:
2288     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
2289   case ISD::ATOMIC_LOAD_XOR:
2290     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
2291   case ISD::ATOMIC_LOAD_NAND:
2292     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
2293   case ISD::ATOMIC_LOAD_MIN:
2294     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
2295   case ISD::ATOMIC_LOAD_MAX:
2296     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
2297   case ISD::ATOMIC_LOAD_UMIN:
2298     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
2299   case ISD::ATOMIC_LOAD_UMAX:
2300     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
2301   case ISD::ATOMIC_CMP_SWAP:
2302     return lowerATOMIC_CMP_SWAP(Op, DAG);
2303   case ISD::STACKSAVE:
2304     return lowerSTACKSAVE(Op, DAG);
2305   case ISD::STACKRESTORE:
2306     return lowerSTACKRESTORE(Op, DAG);
2307   case ISD::PREFETCH:
2308     return lowerPREFETCH(Op, DAG);
2309   default:
2310     llvm_unreachable("Unexpected node to lower");
2311   }
2312 }
2313
2314 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
2315 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
2316   switch (Opcode) {
2317     OPCODE(RET_FLAG);
2318     OPCODE(CALL);
2319     OPCODE(SIBCALL);
2320     OPCODE(PCREL_WRAPPER);
2321     OPCODE(PCREL_OFFSET);
2322     OPCODE(ICMP);
2323     OPCODE(FCMP);
2324     OPCODE(TM);
2325     OPCODE(BR_CCMASK);
2326     OPCODE(SELECT_CCMASK);
2327     OPCODE(ADJDYNALLOC);
2328     OPCODE(EXTRACT_ACCESS);
2329     OPCODE(UMUL_LOHI64);
2330     OPCODE(SDIVREM64);
2331     OPCODE(UDIVREM32);
2332     OPCODE(UDIVREM64);
2333     OPCODE(MVC);
2334     OPCODE(MVC_LOOP);
2335     OPCODE(NC);
2336     OPCODE(NC_LOOP);
2337     OPCODE(OC);
2338     OPCODE(OC_LOOP);
2339     OPCODE(XC);
2340     OPCODE(XC_LOOP);
2341     OPCODE(CLC);
2342     OPCODE(CLC_LOOP);
2343     OPCODE(STRCMP);
2344     OPCODE(STPCPY);
2345     OPCODE(SEARCH_STRING);
2346     OPCODE(IPM);
2347     OPCODE(SERIALIZE);
2348     OPCODE(ATOMIC_SWAPW);
2349     OPCODE(ATOMIC_LOADW_ADD);
2350     OPCODE(ATOMIC_LOADW_SUB);
2351     OPCODE(ATOMIC_LOADW_AND);
2352     OPCODE(ATOMIC_LOADW_OR);
2353     OPCODE(ATOMIC_LOADW_XOR);
2354     OPCODE(ATOMIC_LOADW_NAND);
2355     OPCODE(ATOMIC_LOADW_MIN);
2356     OPCODE(ATOMIC_LOADW_MAX);
2357     OPCODE(ATOMIC_LOADW_UMIN);
2358     OPCODE(ATOMIC_LOADW_UMAX);
2359     OPCODE(ATOMIC_CMP_SWAPW);
2360     OPCODE(PREFETCH);
2361   }
2362   return NULL;
2363 #undef OPCODE
2364 }
2365
2366 //===----------------------------------------------------------------------===//
2367 // Custom insertion
2368 //===----------------------------------------------------------------------===//
2369
2370 // Create a new basic block after MBB.
2371 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
2372   MachineFunction &MF = *MBB->getParent();
2373   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
2374   MF.insert(llvm::next(MachineFunction::iterator(MBB)), NewMBB);
2375   return NewMBB;
2376 }
2377
2378 // Split MBB after MI and return the new block (the one that contains
2379 // instructions after MI).
2380 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
2381                                           MachineBasicBlock *MBB) {
2382   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
2383   NewMBB->splice(NewMBB->begin(), MBB,
2384                  llvm::next(MachineBasicBlock::iterator(MI)),
2385                  MBB->end());
2386   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
2387   return NewMBB;
2388 }
2389
2390 // Split MBB before MI and return the new block (the one that contains MI).
2391 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
2392                                            MachineBasicBlock *MBB) {
2393   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
2394   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
2395   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
2396   return NewMBB;
2397 }
2398
2399 // Force base value Base into a register before MI.  Return the register.
2400 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
2401                          const SystemZInstrInfo *TII) {
2402   if (Base.isReg())
2403     return Base.getReg();
2404
2405   MachineBasicBlock *MBB = MI->getParent();
2406   MachineFunction &MF = *MBB->getParent();
2407   MachineRegisterInfo &MRI = MF.getRegInfo();
2408
2409   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2410   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
2411     .addOperand(Base).addImm(0).addReg(0);
2412   return Reg;
2413 }
2414
2415 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
2416 MachineBasicBlock *
2417 SystemZTargetLowering::emitSelect(MachineInstr *MI,
2418                                   MachineBasicBlock *MBB) const {
2419   const SystemZInstrInfo *TII = TM.getInstrInfo();
2420
2421   unsigned DestReg  = MI->getOperand(0).getReg();
2422   unsigned TrueReg  = MI->getOperand(1).getReg();
2423   unsigned FalseReg = MI->getOperand(2).getReg();
2424   unsigned CCValid  = MI->getOperand(3).getImm();
2425   unsigned CCMask   = MI->getOperand(4).getImm();
2426   DebugLoc DL       = MI->getDebugLoc();
2427
2428   MachineBasicBlock *StartMBB = MBB;
2429   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
2430   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
2431
2432   //  StartMBB:
2433   //   BRC CCMask, JoinMBB
2434   //   # fallthrough to FalseMBB
2435   MBB = StartMBB;
2436   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2437     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
2438   MBB->addSuccessor(JoinMBB);
2439   MBB->addSuccessor(FalseMBB);
2440
2441   //  FalseMBB:
2442   //   # fallthrough to JoinMBB
2443   MBB = FalseMBB;
2444   MBB->addSuccessor(JoinMBB);
2445
2446   //  JoinMBB:
2447   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
2448   //  ...
2449   MBB = JoinMBB;
2450   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
2451     .addReg(TrueReg).addMBB(StartMBB)
2452     .addReg(FalseReg).addMBB(FalseMBB);
2453
2454   MI->eraseFromParent();
2455   return JoinMBB;
2456 }
2457
2458 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
2459 // StoreOpcode is the store to use and Invert says whether the store should
2460 // happen when the condition is false rather than true.  If a STORE ON
2461 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
2462 MachineBasicBlock *
2463 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
2464                                      MachineBasicBlock *MBB,
2465                                      unsigned StoreOpcode, unsigned STOCOpcode,
2466                                      bool Invert) const {
2467   const SystemZInstrInfo *TII = TM.getInstrInfo();
2468
2469   unsigned SrcReg     = MI->getOperand(0).getReg();
2470   MachineOperand Base = MI->getOperand(1);
2471   int64_t Disp        = MI->getOperand(2).getImm();
2472   unsigned IndexReg   = MI->getOperand(3).getReg();
2473   unsigned CCValid    = MI->getOperand(4).getImm();
2474   unsigned CCMask     = MI->getOperand(5).getImm();
2475   DebugLoc DL         = MI->getDebugLoc();
2476
2477   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
2478
2479   // Use STOCOpcode if possible.  We could use different store patterns in
2480   // order to avoid matching the index register, but the performance trade-offs
2481   // might be more complicated in that case.
2482   if (STOCOpcode && !IndexReg && TM.getSubtargetImpl()->hasLoadStoreOnCond()) {
2483     if (Invert)
2484       CCMask ^= CCValid;
2485     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
2486       .addReg(SrcReg).addOperand(Base).addImm(Disp)
2487       .addImm(CCValid).addImm(CCMask);
2488     MI->eraseFromParent();
2489     return MBB;
2490   }
2491
2492   // Get the condition needed to branch around the store.
2493   if (!Invert)
2494     CCMask ^= CCValid;
2495
2496   MachineBasicBlock *StartMBB = MBB;
2497   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
2498   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
2499
2500   //  StartMBB:
2501   //   BRC CCMask, JoinMBB
2502   //   # fallthrough to FalseMBB
2503   MBB = StartMBB;
2504   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2505     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
2506   MBB->addSuccessor(JoinMBB);
2507   MBB->addSuccessor(FalseMBB);
2508
2509   //  FalseMBB:
2510   //   store %SrcReg, %Disp(%Index,%Base)
2511   //   # fallthrough to JoinMBB
2512   MBB = FalseMBB;
2513   BuildMI(MBB, DL, TII->get(StoreOpcode))
2514     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
2515   MBB->addSuccessor(JoinMBB);
2516
2517   MI->eraseFromParent();
2518   return JoinMBB;
2519 }
2520
2521 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
2522 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
2523 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
2524 // BitSize is the width of the field in bits, or 0 if this is a partword
2525 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
2526 // is one of the operands.  Invert says whether the field should be
2527 // inverted after performing BinOpcode (e.g. for NAND).
2528 MachineBasicBlock *
2529 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
2530                                             MachineBasicBlock *MBB,
2531                                             unsigned BinOpcode,
2532                                             unsigned BitSize,
2533                                             bool Invert) const {
2534   const SystemZInstrInfo *TII = TM.getInstrInfo();
2535   MachineFunction &MF = *MBB->getParent();
2536   MachineRegisterInfo &MRI = MF.getRegInfo();
2537   bool IsSubWord = (BitSize < 32);
2538
2539   // Extract the operands.  Base can be a register or a frame index.
2540   // Src2 can be a register or immediate.
2541   unsigned Dest        = MI->getOperand(0).getReg();
2542   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2543   int64_t Disp         = MI->getOperand(2).getImm();
2544   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
2545   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2546   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2547   DebugLoc DL          = MI->getDebugLoc();
2548   if (IsSubWord)
2549     BitSize = MI->getOperand(6).getImm();
2550
2551   // Subword operations use 32-bit registers.
2552   const TargetRegisterClass *RC = (BitSize <= 32 ?
2553                                    &SystemZ::GR32BitRegClass :
2554                                    &SystemZ::GR64BitRegClass);
2555   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2556   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2557
2558   // Get the right opcodes for the displacement.
2559   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2560   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2561   assert(LOpcode && CSOpcode && "Displacement out of range");
2562
2563   // Create virtual registers for temporary results.
2564   unsigned OrigVal       = MRI.createVirtualRegister(RC);
2565   unsigned OldVal        = MRI.createVirtualRegister(RC);
2566   unsigned NewVal        = (BinOpcode || IsSubWord ?
2567                             MRI.createVirtualRegister(RC) : Src2.getReg());
2568   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
2569   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
2570
2571   // Insert a basic block for the main loop.
2572   MachineBasicBlock *StartMBB = MBB;
2573   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
2574   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2575
2576   //  StartMBB:
2577   //   ...
2578   //   %OrigVal = L Disp(%Base)
2579   //   # fall through to LoopMMB
2580   MBB = StartMBB;
2581   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
2582     .addOperand(Base).addImm(Disp).addReg(0);
2583   MBB->addSuccessor(LoopMBB);
2584
2585   //  LoopMBB:
2586   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
2587   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
2588   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
2589   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2590   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2591   //   JNE LoopMBB
2592   //   # fall through to DoneMMB
2593   MBB = LoopMBB;
2594   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2595     .addReg(OrigVal).addMBB(StartMBB)
2596     .addReg(Dest).addMBB(LoopMBB);
2597   if (IsSubWord)
2598     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
2599       .addReg(OldVal).addReg(BitShift).addImm(0);
2600   if (Invert) {
2601     // Perform the operation normally and then invert every bit of the field.
2602     unsigned Tmp = MRI.createVirtualRegister(RC);
2603     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
2604       .addReg(RotatedOldVal).addOperand(Src2);
2605     if (BitSize < 32)
2606       // XILF with the upper BitSize bits set.
2607       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
2608         .addReg(Tmp).addImm(uint32_t(~0 << (32 - BitSize)));
2609     else if (BitSize == 32)
2610       // XILF with every bit set.
2611       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
2612         .addReg(Tmp).addImm(~uint32_t(0));
2613     else {
2614       // Use LCGR and add -1 to the result, which is more compact than
2615       // an XILF, XILH pair.
2616       unsigned Tmp2 = MRI.createVirtualRegister(RC);
2617       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
2618       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
2619         .addReg(Tmp2).addImm(-1);
2620     }
2621   } else if (BinOpcode)
2622     // A simply binary operation.
2623     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
2624       .addReg(RotatedOldVal).addOperand(Src2);
2625   else if (IsSubWord)
2626     // Use RISBG to rotate Src2 into position and use it to replace the
2627     // field in RotatedOldVal.
2628     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
2629       .addReg(RotatedOldVal).addReg(Src2.getReg())
2630       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
2631   if (IsSubWord)
2632     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2633       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2634   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2635     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2636   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2637     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2638   MBB->addSuccessor(LoopMBB);
2639   MBB->addSuccessor(DoneMBB);
2640
2641   MI->eraseFromParent();
2642   return DoneMBB;
2643 }
2644
2645 // Implement EmitInstrWithCustomInserter for pseudo
2646 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
2647 // instruction that should be used to compare the current field with the
2648 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
2649 // for when the current field should be kept.  BitSize is the width of
2650 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
2651 MachineBasicBlock *
2652 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
2653                                             MachineBasicBlock *MBB,
2654                                             unsigned CompareOpcode,
2655                                             unsigned KeepOldMask,
2656                                             unsigned BitSize) const {
2657   const SystemZInstrInfo *TII = TM.getInstrInfo();
2658   MachineFunction &MF = *MBB->getParent();
2659   MachineRegisterInfo &MRI = MF.getRegInfo();
2660   bool IsSubWord = (BitSize < 32);
2661
2662   // Extract the operands.  Base can be a register or a frame index.
2663   unsigned Dest        = MI->getOperand(0).getReg();
2664   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2665   int64_t  Disp        = MI->getOperand(2).getImm();
2666   unsigned Src2        = MI->getOperand(3).getReg();
2667   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2668   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2669   DebugLoc DL          = MI->getDebugLoc();
2670   if (IsSubWord)
2671     BitSize = MI->getOperand(6).getImm();
2672
2673   // Subword operations use 32-bit registers.
2674   const TargetRegisterClass *RC = (BitSize <= 32 ?
2675                                    &SystemZ::GR32BitRegClass :
2676                                    &SystemZ::GR64BitRegClass);
2677   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2678   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2679
2680   // Get the right opcodes for the displacement.
2681   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2682   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2683   assert(LOpcode && CSOpcode && "Displacement out of range");
2684
2685   // Create virtual registers for temporary results.
2686   unsigned OrigVal       = MRI.createVirtualRegister(RC);
2687   unsigned OldVal        = MRI.createVirtualRegister(RC);
2688   unsigned NewVal        = MRI.createVirtualRegister(RC);
2689   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
2690   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
2691   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
2692
2693   // Insert 3 basic blocks for the loop.
2694   MachineBasicBlock *StartMBB  = MBB;
2695   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
2696   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
2697   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
2698   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
2699
2700   //  StartMBB:
2701   //   ...
2702   //   %OrigVal     = L Disp(%Base)
2703   //   # fall through to LoopMMB
2704   MBB = StartMBB;
2705   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
2706     .addOperand(Base).addImm(Disp).addReg(0);
2707   MBB->addSuccessor(LoopMBB);
2708
2709   //  LoopMBB:
2710   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
2711   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
2712   //   CompareOpcode %RotatedOldVal, %Src2
2713   //   BRC KeepOldMask, UpdateMBB
2714   MBB = LoopMBB;
2715   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2716     .addReg(OrigVal).addMBB(StartMBB)
2717     .addReg(Dest).addMBB(UpdateMBB);
2718   if (IsSubWord)
2719     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
2720       .addReg(OldVal).addReg(BitShift).addImm(0);
2721   BuildMI(MBB, DL, TII->get(CompareOpcode))
2722     .addReg(RotatedOldVal).addReg(Src2);
2723   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2724     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
2725   MBB->addSuccessor(UpdateMBB);
2726   MBB->addSuccessor(UseAltMBB);
2727
2728   //  UseAltMBB:
2729   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
2730   //   # fall through to UpdateMMB
2731   MBB = UseAltMBB;
2732   if (IsSubWord)
2733     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
2734       .addReg(RotatedOldVal).addReg(Src2)
2735       .addImm(32).addImm(31 + BitSize).addImm(0);
2736   MBB->addSuccessor(UpdateMBB);
2737
2738   //  UpdateMBB:
2739   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
2740   //                        [ %RotatedAltVal, UseAltMBB ]
2741   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2742   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2743   //   JNE LoopMBB
2744   //   # fall through to DoneMMB
2745   MBB = UpdateMBB;
2746   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
2747     .addReg(RotatedOldVal).addMBB(LoopMBB)
2748     .addReg(RotatedAltVal).addMBB(UseAltMBB);
2749   if (IsSubWord)
2750     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2751       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2752   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2753     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2754   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2755     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2756   MBB->addSuccessor(LoopMBB);
2757   MBB->addSuccessor(DoneMBB);
2758
2759   MI->eraseFromParent();
2760   return DoneMBB;
2761 }
2762
2763 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
2764 // instruction MI.
2765 MachineBasicBlock *
2766 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
2767                                           MachineBasicBlock *MBB) const {
2768   const SystemZInstrInfo *TII = TM.getInstrInfo();
2769   MachineFunction &MF = *MBB->getParent();
2770   MachineRegisterInfo &MRI = MF.getRegInfo();
2771
2772   // Extract the operands.  Base can be a register or a frame index.
2773   unsigned Dest        = MI->getOperand(0).getReg();
2774   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2775   int64_t  Disp        = MI->getOperand(2).getImm();
2776   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
2777   unsigned OrigSwapVal = MI->getOperand(4).getReg();
2778   unsigned BitShift    = MI->getOperand(5).getReg();
2779   unsigned NegBitShift = MI->getOperand(6).getReg();
2780   int64_t  BitSize     = MI->getOperand(7).getImm();
2781   DebugLoc DL          = MI->getDebugLoc();
2782
2783   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
2784
2785   // Get the right opcodes for the displacement.
2786   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
2787   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
2788   assert(LOpcode && CSOpcode && "Displacement out of range");
2789
2790   // Create virtual registers for temporary results.
2791   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
2792   unsigned OldVal       = MRI.createVirtualRegister(RC);
2793   unsigned CmpVal       = MRI.createVirtualRegister(RC);
2794   unsigned SwapVal      = MRI.createVirtualRegister(RC);
2795   unsigned StoreVal     = MRI.createVirtualRegister(RC);
2796   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
2797   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
2798   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
2799
2800   // Insert 2 basic blocks for the loop.
2801   MachineBasicBlock *StartMBB = MBB;
2802   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
2803   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2804   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
2805
2806   //  StartMBB:
2807   //   ...
2808   //   %OrigOldVal     = L Disp(%Base)
2809   //   # fall through to LoopMMB
2810   MBB = StartMBB;
2811   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
2812     .addOperand(Base).addImm(Disp).addReg(0);
2813   MBB->addSuccessor(LoopMBB);
2814
2815   //  LoopMBB:
2816   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
2817   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
2818   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
2819   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
2820   //                      ^^ The low BitSize bits contain the field
2821   //                         of interest.
2822   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
2823   //                      ^^ Replace the upper 32-BitSize bits of the
2824   //                         comparison value with those that we loaded,
2825   //                         so that we can use a full word comparison.
2826   //   CR %Dest, %RetryCmpVal
2827   //   JNE DoneMBB
2828   //   # Fall through to SetMBB
2829   MBB = LoopMBB;
2830   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2831     .addReg(OrigOldVal).addMBB(StartMBB)
2832     .addReg(RetryOldVal).addMBB(SetMBB);
2833   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
2834     .addReg(OrigCmpVal).addMBB(StartMBB)
2835     .addReg(RetryCmpVal).addMBB(SetMBB);
2836   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
2837     .addReg(OrigSwapVal).addMBB(StartMBB)
2838     .addReg(RetrySwapVal).addMBB(SetMBB);
2839   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
2840     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
2841   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
2842     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2843   BuildMI(MBB, DL, TII->get(SystemZ::CR))
2844     .addReg(Dest).addReg(RetryCmpVal);
2845   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2846     .addImm(SystemZ::CCMASK_ICMP)
2847     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
2848   MBB->addSuccessor(DoneMBB);
2849   MBB->addSuccessor(SetMBB);
2850
2851   //  SetMBB:
2852   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
2853   //                      ^^ Replace the upper 32-BitSize bits of the new
2854   //                         value with those that we loaded.
2855   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
2856   //                      ^^ Rotate the new field to its proper position.
2857   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
2858   //   JNE LoopMBB
2859   //   # fall through to ExitMMB
2860   MBB = SetMBB;
2861   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
2862     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2863   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
2864     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
2865   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
2866     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
2867   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2868     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2869   MBB->addSuccessor(LoopMBB);
2870   MBB->addSuccessor(DoneMBB);
2871
2872   MI->eraseFromParent();
2873   return DoneMBB;
2874 }
2875
2876 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
2877 // if the high register of the GR128 value must be cleared or false if
2878 // it's "don't care".  SubReg is subreg_l32 when extending a GR32
2879 // and subreg_l64 when extending a GR64.
2880 MachineBasicBlock *
2881 SystemZTargetLowering::emitExt128(MachineInstr *MI,
2882                                   MachineBasicBlock *MBB,
2883                                   bool ClearEven, unsigned SubReg) const {
2884   const SystemZInstrInfo *TII = TM.getInstrInfo();
2885   MachineFunction &MF = *MBB->getParent();
2886   MachineRegisterInfo &MRI = MF.getRegInfo();
2887   DebugLoc DL = MI->getDebugLoc();
2888
2889   unsigned Dest  = MI->getOperand(0).getReg();
2890   unsigned Src   = MI->getOperand(1).getReg();
2891   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2892
2893   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
2894   if (ClearEven) {
2895     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2896     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
2897
2898     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
2899       .addImm(0);
2900     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
2901       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
2902     In128 = NewIn128;
2903   }
2904   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
2905     .addReg(In128).addReg(Src).addImm(SubReg);
2906
2907   MI->eraseFromParent();
2908   return MBB;
2909 }
2910
2911 MachineBasicBlock *
2912 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
2913                                          MachineBasicBlock *MBB,
2914                                          unsigned Opcode) const {
2915   const SystemZInstrInfo *TII = TM.getInstrInfo();
2916   MachineFunction &MF = *MBB->getParent();
2917   MachineRegisterInfo &MRI = MF.getRegInfo();
2918   DebugLoc DL = MI->getDebugLoc();
2919
2920   MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
2921   uint64_t       DestDisp = MI->getOperand(1).getImm();
2922   MachineOperand SrcBase  = earlyUseOperand(MI->getOperand(2));
2923   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
2924   uint64_t       Length   = MI->getOperand(4).getImm();
2925
2926   // When generating more than one CLC, all but the last will need to
2927   // branch to the end when a difference is found.
2928   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
2929                                splitBlockAfter(MI, MBB) : 0);
2930
2931   // Check for the loop form, in which operand 5 is the trip count.
2932   if (MI->getNumExplicitOperands() > 5) {
2933     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
2934
2935     uint64_t StartCountReg = MI->getOperand(5).getReg();
2936     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
2937     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
2938                               forceReg(MI, DestBase, TII));
2939
2940     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
2941     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
2942     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
2943                             MRI.createVirtualRegister(RC));
2944     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
2945     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
2946                             MRI.createVirtualRegister(RC));
2947
2948     RC = &SystemZ::GR64BitRegClass;
2949     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
2950     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
2951
2952     MachineBasicBlock *StartMBB = MBB;
2953     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
2954     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
2955     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
2956
2957     //  StartMBB:
2958     //   # fall through to LoopMMB
2959     MBB->addSuccessor(LoopMBB);
2960
2961     //  LoopMBB:
2962     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
2963     //                      [ %NextDestReg, NextMBB ]
2964     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
2965     //                     [ %NextSrcReg, NextMBB ]
2966     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
2967     //                       [ %NextCountReg, NextMBB ]
2968     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
2969     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
2970     //   ( JLH EndMBB )
2971     //
2972     // The prefetch is used only for MVC.  The JLH is used only for CLC.
2973     MBB = LoopMBB;
2974
2975     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
2976       .addReg(StartDestReg).addMBB(StartMBB)
2977       .addReg(NextDestReg).addMBB(NextMBB);
2978     if (!HaveSingleBase)
2979       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
2980         .addReg(StartSrcReg).addMBB(StartMBB)
2981         .addReg(NextSrcReg).addMBB(NextMBB);
2982     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
2983       .addReg(StartCountReg).addMBB(StartMBB)
2984       .addReg(NextCountReg).addMBB(NextMBB);
2985     if (Opcode == SystemZ::MVC)
2986       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
2987         .addImm(SystemZ::PFD_WRITE)
2988         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
2989     BuildMI(MBB, DL, TII->get(Opcode))
2990       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
2991       .addReg(ThisSrcReg).addImm(SrcDisp);
2992     if (EndMBB) {
2993       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2994         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
2995         .addMBB(EndMBB);
2996       MBB->addSuccessor(EndMBB);
2997       MBB->addSuccessor(NextMBB);
2998     }
2999
3000     // NextMBB:
3001     //   %NextDestReg = LA 256(%ThisDestReg)
3002     //   %NextSrcReg = LA 256(%ThisSrcReg)
3003     //   %NextCountReg = AGHI %ThisCountReg, -1
3004     //   CGHI %NextCountReg, 0
3005     //   JLH LoopMBB
3006     //   # fall through to DoneMMB
3007     //
3008     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
3009     MBB = NextMBB;
3010
3011     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
3012       .addReg(ThisDestReg).addImm(256).addReg(0);
3013     if (!HaveSingleBase)
3014       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
3015         .addReg(ThisSrcReg).addImm(256).addReg(0);
3016     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
3017       .addReg(ThisCountReg).addImm(-1);
3018     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
3019       .addReg(NextCountReg).addImm(0);
3020     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3021       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
3022       .addMBB(LoopMBB);
3023     MBB->addSuccessor(LoopMBB);
3024     MBB->addSuccessor(DoneMBB);
3025
3026     DestBase = MachineOperand::CreateReg(NextDestReg, false);
3027     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
3028     Length &= 255;
3029     MBB = DoneMBB;
3030   }
3031   // Handle any remaining bytes with straight-line code.
3032   while (Length > 0) {
3033     uint64_t ThisLength = std::min(Length, uint64_t(256));
3034     // The previous iteration might have created out-of-range displacements.
3035     // Apply them using LAY if so.
3036     if (!isUInt<12>(DestDisp)) {
3037       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
3038       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
3039         .addOperand(DestBase).addImm(DestDisp).addReg(0);
3040       DestBase = MachineOperand::CreateReg(Reg, false);
3041       DestDisp = 0;
3042     }
3043     if (!isUInt<12>(SrcDisp)) {
3044       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
3045       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
3046         .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
3047       SrcBase = MachineOperand::CreateReg(Reg, false);
3048       SrcDisp = 0;
3049     }
3050     BuildMI(*MBB, MI, DL, TII->get(Opcode))
3051       .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
3052       .addOperand(SrcBase).addImm(SrcDisp);
3053     DestDisp += ThisLength;
3054     SrcDisp += ThisLength;
3055     Length -= ThisLength;
3056     // If there's another CLC to go, branch to the end if a difference
3057     // was found.
3058     if (EndMBB && Length > 0) {
3059       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
3060       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3061         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
3062         .addMBB(EndMBB);
3063       MBB->addSuccessor(EndMBB);
3064       MBB->addSuccessor(NextMBB);
3065       MBB = NextMBB;
3066     }
3067   }
3068   if (EndMBB) {
3069     MBB->addSuccessor(EndMBB);
3070     MBB = EndMBB;
3071     MBB->addLiveIn(SystemZ::CC);
3072   }
3073
3074   MI->eraseFromParent();
3075   return MBB;
3076 }
3077
3078 // Decompose string pseudo-instruction MI into a loop that continually performs
3079 // Opcode until CC != 3.
3080 MachineBasicBlock *
3081 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
3082                                          MachineBasicBlock *MBB,
3083                                          unsigned Opcode) const {
3084   const SystemZInstrInfo *TII = TM.getInstrInfo();
3085   MachineFunction &MF = *MBB->getParent();
3086   MachineRegisterInfo &MRI = MF.getRegInfo();
3087   DebugLoc DL = MI->getDebugLoc();
3088
3089   uint64_t End1Reg   = MI->getOperand(0).getReg();
3090   uint64_t Start1Reg = MI->getOperand(1).getReg();
3091   uint64_t Start2Reg = MI->getOperand(2).getReg();
3092   uint64_t CharReg   = MI->getOperand(3).getReg();
3093
3094   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
3095   uint64_t This1Reg = MRI.createVirtualRegister(RC);
3096   uint64_t This2Reg = MRI.createVirtualRegister(RC);
3097   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
3098
3099   MachineBasicBlock *StartMBB = MBB;
3100   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
3101   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
3102
3103   //  StartMBB:
3104   //   # fall through to LoopMMB
3105   MBB->addSuccessor(LoopMBB);
3106
3107   //  LoopMBB:
3108   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
3109   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
3110   //   R0L = %CharReg
3111   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
3112   //   JO LoopMBB
3113   //   # fall through to DoneMMB
3114   //
3115   // The load of R0L can be hoisted by post-RA LICM.
3116   MBB = LoopMBB;
3117
3118   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
3119     .addReg(Start1Reg).addMBB(StartMBB)
3120     .addReg(End1Reg).addMBB(LoopMBB);
3121   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
3122     .addReg(Start2Reg).addMBB(StartMBB)
3123     .addReg(End2Reg).addMBB(LoopMBB);
3124   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
3125   BuildMI(MBB, DL, TII->get(Opcode))
3126     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
3127     .addReg(This1Reg).addReg(This2Reg);
3128   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3129     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
3130   MBB->addSuccessor(LoopMBB);
3131   MBB->addSuccessor(DoneMBB);
3132
3133   DoneMBB->addLiveIn(SystemZ::CC);
3134
3135   MI->eraseFromParent();
3136   return DoneMBB;
3137 }
3138
3139 MachineBasicBlock *SystemZTargetLowering::
3140 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
3141   switch (MI->getOpcode()) {
3142   case SystemZ::Select32Mux:
3143   case SystemZ::Select32:
3144   case SystemZ::SelectF32:
3145   case SystemZ::Select64:
3146   case SystemZ::SelectF64:
3147   case SystemZ::SelectF128:
3148     return emitSelect(MI, MBB);
3149
3150   case SystemZ::CondStore8Mux:
3151     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
3152   case SystemZ::CondStore8MuxInv:
3153     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
3154   case SystemZ::CondStore16Mux:
3155     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
3156   case SystemZ::CondStore16MuxInv:
3157     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
3158   case SystemZ::CondStore8:
3159     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
3160   case SystemZ::CondStore8Inv:
3161     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
3162   case SystemZ::CondStore16:
3163     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
3164   case SystemZ::CondStore16Inv:
3165     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
3166   case SystemZ::CondStore32:
3167     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
3168   case SystemZ::CondStore32Inv:
3169     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
3170   case SystemZ::CondStore64:
3171     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
3172   case SystemZ::CondStore64Inv:
3173     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
3174   case SystemZ::CondStoreF32:
3175     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
3176   case SystemZ::CondStoreF32Inv:
3177     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
3178   case SystemZ::CondStoreF64:
3179     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
3180   case SystemZ::CondStoreF64Inv:
3181     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
3182
3183   case SystemZ::AEXT128_64:
3184     return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
3185   case SystemZ::ZEXT128_32:
3186     return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
3187   case SystemZ::ZEXT128_64:
3188     return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
3189
3190   case SystemZ::ATOMIC_SWAPW:
3191     return emitAtomicLoadBinary(MI, MBB, 0, 0);
3192   case SystemZ::ATOMIC_SWAP_32:
3193     return emitAtomicLoadBinary(MI, MBB, 0, 32);
3194   case SystemZ::ATOMIC_SWAP_64:
3195     return emitAtomicLoadBinary(MI, MBB, 0, 64);
3196
3197   case SystemZ::ATOMIC_LOADW_AR:
3198     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
3199   case SystemZ::ATOMIC_LOADW_AFI:
3200     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
3201   case SystemZ::ATOMIC_LOAD_AR:
3202     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
3203   case SystemZ::ATOMIC_LOAD_AHI:
3204     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
3205   case SystemZ::ATOMIC_LOAD_AFI:
3206     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
3207   case SystemZ::ATOMIC_LOAD_AGR:
3208     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
3209   case SystemZ::ATOMIC_LOAD_AGHI:
3210     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
3211   case SystemZ::ATOMIC_LOAD_AGFI:
3212     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
3213
3214   case SystemZ::ATOMIC_LOADW_SR:
3215     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
3216   case SystemZ::ATOMIC_LOAD_SR:
3217     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
3218   case SystemZ::ATOMIC_LOAD_SGR:
3219     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
3220
3221   case SystemZ::ATOMIC_LOADW_NR:
3222     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
3223   case SystemZ::ATOMIC_LOADW_NILH:
3224     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
3225   case SystemZ::ATOMIC_LOAD_NR:
3226     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
3227   case SystemZ::ATOMIC_LOAD_NILL:
3228     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
3229   case SystemZ::ATOMIC_LOAD_NILH:
3230     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
3231   case SystemZ::ATOMIC_LOAD_NILF:
3232     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
3233   case SystemZ::ATOMIC_LOAD_NGR:
3234     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
3235   case SystemZ::ATOMIC_LOAD_NILL64:
3236     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
3237   case SystemZ::ATOMIC_LOAD_NILH64:
3238     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
3239   case SystemZ::ATOMIC_LOAD_NIHL64:
3240     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
3241   case SystemZ::ATOMIC_LOAD_NIHH64:
3242     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
3243   case SystemZ::ATOMIC_LOAD_NILF64:
3244     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
3245   case SystemZ::ATOMIC_LOAD_NIHF64:
3246     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
3247
3248   case SystemZ::ATOMIC_LOADW_OR:
3249     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
3250   case SystemZ::ATOMIC_LOADW_OILH:
3251     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
3252   case SystemZ::ATOMIC_LOAD_OR:
3253     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
3254   case SystemZ::ATOMIC_LOAD_OILL:
3255     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
3256   case SystemZ::ATOMIC_LOAD_OILH:
3257     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
3258   case SystemZ::ATOMIC_LOAD_OILF:
3259     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
3260   case SystemZ::ATOMIC_LOAD_OGR:
3261     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
3262   case SystemZ::ATOMIC_LOAD_OILL64:
3263     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
3264   case SystemZ::ATOMIC_LOAD_OILH64:
3265     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
3266   case SystemZ::ATOMIC_LOAD_OIHL64:
3267     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
3268   case SystemZ::ATOMIC_LOAD_OIHH64:
3269     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
3270   case SystemZ::ATOMIC_LOAD_OILF64:
3271     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
3272   case SystemZ::ATOMIC_LOAD_OIHF64:
3273     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
3274
3275   case SystemZ::ATOMIC_LOADW_XR:
3276     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
3277   case SystemZ::ATOMIC_LOADW_XILF:
3278     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
3279   case SystemZ::ATOMIC_LOAD_XR:
3280     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
3281   case SystemZ::ATOMIC_LOAD_XILF:
3282     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
3283   case SystemZ::ATOMIC_LOAD_XGR:
3284     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
3285   case SystemZ::ATOMIC_LOAD_XILF64:
3286     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
3287   case SystemZ::ATOMIC_LOAD_XIHF64:
3288     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
3289
3290   case SystemZ::ATOMIC_LOADW_NRi:
3291     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
3292   case SystemZ::ATOMIC_LOADW_NILHi:
3293     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
3294   case SystemZ::ATOMIC_LOAD_NRi:
3295     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
3296   case SystemZ::ATOMIC_LOAD_NILLi:
3297     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
3298   case SystemZ::ATOMIC_LOAD_NILHi:
3299     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
3300   case SystemZ::ATOMIC_LOAD_NILFi:
3301     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
3302   case SystemZ::ATOMIC_LOAD_NGRi:
3303     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
3304   case SystemZ::ATOMIC_LOAD_NILL64i:
3305     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
3306   case SystemZ::ATOMIC_LOAD_NILH64i:
3307     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
3308   case SystemZ::ATOMIC_LOAD_NIHL64i:
3309     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
3310   case SystemZ::ATOMIC_LOAD_NIHH64i:
3311     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
3312   case SystemZ::ATOMIC_LOAD_NILF64i:
3313     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
3314   case SystemZ::ATOMIC_LOAD_NIHF64i:
3315     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
3316
3317   case SystemZ::ATOMIC_LOADW_MIN:
3318     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3319                                 SystemZ::CCMASK_CMP_LE, 0);
3320   case SystemZ::ATOMIC_LOAD_MIN_32:
3321     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3322                                 SystemZ::CCMASK_CMP_LE, 32);
3323   case SystemZ::ATOMIC_LOAD_MIN_64:
3324     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
3325                                 SystemZ::CCMASK_CMP_LE, 64);
3326
3327   case SystemZ::ATOMIC_LOADW_MAX:
3328     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3329                                 SystemZ::CCMASK_CMP_GE, 0);
3330   case SystemZ::ATOMIC_LOAD_MAX_32:
3331     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3332                                 SystemZ::CCMASK_CMP_GE, 32);
3333   case SystemZ::ATOMIC_LOAD_MAX_64:
3334     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
3335                                 SystemZ::CCMASK_CMP_GE, 64);
3336
3337   case SystemZ::ATOMIC_LOADW_UMIN:
3338     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3339                                 SystemZ::CCMASK_CMP_LE, 0);
3340   case SystemZ::ATOMIC_LOAD_UMIN_32:
3341     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3342                                 SystemZ::CCMASK_CMP_LE, 32);
3343   case SystemZ::ATOMIC_LOAD_UMIN_64:
3344     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
3345                                 SystemZ::CCMASK_CMP_LE, 64);
3346
3347   case SystemZ::ATOMIC_LOADW_UMAX:
3348     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3349                                 SystemZ::CCMASK_CMP_GE, 0);
3350   case SystemZ::ATOMIC_LOAD_UMAX_32:
3351     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3352                                 SystemZ::CCMASK_CMP_GE, 32);
3353   case SystemZ::ATOMIC_LOAD_UMAX_64:
3354     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
3355                                 SystemZ::CCMASK_CMP_GE, 64);
3356
3357   case SystemZ::ATOMIC_CMP_SWAPW:
3358     return emitAtomicCmpSwapW(MI, MBB);
3359   case SystemZ::MVCSequence:
3360   case SystemZ::MVCLoop:
3361     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
3362   case SystemZ::NCSequence:
3363   case SystemZ::NCLoop:
3364     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
3365   case SystemZ::OCSequence:
3366   case SystemZ::OCLoop:
3367     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
3368   case SystemZ::XCSequence:
3369   case SystemZ::XCLoop:
3370     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
3371   case SystemZ::CLCSequence:
3372   case SystemZ::CLCLoop:
3373     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
3374   case SystemZ::CLSTLoop:
3375     return emitStringWrapper(MI, MBB, SystemZ::CLST);
3376   case SystemZ::MVSTLoop:
3377     return emitStringWrapper(MI, MBB, SystemZ::MVST);
3378   case SystemZ::SRSTLoop:
3379     return emitStringWrapper(MI, MBB, SystemZ::SRST);
3380   default:
3381     llvm_unreachable("Unexpected instr type to insert");
3382   }
3383 }