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