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 "llvm/IR/Intrinsics.h"
24 #include <cctype>
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "systemz-lower"
29 
30 namespace {
31 // Represents a sequence for extracting a 0/1 value from an IPM result:
32 // (((X ^ XORValue) + AddValue) >> Bit)
33 struct IPMConversion {
34   IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
35     : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
36 
37   int64_t XORValue;
38   int64_t AddValue;
39   unsigned Bit;
40 };
41 
42 // Represents information about a comparison.
43 struct Comparison {
44   Comparison(SDValue Op0In, SDValue Op1In)
45     : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
46 
47   // The operands to the comparison.
48   SDValue Op0, Op1;
49 
50   // The opcode that should be used to compare Op0 and Op1.
51   unsigned Opcode;
52 
53   // A SystemZICMP value.  Only used for integer comparisons.
54   unsigned ICmpType;
55 
56   // The mask of CC values that Opcode can produce.
57   unsigned CCValid;
58 
59   // The mask of CC values for which the original condition is true.
60   unsigned CCMask;
61 };
62 } // end anonymous namespace
63 
64 // Classify VT as either 32 or 64 bit.
65 static bool is32Bit(EVT VT) {
66   switch (VT.getSimpleVT().SimpleTy) {
67   case MVT::i32:
68     return true;
69   case MVT::i64:
70     return false;
71   default:
72     llvm_unreachable("Unsupported type");
73   }
74 }
75 
76 // Return a version of MachineOperand that can be safely used before the
77 // final use.
78 static MachineOperand earlyUseOperand(MachineOperand Op) {
79   if (Op.isReg())
80     Op.setIsKill(false);
81   return Op;
82 }
83 
84 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM,
85                                              const SystemZSubtarget &STI)
86     : TargetLowering(TM), Subtarget(STI) {
87   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
88 
89   // Set up the register classes.
90   if (Subtarget.hasHighWord())
91     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
92   else
93     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
94   addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
95   if (Subtarget.hasVector()) {
96     addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
97     addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
98   } else {
99     addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
100     addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
101   }
102   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
103 
104   if (Subtarget.hasVector()) {
105     addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
106     addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
107     addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
108     addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
109     addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
110     addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
111   }
112 
113   // Compute derived properties from the register classes
114   computeRegisterProperties(Subtarget.getRegisterInfo());
115 
116   // Set up special registers.
117   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
118 
119   // TODO: It may be better to default to latency-oriented scheduling, however
120   // LLVM's current latency-oriented scheduler can't handle physreg definitions
121   // such as SystemZ has with CC, so set this to the register-pressure
122   // scheduler, because it can.
123   setSchedulingPreference(Sched::RegPressure);
124 
125   setBooleanContents(ZeroOrOneBooleanContent);
126   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
127 
128   // Instructions are strings of 2-byte aligned 2-byte values.
129   setMinFunctionAlignment(2);
130 
131   // Handle operations that are handled in a similar way for all types.
132   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
133        I <= MVT::LAST_FP_VALUETYPE;
134        ++I) {
135     MVT VT = MVT::SimpleValueType(I);
136     if (isTypeLegal(VT)) {
137       // Lower SET_CC into an IPM-based sequence.
138       setOperationAction(ISD::SETCC, VT, Custom);
139 
140       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
141       setOperationAction(ISD::SELECT, VT, Expand);
142 
143       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
144       setOperationAction(ISD::SELECT_CC, VT, Custom);
145       setOperationAction(ISD::BR_CC,     VT, Custom);
146     }
147   }
148 
149   // Expand jump table branches as address arithmetic followed by an
150   // indirect jump.
151   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
152 
153   // Expand BRCOND into a BR_CC (see above).
154   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
155 
156   // Handle integer types.
157   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
158        I <= MVT::LAST_INTEGER_VALUETYPE;
159        ++I) {
160     MVT VT = MVT::SimpleValueType(I);
161     if (isTypeLegal(VT)) {
162       // Expand individual DIV and REMs into DIVREMs.
163       setOperationAction(ISD::SDIV, VT, Expand);
164       setOperationAction(ISD::UDIV, VT, Expand);
165       setOperationAction(ISD::SREM, VT, Expand);
166       setOperationAction(ISD::UREM, VT, Expand);
167       setOperationAction(ISD::SDIVREM, VT, Custom);
168       setOperationAction(ISD::UDIVREM, VT, Custom);
169 
170       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
171       // stores, putting a serialization instruction after the stores.
172       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
173       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
174 
175       // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
176       // available, or if the operand is constant.
177       setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
178 
179       // Use POPCNT on z196 and above.
180       if (Subtarget.hasPopulationCount())
181         setOperationAction(ISD::CTPOP, VT, Custom);
182       else
183         setOperationAction(ISD::CTPOP, VT, Expand);
184 
185       // No special instructions for these.
186       setOperationAction(ISD::CTTZ,            VT, Expand);
187       setOperationAction(ISD::ROTR,            VT, Expand);
188 
189       // Use *MUL_LOHI where possible instead of MULH*.
190       setOperationAction(ISD::MULHS, VT, Expand);
191       setOperationAction(ISD::MULHU, VT, Expand);
192       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
193       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
194 
195       // Only z196 and above have native support for conversions to unsigned.
196       if (!Subtarget.hasFPExtension())
197         setOperationAction(ISD::FP_TO_UINT, VT, Expand);
198     }
199   }
200 
201   // Type legalization will convert 8- and 16-bit atomic operations into
202   // forms that operate on i32s (but still keeping the original memory VT).
203   // Lower them into full i32 operations.
204   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
205   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
206   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
207   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
208   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
209   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
210   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
211   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
212   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
213   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
214   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
215   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
216 
217   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
218 
219   // z10 has instructions for signed but not unsigned FP conversion.
220   // Handle unsigned 32-bit types as signed 64-bit types.
221   if (!Subtarget.hasFPExtension()) {
222     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
223     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
224   }
225 
226   // We have native support for a 64-bit CTLZ, via FLOGR.
227   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
228   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
229 
230   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
231   setOperationAction(ISD::OR, MVT::i64, Custom);
232 
233   // FIXME: Can we support these natively?
234   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
235   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
236   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
237 
238   // We have native instructions for i8, i16 and i32 extensions, but not i1.
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
240   for (MVT VT : MVT::integer_valuetypes()) {
241     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
242     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
243     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1, Promote);
244   }
245 
246   // Handle the various types of symbolic address.
247   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
248   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
249   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
250   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
251   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
252 
253   // We need to handle dynamic allocations specially because of the
254   // 160-byte area at the bottom of the stack.
255   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
256 
257   // Use custom expanders so that we can force the function to use
258   // a frame pointer.
259   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
260   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
261 
262   // Handle prefetches with PFD or PFDRL.
263   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
264 
265   for (MVT VT : MVT::vector_valuetypes()) {
266     // Assume by default that all vector operations need to be expanded.
267     for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
268       if (getOperationAction(Opcode, VT) == Legal)
269         setOperationAction(Opcode, VT, Expand);
270 
271     // Likewise all truncating stores and extending loads.
272     for (MVT InnerVT : MVT::vector_valuetypes()) {
273       setTruncStoreAction(VT, InnerVT, Expand);
274       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
275       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
276       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
277     }
278 
279     if (isTypeLegal(VT)) {
280       // These operations are legal for anything that can be stored in a
281       // vector register, even if there is no native support for the format
282       // as such.  In particular, we can do these for v4f32 even though there
283       // are no specific instructions for that format.
284       setOperationAction(ISD::LOAD, VT, Legal);
285       setOperationAction(ISD::STORE, VT, Legal);
286       setOperationAction(ISD::VSELECT, VT, Legal);
287       setOperationAction(ISD::BITCAST, VT, Legal);
288       setOperationAction(ISD::UNDEF, VT, Legal);
289 
290       // Likewise, except that we need to replace the nodes with something
291       // more specific.
292       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
293       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
294     }
295   }
296 
297   // Handle integer vector types.
298   for (MVT VT : MVT::integer_vector_valuetypes()) {
299     if (isTypeLegal(VT)) {
300       // These operations have direct equivalents.
301       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
302       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
303       setOperationAction(ISD::ADD, VT, Legal);
304       setOperationAction(ISD::SUB, VT, Legal);
305       if (VT != MVT::v2i64)
306         setOperationAction(ISD::MUL, VT, Legal);
307       setOperationAction(ISD::AND, VT, Legal);
308       setOperationAction(ISD::OR, VT, Legal);
309       setOperationAction(ISD::XOR, VT, Legal);
310       setOperationAction(ISD::CTPOP, VT, Custom);
311       setOperationAction(ISD::CTTZ, VT, Legal);
312       setOperationAction(ISD::CTLZ, VT, Legal);
313 
314       // Convert a GPR scalar to a vector by inserting it into element 0.
315       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
316 
317       // Use a series of unpacks for extensions.
318       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
319       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
320 
321       // Detect shifts by a scalar amount and convert them into
322       // V*_BY_SCALAR.
323       setOperationAction(ISD::SHL, VT, Custom);
324       setOperationAction(ISD::SRA, VT, Custom);
325       setOperationAction(ISD::SRL, VT, Custom);
326 
327       // At present ROTL isn't matched by DAGCombiner.  ROTR should be
328       // converted into ROTL.
329       setOperationAction(ISD::ROTL, VT, Expand);
330       setOperationAction(ISD::ROTR, VT, Expand);
331 
332       // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
333       // and inverting the result as necessary.
334       setOperationAction(ISD::SETCC, VT, Custom);
335     }
336   }
337 
338   if (Subtarget.hasVector()) {
339     // There should be no need to check for float types other than v2f64
340     // since <2 x f32> isn't a legal type.
341     setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
342     setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
343     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
344     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
345   }
346 
347   // Handle floating-point types.
348   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
349        I <= MVT::LAST_FP_VALUETYPE;
350        ++I) {
351     MVT VT = MVT::SimpleValueType(I);
352     if (isTypeLegal(VT)) {
353       // We can use FI for FRINT.
354       setOperationAction(ISD::FRINT, VT, Legal);
355 
356       // We can use the extended form of FI for other rounding operations.
357       if (Subtarget.hasFPExtension()) {
358         setOperationAction(ISD::FNEARBYINT, VT, Legal);
359         setOperationAction(ISD::FFLOOR, VT, Legal);
360         setOperationAction(ISD::FCEIL, VT, Legal);
361         setOperationAction(ISD::FTRUNC, VT, Legal);
362         setOperationAction(ISD::FROUND, VT, Legal);
363       }
364 
365       // No special instructions for these.
366       setOperationAction(ISD::FSIN, VT, Expand);
367       setOperationAction(ISD::FCOS, VT, Expand);
368       setOperationAction(ISD::FSINCOS, VT, Expand);
369       setOperationAction(ISD::FREM, VT, Expand);
370       setOperationAction(ISD::FPOW, VT, Expand);
371     }
372   }
373 
374   // Handle floating-point vector types.
375   if (Subtarget.hasVector()) {
376     // Scalar-to-vector conversion is just a subreg.
377     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
378     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
379 
380     // Some insertions and extractions can be done directly but others
381     // need to go via integers.
382     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
383     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
384     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
385     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
386 
387     // These operations have direct equivalents.
388     setOperationAction(ISD::FADD, MVT::v2f64, Legal);
389     setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
390     setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
391     setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
392     setOperationAction(ISD::FMA, MVT::v2f64, Legal);
393     setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
394     setOperationAction(ISD::FABS, MVT::v2f64, Legal);
395     setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
396     setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
397     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
398     setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
399     setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
400     setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
401     setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
402   }
403 
404   // We have fused multiply-addition for f32 and f64 but not f128.
405   setOperationAction(ISD::FMA, MVT::f32,  Legal);
406   setOperationAction(ISD::FMA, MVT::f64,  Legal);
407   setOperationAction(ISD::FMA, MVT::f128, Expand);
408 
409   // Needed so that we don't try to implement f128 constant loads using
410   // a load-and-extend of a f80 constant (in cases where the constant
411   // would fit in an f80).
412   for (MVT VT : MVT::fp_valuetypes())
413     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
414 
415   // Floating-point truncation and stores need to be done separately.
416   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
417   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
418   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
419 
420   // We have 64-bit FPR<->GPR moves, but need special handling for
421   // 32-bit forms.
422   if (!Subtarget.hasVector()) {
423     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
424     setOperationAction(ISD::BITCAST, MVT::f32, Custom);
425   }
426 
427   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
428   // structure, but VAEND is a no-op.
429   setOperationAction(ISD::VASTART, MVT::Other, Custom);
430   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
431   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
432 
433   // Codes for which we want to perform some z-specific combinations.
434   setTargetDAGCombine(ISD::SIGN_EXTEND);
435   setTargetDAGCombine(ISD::STORE);
436   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
437   setTargetDAGCombine(ISD::FP_ROUND);
438 
439   // Handle intrinsics.
440   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
441   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
442 
443   // We want to use MVC in preference to even a single load/store pair.
444   MaxStoresPerMemcpy = 0;
445   MaxStoresPerMemcpyOptSize = 0;
446 
447   // The main memset sequence is a byte store followed by an MVC.
448   // Two STC or MV..I stores win over that, but the kind of fused stores
449   // generated by target-independent code don't when the byte value is
450   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
451   // than "STC;MVC".  Handle the choice in target-specific code instead.
452   MaxStoresPerMemset = 0;
453   MaxStoresPerMemsetOptSize = 0;
454 }
455 
456 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
457                                               LLVMContext &, EVT VT) const {
458   if (!VT.isVector())
459     return MVT::i32;
460   return VT.changeVectorElementTypeToInteger();
461 }
462 
463 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
464   VT = VT.getScalarType();
465 
466   if (!VT.isSimple())
467     return false;
468 
469   switch (VT.getSimpleVT().SimpleTy) {
470   case MVT::f32:
471   case MVT::f64:
472     return true;
473   case MVT::f128:
474     return false;
475   default:
476     break;
477   }
478 
479   return false;
480 }
481 
482 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
483   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
484   return Imm.isZero() || Imm.isNegZero();
485 }
486 
487 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
488   // We can use CGFI or CLGFI.
489   return isInt<32>(Imm) || isUInt<32>(Imm);
490 }
491 
492 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
493   // We can use ALGFI or SLGFI.
494   return isUInt<32>(Imm) || isUInt<32>(-Imm);
495 }
496 
497 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
498                                                            unsigned,
499                                                            unsigned,
500                                                            bool *Fast) const {
501   // Unaligned accesses should never be slower than the expanded version.
502   // We check specifically for aligned accesses in the few cases where
503   // they are required.
504   if (Fast)
505     *Fast = true;
506   return true;
507 }
508 
509 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
510                                                   const AddrMode &AM, Type *Ty,
511                                                   unsigned AS) const {
512   // Punt on globals for now, although they can be used in limited
513   // RELATIVE LONG cases.
514   if (AM.BaseGV)
515     return false;
516 
517   // Require a 20-bit signed offset.
518   if (!isInt<20>(AM.BaseOffs))
519     return false;
520 
521   // Indexing is OK but no scale factor can be applied.
522   return AM.Scale == 0 || AM.Scale == 1;
523 }
524 
525 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
526   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
527     return false;
528   unsigned FromBits = FromType->getPrimitiveSizeInBits();
529   unsigned ToBits = ToType->getPrimitiveSizeInBits();
530   return FromBits > ToBits;
531 }
532 
533 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
534   if (!FromVT.isInteger() || !ToVT.isInteger())
535     return false;
536   unsigned FromBits = FromVT.getSizeInBits();
537   unsigned ToBits = ToVT.getSizeInBits();
538   return FromBits > ToBits;
539 }
540 
541 //===----------------------------------------------------------------------===//
542 // Inline asm support
543 //===----------------------------------------------------------------------===//
544 
545 TargetLowering::ConstraintType
546 SystemZTargetLowering::getConstraintType(StringRef Constraint) const {
547   if (Constraint.size() == 1) {
548     switch (Constraint[0]) {
549     case 'a': // Address register
550     case 'd': // Data register (equivalent to 'r')
551     case 'f': // Floating-point register
552     case 'h': // High-part register
553     case 'r': // General-purpose register
554       return C_RegisterClass;
555 
556     case 'Q': // Memory with base and unsigned 12-bit displacement
557     case 'R': // Likewise, plus an index
558     case 'S': // Memory with base and signed 20-bit displacement
559     case 'T': // Likewise, plus an index
560     case 'm': // Equivalent to 'T'.
561       return C_Memory;
562 
563     case 'I': // Unsigned 8-bit constant
564     case 'J': // Unsigned 12-bit constant
565     case 'K': // Signed 16-bit constant
566     case 'L': // Signed 20-bit displacement (on all targets we support)
567     case 'M': // 0x7fffffff
568       return C_Other;
569 
570     default:
571       break;
572     }
573   }
574   return TargetLowering::getConstraintType(Constraint);
575 }
576 
577 TargetLowering::ConstraintWeight SystemZTargetLowering::
578 getSingleConstraintMatchWeight(AsmOperandInfo &info,
579                                const char *constraint) const {
580   ConstraintWeight weight = CW_Invalid;
581   Value *CallOperandVal = info.CallOperandVal;
582   // If we don't have a value, we can't do a match,
583   // but allow it at the lowest weight.
584   if (!CallOperandVal)
585     return CW_Default;
586   Type *type = CallOperandVal->getType();
587   // Look at the constraint type.
588   switch (*constraint) {
589   default:
590     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
591     break;
592 
593   case 'a': // Address register
594   case 'd': // Data register (equivalent to 'r')
595   case 'h': // High-part register
596   case 'r': // General-purpose register
597     if (CallOperandVal->getType()->isIntegerTy())
598       weight = CW_Register;
599     break;
600 
601   case 'f': // Floating-point register
602     if (type->isFloatingPointTy())
603       weight = CW_Register;
604     break;
605 
606   case 'I': // Unsigned 8-bit constant
607     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
608       if (isUInt<8>(C->getZExtValue()))
609         weight = CW_Constant;
610     break;
611 
612   case 'J': // Unsigned 12-bit constant
613     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
614       if (isUInt<12>(C->getZExtValue()))
615         weight = CW_Constant;
616     break;
617 
618   case 'K': // Signed 16-bit constant
619     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
620       if (isInt<16>(C->getSExtValue()))
621         weight = CW_Constant;
622     break;
623 
624   case 'L': // Signed 20-bit displacement (on all targets we support)
625     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
626       if (isInt<20>(C->getSExtValue()))
627         weight = CW_Constant;
628     break;
629 
630   case 'M': // 0x7fffffff
631     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
632       if (C->getZExtValue() == 0x7fffffff)
633         weight = CW_Constant;
634     break;
635   }
636   return weight;
637 }
638 
639 // Parse a "{tNNN}" register constraint for which the register type "t"
640 // has already been verified.  MC is the class associated with "t" and
641 // Map maps 0-based register numbers to LLVM register numbers.
642 static std::pair<unsigned, const TargetRegisterClass *>
643 parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC,
644                     const unsigned *Map) {
645   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
646   if (isdigit(Constraint[2])) {
647     unsigned Index;
648     bool Failed =
649         Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
650     if (!Failed && Index < 16 && Map[Index])
651       return std::make_pair(Map[Index], RC);
652   }
653   return std::make_pair(0U, nullptr);
654 }
655 
656 std::pair<unsigned, const TargetRegisterClass *>
657 SystemZTargetLowering::getRegForInlineAsmConstraint(
658     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
659   if (Constraint.size() == 1) {
660     // GCC Constraint Letters
661     switch (Constraint[0]) {
662     default: break;
663     case 'd': // Data register (equivalent to 'r')
664     case 'r': // General-purpose register
665       if (VT == MVT::i64)
666         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
667       else if (VT == MVT::i128)
668         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
669       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
670 
671     case 'a': // Address register
672       if (VT == MVT::i64)
673         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
674       else if (VT == MVT::i128)
675         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
676       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
677 
678     case 'h': // High-part register (an LLVM extension)
679       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
680 
681     case 'f': // Floating-point register
682       if (VT == MVT::f64)
683         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
684       else if (VT == MVT::f128)
685         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
686       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
687     }
688   }
689   if (Constraint.size() > 0 && Constraint[0] == '{') {
690     // We need to override the default register parsing for GPRs and FPRs
691     // because the interpretation depends on VT.  The internal names of
692     // the registers are also different from the external names
693     // (F0D and F0S instead of F0, etc.).
694     if (Constraint[1] == 'r') {
695       if (VT == MVT::i32)
696         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
697                                    SystemZMC::GR32Regs);
698       if (VT == MVT::i128)
699         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
700                                    SystemZMC::GR128Regs);
701       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
702                                  SystemZMC::GR64Regs);
703     }
704     if (Constraint[1] == 'f') {
705       if (VT == MVT::f32)
706         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
707                                    SystemZMC::FP32Regs);
708       if (VT == MVT::f128)
709         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
710                                    SystemZMC::FP128Regs);
711       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
712                                  SystemZMC::FP64Regs);
713     }
714   }
715   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
716 }
717 
718 void SystemZTargetLowering::
719 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
720                              std::vector<SDValue> &Ops,
721                              SelectionDAG &DAG) const {
722   // Only support length 1 constraints for now.
723   if (Constraint.length() == 1) {
724     switch (Constraint[0]) {
725     case 'I': // Unsigned 8-bit constant
726       if (auto *C = dyn_cast<ConstantSDNode>(Op))
727         if (isUInt<8>(C->getZExtValue()))
728           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
729                                               Op.getValueType()));
730       return;
731 
732     case 'J': // Unsigned 12-bit constant
733       if (auto *C = dyn_cast<ConstantSDNode>(Op))
734         if (isUInt<12>(C->getZExtValue()))
735           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
736                                               Op.getValueType()));
737       return;
738 
739     case 'K': // Signed 16-bit constant
740       if (auto *C = dyn_cast<ConstantSDNode>(Op))
741         if (isInt<16>(C->getSExtValue()))
742           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
743                                               Op.getValueType()));
744       return;
745 
746     case 'L': // Signed 20-bit displacement (on all targets we support)
747       if (auto *C = dyn_cast<ConstantSDNode>(Op))
748         if (isInt<20>(C->getSExtValue()))
749           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
750                                               Op.getValueType()));
751       return;
752 
753     case 'M': // 0x7fffffff
754       if (auto *C = dyn_cast<ConstantSDNode>(Op))
755         if (C->getZExtValue() == 0x7fffffff)
756           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
757                                               Op.getValueType()));
758       return;
759     }
760   }
761   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
762 }
763 
764 //===----------------------------------------------------------------------===//
765 // Calling conventions
766 //===----------------------------------------------------------------------===//
767 
768 #include "SystemZGenCallingConv.inc"
769 
770 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
771                                                      Type *ToType) const {
772   return isTruncateFree(FromType, ToType);
773 }
774 
775 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
776   return CI->isTailCall();
777 }
778 
779 // We do not yet support 128-bit single-element vector types.  If the user
780 // attempts to use such types as function argument or return type, prefer
781 // to error out instead of emitting code violating the ABI.
782 static void VerifyVectorType(MVT VT, EVT ArgVT) {
783   if (ArgVT.isVector() && !VT.isVector())
784     report_fatal_error("Unsupported vector argument or return type");
785 }
786 
787 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
788   for (unsigned i = 0; i < Ins.size(); ++i)
789     VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
790 }
791 
792 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
793   for (unsigned i = 0; i < Outs.size(); ++i)
794     VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
795 }
796 
797 // Value is a value that has been passed to us in the location described by VA
798 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
799 // any loads onto Chain.
800 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
801                                    CCValAssign &VA, SDValue Chain,
802                                    SDValue Value) {
803   // If the argument has been promoted from a smaller type, insert an
804   // assertion to capture this.
805   if (VA.getLocInfo() == CCValAssign::SExt)
806     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
807                         DAG.getValueType(VA.getValVT()));
808   else if (VA.getLocInfo() == CCValAssign::ZExt)
809     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
810                         DAG.getValueType(VA.getValVT()));
811 
812   if (VA.isExtInLoc())
813     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
814   else if (VA.getLocInfo() == CCValAssign::BCvt) {
815     // If this is a short vector argument loaded from the stack,
816     // extend from i64 to full vector size and then bitcast.
817     assert(VA.getLocVT() == MVT::i64);
818     assert(VA.getValVT().isVector());
819     Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
820     Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
821   } else
822     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
823   return Value;
824 }
825 
826 // Value is a value of type VA.getValVT() that we need to copy into
827 // the location described by VA.  Return a copy of Value converted to
828 // VA.getValVT().  The caller is responsible for handling indirect values.
829 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
830                                    CCValAssign &VA, SDValue Value) {
831   switch (VA.getLocInfo()) {
832   case CCValAssign::SExt:
833     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
834   case CCValAssign::ZExt:
835     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
836   case CCValAssign::AExt:
837     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
838   case CCValAssign::BCvt:
839     // If this is a short vector argument to be stored to the stack,
840     // bitcast to v2i64 and then extract first element.
841     assert(VA.getLocVT() == MVT::i64);
842     assert(VA.getValVT().isVector());
843     Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
844     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
845                        DAG.getConstant(0, DL, MVT::i32));
846   case CCValAssign::Full:
847     return Value;
848   default:
849     llvm_unreachable("Unhandled getLocInfo()");
850   }
851 }
852 
853 SDValue SystemZTargetLowering::
854 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
855                      const SmallVectorImpl<ISD::InputArg> &Ins,
856                      SDLoc DL, SelectionDAG &DAG,
857                      SmallVectorImpl<SDValue> &InVals) const {
858   MachineFunction &MF = DAG.getMachineFunction();
859   MachineFrameInfo *MFI = MF.getFrameInfo();
860   MachineRegisterInfo &MRI = MF.getRegInfo();
861   SystemZMachineFunctionInfo *FuncInfo =
862       MF.getInfo<SystemZMachineFunctionInfo>();
863   auto *TFL =
864       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
865   EVT PtrVT = getPointerTy(DAG.getDataLayout());
866 
867   // Detect unsupported vector argument types.
868   if (Subtarget.hasVector())
869     VerifyVectorTypes(Ins);
870 
871   // Assign locations to all of the incoming arguments.
872   SmallVector<CCValAssign, 16> ArgLocs;
873   SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
874   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
875 
876   unsigned NumFixedGPRs = 0;
877   unsigned NumFixedFPRs = 0;
878   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
879     SDValue ArgValue;
880     CCValAssign &VA = ArgLocs[I];
881     EVT LocVT = VA.getLocVT();
882     if (VA.isRegLoc()) {
883       // Arguments passed in registers
884       const TargetRegisterClass *RC;
885       switch (LocVT.getSimpleVT().SimpleTy) {
886       default:
887         // Integers smaller than i64 should be promoted to i64.
888         llvm_unreachable("Unexpected argument type");
889       case MVT::i32:
890         NumFixedGPRs += 1;
891         RC = &SystemZ::GR32BitRegClass;
892         break;
893       case MVT::i64:
894         NumFixedGPRs += 1;
895         RC = &SystemZ::GR64BitRegClass;
896         break;
897       case MVT::f32:
898         NumFixedFPRs += 1;
899         RC = &SystemZ::FP32BitRegClass;
900         break;
901       case MVT::f64:
902         NumFixedFPRs += 1;
903         RC = &SystemZ::FP64BitRegClass;
904         break;
905       case MVT::v16i8:
906       case MVT::v8i16:
907       case MVT::v4i32:
908       case MVT::v2i64:
909       case MVT::v4f32:
910       case MVT::v2f64:
911         RC = &SystemZ::VR128BitRegClass;
912         break;
913       }
914 
915       unsigned VReg = MRI.createVirtualRegister(RC);
916       MRI.addLiveIn(VA.getLocReg(), VReg);
917       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
918     } else {
919       assert(VA.isMemLoc() && "Argument not register or memory");
920 
921       // Create the frame index object for this incoming parameter.
922       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
923                                       VA.getLocMemOffset(), true);
924 
925       // Create the SelectionDAG nodes corresponding to a load
926       // from this parameter.  Unpromoted ints and floats are
927       // passed as right-justified 8-byte values.
928       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
929       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
930         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
931                           DAG.getIntPtrConstant(4, DL));
932       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
933                              MachinePointerInfo::getFixedStack(MF, FI), false,
934                              false, false, 0);
935     }
936 
937     // Convert the value of the argument register into the value that's
938     // being passed.
939     if (VA.getLocInfo() == CCValAssign::Indirect) {
940       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain,
941                                    ArgValue, MachinePointerInfo(),
942                                    false, false, false, 0));
943       // If the original argument was split (e.g. i128), we need
944       // to load all parts of it here (using the same address).
945       unsigned ArgIndex = Ins[I].OrigArgIndex;
946       assert (Ins[I].PartOffset == 0);
947       while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
948         CCValAssign &PartVA = ArgLocs[I + 1];
949         unsigned PartOffset = Ins[I + 1].PartOffset;
950         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
951                                       DAG.getIntPtrConstant(PartOffset, DL));
952         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain,
953                                      Address, MachinePointerInfo(),
954                                      false, false, false, 0));
955         ++I;
956       }
957     } else
958       InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
959   }
960 
961   if (IsVarArg) {
962     // Save the number of non-varargs registers for later use by va_start, etc.
963     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
964     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
965 
966     // Likewise the address (in the form of a frame index) of where the
967     // first stack vararg would be.  The 1-byte size here is arbitrary.
968     int64_t StackSize = CCInfo.getNextStackOffset();
969     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
970 
971     // ...and a similar frame index for the caller-allocated save area
972     // that will be used to store the incoming registers.
973     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
974     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
975     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
976 
977     // Store the FPR varargs in the reserved frame slots.  (We store the
978     // GPRs as part of the prologue.)
979     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
980       SDValue MemOps[SystemZ::NumArgFPRs];
981       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
982         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
983         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
984         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
985         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
986                                      &SystemZ::FP64BitRegClass);
987         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
988         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
989                                  MachinePointerInfo::getFixedStack(MF, FI),
990                                  false, false, 0);
991       }
992       // Join the stores, which are independent of one another.
993       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
994                           makeArrayRef(&MemOps[NumFixedFPRs],
995                                        SystemZ::NumArgFPRs-NumFixedFPRs));
996     }
997   }
998 
999   return Chain;
1000 }
1001 
1002 static bool canUseSiblingCall(const CCState &ArgCCInfo,
1003                               SmallVectorImpl<CCValAssign> &ArgLocs,
1004                               SmallVectorImpl<ISD::OutputArg> &Outs) {
1005   // Punt if there are any indirect or stack arguments, or if the call
1006   // needs the callee-saved argument register R6, or if the call uses
1007   // the callee-saved register arguments SwiftSelf and SwiftError.
1008   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1009     CCValAssign &VA = ArgLocs[I];
1010     if (VA.getLocInfo() == CCValAssign::Indirect)
1011       return false;
1012     if (!VA.isRegLoc())
1013       return false;
1014     unsigned Reg = VA.getLocReg();
1015     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1016       return false;
1017     if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1018       return false;
1019   }
1020   return true;
1021 }
1022 
1023 SDValue
1024 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1025                                  SmallVectorImpl<SDValue> &InVals) const {
1026   SelectionDAG &DAG = CLI.DAG;
1027   SDLoc &DL = CLI.DL;
1028   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1029   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1030   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1031   SDValue Chain = CLI.Chain;
1032   SDValue Callee = CLI.Callee;
1033   bool &IsTailCall = CLI.IsTailCall;
1034   CallingConv::ID CallConv = CLI.CallConv;
1035   bool IsVarArg = CLI.IsVarArg;
1036   MachineFunction &MF = DAG.getMachineFunction();
1037   EVT PtrVT = getPointerTy(MF.getDataLayout());
1038 
1039   // Detect unsupported vector argument and return types.
1040   if (Subtarget.hasVector()) {
1041     VerifyVectorTypes(Outs);
1042     VerifyVectorTypes(Ins);
1043   }
1044 
1045   // Analyze the operands of the call, assigning locations to each operand.
1046   SmallVector<CCValAssign, 16> ArgLocs;
1047   SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1048   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1049 
1050   // We don't support GuaranteedTailCallOpt, only automatically-detected
1051   // sibling calls.
1052   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1053     IsTailCall = false;
1054 
1055   // Get a count of how many bytes are to be pushed on the stack.
1056   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1057 
1058   // Mark the start of the call.
1059   if (!IsTailCall)
1060     Chain = DAG.getCALLSEQ_START(Chain,
1061                                  DAG.getConstant(NumBytes, DL, PtrVT, true),
1062                                  DL);
1063 
1064   // Copy argument values to their designated locations.
1065   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1066   SmallVector<SDValue, 8> MemOpChains;
1067   SDValue StackPtr;
1068   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1069     CCValAssign &VA = ArgLocs[I];
1070     SDValue ArgValue = OutVals[I];
1071 
1072     if (VA.getLocInfo() == CCValAssign::Indirect) {
1073       // Store the argument in a stack slot and pass its address.
1074       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1075       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1076       MemOpChains.push_back(DAG.getStore(
1077           Chain, DL, ArgValue, SpillSlot,
1078           MachinePointerInfo::getFixedStack(MF, FI), false, false, 0));
1079       // If the original argument was split (e.g. i128), we need
1080       // to store all parts of it here (and pass just one address).
1081       unsigned ArgIndex = Outs[I].OrigArgIndex;
1082       assert (Outs[I].PartOffset == 0);
1083       while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1084         SDValue PartValue = OutVals[I + 1];
1085         unsigned PartOffset = Outs[I + 1].PartOffset;
1086         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1087                                       DAG.getIntPtrConstant(PartOffset, DL));
1088         MemOpChains.push_back(DAG.getStore(
1089             Chain, DL, PartValue, Address,
1090             MachinePointerInfo::getFixedStack(MF, FI), false, false, 0));
1091         ++I;
1092       }
1093       ArgValue = SpillSlot;
1094     } else
1095       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1096 
1097     if (VA.isRegLoc())
1098       // Queue up the argument copies and emit them at the end.
1099       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1100     else {
1101       assert(VA.isMemLoc() && "Argument not register or memory");
1102 
1103       // Work out the address of the stack slot.  Unpromoted ints and
1104       // floats are passed as right-justified 8-byte values.
1105       if (!StackPtr.getNode())
1106         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1107       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1108       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1109         Offset += 4;
1110       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1111                                     DAG.getIntPtrConstant(Offset, DL));
1112 
1113       // Emit the store.
1114       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
1115                                          MachinePointerInfo(),
1116                                          false, false, 0));
1117     }
1118   }
1119 
1120   // Join the stores, which are independent of one another.
1121   if (!MemOpChains.empty())
1122     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1123 
1124   // Accept direct calls by converting symbolic call addresses to the
1125   // associated Target* opcodes.  Force %r1 to be used for indirect
1126   // tail calls.
1127   SDValue Glue;
1128   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1129     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1130     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1131   } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1132     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1133     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1134   } else if (IsTailCall) {
1135     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1136     Glue = Chain.getValue(1);
1137     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1138   }
1139 
1140   // Build a sequence of copy-to-reg nodes, chained and glued together.
1141   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1142     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1143                              RegsToPass[I].second, Glue);
1144     Glue = Chain.getValue(1);
1145   }
1146 
1147   // The first call operand is the chain and the second is the target address.
1148   SmallVector<SDValue, 8> Ops;
1149   Ops.push_back(Chain);
1150   Ops.push_back(Callee);
1151 
1152   // Add argument registers to the end of the list so that they are
1153   // known live into the call.
1154   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1155     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1156                                   RegsToPass[I].second.getValueType()));
1157 
1158   // Add a register mask operand representing the call-preserved registers.
1159   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1160   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1161   assert(Mask && "Missing call preserved mask for calling convention");
1162   Ops.push_back(DAG.getRegisterMask(Mask));
1163 
1164   // Glue the call to the argument copies, if any.
1165   if (Glue.getNode())
1166     Ops.push_back(Glue);
1167 
1168   // Emit the call.
1169   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1170   if (IsTailCall)
1171     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1172   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1173   Glue = Chain.getValue(1);
1174 
1175   // Mark the end of the call, which is glued to the call itself.
1176   Chain = DAG.getCALLSEQ_END(Chain,
1177                              DAG.getConstant(NumBytes, DL, PtrVT, true),
1178                              DAG.getConstant(0, DL, PtrVT, true),
1179                              Glue, DL);
1180   Glue = Chain.getValue(1);
1181 
1182   // Assign locations to each value returned by this call.
1183   SmallVector<CCValAssign, 16> RetLocs;
1184   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1185   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1186 
1187   // Copy all of the result registers out of their specified physreg.
1188   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1189     CCValAssign &VA = RetLocs[I];
1190 
1191     // Copy the value out, gluing the copy to the end of the call sequence.
1192     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1193                                           VA.getLocVT(), Glue);
1194     Chain = RetValue.getValue(1);
1195     Glue = RetValue.getValue(2);
1196 
1197     // Convert the value of the return register into the value that's
1198     // being returned.
1199     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1200   }
1201 
1202   return Chain;
1203 }
1204 
1205 bool SystemZTargetLowering::
1206 CanLowerReturn(CallingConv::ID CallConv,
1207                MachineFunction &MF, bool isVarArg,
1208                const SmallVectorImpl<ISD::OutputArg> &Outs,
1209                LLVMContext &Context) const {
1210   // Detect unsupported vector return types.
1211   if (Subtarget.hasVector())
1212     VerifyVectorTypes(Outs);
1213 
1214   // Special case that we cannot easily detect in RetCC_SystemZ since
1215   // i128 is not a legal type.
1216   for (auto &Out : Outs)
1217     if (Out.ArgVT == MVT::i128)
1218       return false;
1219 
1220   SmallVector<CCValAssign, 16> RetLocs;
1221   CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1222   return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1223 }
1224 
1225 SDValue
1226 SystemZTargetLowering::LowerReturn(SDValue Chain,
1227                                    CallingConv::ID CallConv, bool IsVarArg,
1228                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1229                                    const SmallVectorImpl<SDValue> &OutVals,
1230                                    SDLoc DL, SelectionDAG &DAG) const {
1231   MachineFunction &MF = DAG.getMachineFunction();
1232 
1233   // Detect unsupported vector return types.
1234   if (Subtarget.hasVector())
1235     VerifyVectorTypes(Outs);
1236 
1237   // Assign locations to each returned value.
1238   SmallVector<CCValAssign, 16> RetLocs;
1239   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1240   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1241 
1242   // Quick exit for void returns
1243   if (RetLocs.empty())
1244     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1245 
1246   // Copy the result values into the output registers.
1247   SDValue Glue;
1248   SmallVector<SDValue, 4> RetOps;
1249   RetOps.push_back(Chain);
1250   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1251     CCValAssign &VA = RetLocs[I];
1252     SDValue RetValue = OutVals[I];
1253 
1254     // Make the return register live on exit.
1255     assert(VA.isRegLoc() && "Can only return in registers!");
1256 
1257     // Promote the value as required.
1258     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1259 
1260     // Chain and glue the copies together.
1261     unsigned Reg = VA.getLocReg();
1262     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1263     Glue = Chain.getValue(1);
1264     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1265   }
1266 
1267   // Update chain and glue.
1268   RetOps[0] = Chain;
1269   if (Glue.getNode())
1270     RetOps.push_back(Glue);
1271 
1272   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1273 }
1274 
1275 SDValue SystemZTargetLowering::
1276 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
1277   return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1278 }
1279 
1280 // Return true if Op is an intrinsic node with chain that returns the CC value
1281 // as its only (other) argument.  Provide the associated SystemZISD opcode and
1282 // the mask of valid CC values if so.
1283 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1284                                       unsigned &CCValid) {
1285   unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1286   switch (Id) {
1287   case Intrinsic::s390_tbegin:
1288     Opcode = SystemZISD::TBEGIN;
1289     CCValid = SystemZ::CCMASK_TBEGIN;
1290     return true;
1291 
1292   case Intrinsic::s390_tbegin_nofloat:
1293     Opcode = SystemZISD::TBEGIN_NOFLOAT;
1294     CCValid = SystemZ::CCMASK_TBEGIN;
1295     return true;
1296 
1297   case Intrinsic::s390_tend:
1298     Opcode = SystemZISD::TEND;
1299     CCValid = SystemZ::CCMASK_TEND;
1300     return true;
1301 
1302   default:
1303     return false;
1304   }
1305 }
1306 
1307 // Return true if Op is an intrinsic node without chain that returns the
1308 // CC value as its final argument.  Provide the associated SystemZISD
1309 // opcode and the mask of valid CC values if so.
1310 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1311   unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1312   switch (Id) {
1313   case Intrinsic::s390_vpkshs:
1314   case Intrinsic::s390_vpksfs:
1315   case Intrinsic::s390_vpksgs:
1316     Opcode = SystemZISD::PACKS_CC;
1317     CCValid = SystemZ::CCMASK_VCMP;
1318     return true;
1319 
1320   case Intrinsic::s390_vpklshs:
1321   case Intrinsic::s390_vpklsfs:
1322   case Intrinsic::s390_vpklsgs:
1323     Opcode = SystemZISD::PACKLS_CC;
1324     CCValid = SystemZ::CCMASK_VCMP;
1325     return true;
1326 
1327   case Intrinsic::s390_vceqbs:
1328   case Intrinsic::s390_vceqhs:
1329   case Intrinsic::s390_vceqfs:
1330   case Intrinsic::s390_vceqgs:
1331     Opcode = SystemZISD::VICMPES;
1332     CCValid = SystemZ::CCMASK_VCMP;
1333     return true;
1334 
1335   case Intrinsic::s390_vchbs:
1336   case Intrinsic::s390_vchhs:
1337   case Intrinsic::s390_vchfs:
1338   case Intrinsic::s390_vchgs:
1339     Opcode = SystemZISD::VICMPHS;
1340     CCValid = SystemZ::CCMASK_VCMP;
1341     return true;
1342 
1343   case Intrinsic::s390_vchlbs:
1344   case Intrinsic::s390_vchlhs:
1345   case Intrinsic::s390_vchlfs:
1346   case Intrinsic::s390_vchlgs:
1347     Opcode = SystemZISD::VICMPHLS;
1348     CCValid = SystemZ::CCMASK_VCMP;
1349     return true;
1350 
1351   case Intrinsic::s390_vtm:
1352     Opcode = SystemZISD::VTM;
1353     CCValid = SystemZ::CCMASK_VCMP;
1354     return true;
1355 
1356   case Intrinsic::s390_vfaebs:
1357   case Intrinsic::s390_vfaehs:
1358   case Intrinsic::s390_vfaefs:
1359     Opcode = SystemZISD::VFAE_CC;
1360     CCValid = SystemZ::CCMASK_ANY;
1361     return true;
1362 
1363   case Intrinsic::s390_vfaezbs:
1364   case Intrinsic::s390_vfaezhs:
1365   case Intrinsic::s390_vfaezfs:
1366     Opcode = SystemZISD::VFAEZ_CC;
1367     CCValid = SystemZ::CCMASK_ANY;
1368     return true;
1369 
1370   case Intrinsic::s390_vfeebs:
1371   case Intrinsic::s390_vfeehs:
1372   case Intrinsic::s390_vfeefs:
1373     Opcode = SystemZISD::VFEE_CC;
1374     CCValid = SystemZ::CCMASK_ANY;
1375     return true;
1376 
1377   case Intrinsic::s390_vfeezbs:
1378   case Intrinsic::s390_vfeezhs:
1379   case Intrinsic::s390_vfeezfs:
1380     Opcode = SystemZISD::VFEEZ_CC;
1381     CCValid = SystemZ::CCMASK_ANY;
1382     return true;
1383 
1384   case Intrinsic::s390_vfenebs:
1385   case Intrinsic::s390_vfenehs:
1386   case Intrinsic::s390_vfenefs:
1387     Opcode = SystemZISD::VFENE_CC;
1388     CCValid = SystemZ::CCMASK_ANY;
1389     return true;
1390 
1391   case Intrinsic::s390_vfenezbs:
1392   case Intrinsic::s390_vfenezhs:
1393   case Intrinsic::s390_vfenezfs:
1394     Opcode = SystemZISD::VFENEZ_CC;
1395     CCValid = SystemZ::CCMASK_ANY;
1396     return true;
1397 
1398   case Intrinsic::s390_vistrbs:
1399   case Intrinsic::s390_vistrhs:
1400   case Intrinsic::s390_vistrfs:
1401     Opcode = SystemZISD::VISTR_CC;
1402     CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
1403     return true;
1404 
1405   case Intrinsic::s390_vstrcbs:
1406   case Intrinsic::s390_vstrchs:
1407   case Intrinsic::s390_vstrcfs:
1408     Opcode = SystemZISD::VSTRC_CC;
1409     CCValid = SystemZ::CCMASK_ANY;
1410     return true;
1411 
1412   case Intrinsic::s390_vstrczbs:
1413   case Intrinsic::s390_vstrczhs:
1414   case Intrinsic::s390_vstrczfs:
1415     Opcode = SystemZISD::VSTRCZ_CC;
1416     CCValid = SystemZ::CCMASK_ANY;
1417     return true;
1418 
1419   case Intrinsic::s390_vfcedbs:
1420     Opcode = SystemZISD::VFCMPES;
1421     CCValid = SystemZ::CCMASK_VCMP;
1422     return true;
1423 
1424   case Intrinsic::s390_vfchdbs:
1425     Opcode = SystemZISD::VFCMPHS;
1426     CCValid = SystemZ::CCMASK_VCMP;
1427     return true;
1428 
1429   case Intrinsic::s390_vfchedbs:
1430     Opcode = SystemZISD::VFCMPHES;
1431     CCValid = SystemZ::CCMASK_VCMP;
1432     return true;
1433 
1434   case Intrinsic::s390_vftcidb:
1435     Opcode = SystemZISD::VFTCI;
1436     CCValid = SystemZ::CCMASK_VCMP;
1437     return true;
1438 
1439   default:
1440     return false;
1441   }
1442 }
1443 
1444 // Emit an intrinsic with chain with a glued value instead of its CC result.
1445 static SDValue emitIntrinsicWithChainAndGlue(SelectionDAG &DAG, SDValue Op,
1446                                              unsigned Opcode) {
1447   // Copy all operands except the intrinsic ID.
1448   unsigned NumOps = Op.getNumOperands();
1449   SmallVector<SDValue, 6> Ops;
1450   Ops.reserve(NumOps - 1);
1451   Ops.push_back(Op.getOperand(0));
1452   for (unsigned I = 2; I < NumOps; ++I)
1453     Ops.push_back(Op.getOperand(I));
1454 
1455   assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1456   SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1457   SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1458   SDValue OldChain = SDValue(Op.getNode(), 1);
1459   SDValue NewChain = SDValue(Intr.getNode(), 0);
1460   DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1461   return Intr;
1462 }
1463 
1464 // Emit an intrinsic with a glued value instead of its CC result.
1465 static SDValue emitIntrinsicWithGlue(SelectionDAG &DAG, SDValue Op,
1466                                      unsigned Opcode) {
1467   // Copy all operands except the intrinsic ID.
1468   unsigned NumOps = Op.getNumOperands();
1469   SmallVector<SDValue, 6> Ops;
1470   Ops.reserve(NumOps - 1);
1471   for (unsigned I = 1; I < NumOps; ++I)
1472     Ops.push_back(Op.getOperand(I));
1473 
1474   if (Op->getNumValues() == 1)
1475     return DAG.getNode(Opcode, SDLoc(Op), MVT::Glue, Ops);
1476   assert(Op->getNumValues() == 2 && "Expected exactly one non-CC result");
1477   SDVTList RawVTs = DAG.getVTList(Op->getValueType(0), MVT::Glue);
1478   return DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1479 }
1480 
1481 // CC is a comparison that will be implemented using an integer or
1482 // floating-point comparison.  Return the condition code mask for
1483 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
1484 // unsigned comparisons and clear for signed ones.  In the floating-point
1485 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1486 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1487 #define CONV(X) \
1488   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1489   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1490   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1491 
1492   switch (CC) {
1493   default:
1494     llvm_unreachable("Invalid integer condition!");
1495 
1496   CONV(EQ);
1497   CONV(NE);
1498   CONV(GT);
1499   CONV(GE);
1500   CONV(LT);
1501   CONV(LE);
1502 
1503   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
1504   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1505   }
1506 #undef CONV
1507 }
1508 
1509 // Return a sequence for getting a 1 from an IPM result when CC has a
1510 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1511 // The handling of CC values outside CCValid doesn't matter.
1512 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1513   // Deal with cases where the result can be taken directly from a bit
1514   // of the IPM result.
1515   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1516     return IPMConversion(0, 0, SystemZ::IPM_CC);
1517   if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1518     return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1519 
1520   // Deal with cases where we can add a value to force the sign bit
1521   // to contain the right value.  Putting the bit in 31 means we can
1522   // use SRL rather than RISBG(L), and also makes it easier to get a
1523   // 0/-1 value, so it has priority over the other tests below.
1524   //
1525   // These sequences rely on the fact that the upper two bits of the
1526   // IPM result are zero.
1527   uint64_t TopBit = uint64_t(1) << 31;
1528   if (CCMask == (CCValid & SystemZ::CCMASK_0))
1529     return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1530   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1531     return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1532   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1533                             | SystemZ::CCMASK_1
1534                             | SystemZ::CCMASK_2)))
1535     return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1536   if (CCMask == (CCValid & SystemZ::CCMASK_3))
1537     return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1538   if (CCMask == (CCValid & (SystemZ::CCMASK_1
1539                             | SystemZ::CCMASK_2
1540                             | SystemZ::CCMASK_3)))
1541     return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1542 
1543   // Next try inverting the value and testing a bit.  0/1 could be
1544   // handled this way too, but we dealt with that case above.
1545   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1546     return IPMConversion(-1, 0, SystemZ::IPM_CC);
1547 
1548   // Handle cases where adding a value forces a non-sign bit to contain
1549   // the right value.
1550   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1551     return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1552   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1553     return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1554 
1555   // The remaining cases are 1, 2, 0/1/3 and 0/2/3.  All these are
1556   // can be done by inverting the low CC bit and applying one of the
1557   // sign-based extractions above.
1558   if (CCMask == (CCValid & SystemZ::CCMASK_1))
1559     return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1560   if (CCMask == (CCValid & SystemZ::CCMASK_2))
1561     return IPMConversion(1 << SystemZ::IPM_CC,
1562                          TopBit - (3 << SystemZ::IPM_CC), 31);
1563   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1564                             | SystemZ::CCMASK_1
1565                             | SystemZ::CCMASK_3)))
1566     return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1567   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1568                             | SystemZ::CCMASK_2
1569                             | SystemZ::CCMASK_3)))
1570     return IPMConversion(1 << SystemZ::IPM_CC,
1571                          TopBit - (1 << SystemZ::IPM_CC), 31);
1572 
1573   llvm_unreachable("Unexpected CC combination");
1574 }
1575 
1576 // If C can be converted to a comparison against zero, adjust the operands
1577 // as necessary.
1578 static void adjustZeroCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1579   if (C.ICmpType == SystemZICMP::UnsignedOnly)
1580     return;
1581 
1582   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1583   if (!ConstOp1)
1584     return;
1585 
1586   int64_t Value = ConstOp1->getSExtValue();
1587   if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1588       (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1589       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1590       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1591     C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1592     C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1593   }
1594 }
1595 
1596 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1597 // adjust the operands as necessary.
1598 static void adjustSubwordCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1599   // For us to make any changes, it must a comparison between a single-use
1600   // load and a constant.
1601   if (!C.Op0.hasOneUse() ||
1602       C.Op0.getOpcode() != ISD::LOAD ||
1603       C.Op1.getOpcode() != ISD::Constant)
1604     return;
1605 
1606   // We must have an 8- or 16-bit load.
1607   auto *Load = cast<LoadSDNode>(C.Op0);
1608   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1609   if (NumBits != 8 && NumBits != 16)
1610     return;
1611 
1612   // The load must be an extending one and the constant must be within the
1613   // range of the unextended value.
1614   auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1615   uint64_t Value = ConstOp1->getZExtValue();
1616   uint64_t Mask = (1 << NumBits) - 1;
1617   if (Load->getExtensionType() == ISD::SEXTLOAD) {
1618     // Make sure that ConstOp1 is in range of C.Op0.
1619     int64_t SignedValue = ConstOp1->getSExtValue();
1620     if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1621       return;
1622     if (C.ICmpType != SystemZICMP::SignedOnly) {
1623       // Unsigned comparison between two sign-extended values is equivalent
1624       // to unsigned comparison between two zero-extended values.
1625       Value &= Mask;
1626     } else if (NumBits == 8) {
1627       // Try to treat the comparison as unsigned, so that we can use CLI.
1628       // Adjust CCMask and Value as necessary.
1629       if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1630         // Test whether the high bit of the byte is set.
1631         Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1632       else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1633         // Test whether the high bit of the byte is clear.
1634         Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1635       else
1636         // No instruction exists for this combination.
1637         return;
1638       C.ICmpType = SystemZICMP::UnsignedOnly;
1639     }
1640   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1641     if (Value > Mask)
1642       return;
1643     // If the constant is in range, we can use any comparison.
1644     C.ICmpType = SystemZICMP::Any;
1645   } else
1646     return;
1647 
1648   // Make sure that the first operand is an i32 of the right extension type.
1649   ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1650                               ISD::SEXTLOAD :
1651                               ISD::ZEXTLOAD);
1652   if (C.Op0.getValueType() != MVT::i32 ||
1653       Load->getExtensionType() != ExtType)
1654     C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1655                            Load->getChain(), Load->getBasePtr(),
1656                            Load->getPointerInfo(), Load->getMemoryVT(),
1657                            Load->isVolatile(), Load->isNonTemporal(),
1658                            Load->isInvariant(), Load->getAlignment());
1659 
1660   // Make sure that the second operand is an i32 with the right value.
1661   if (C.Op1.getValueType() != MVT::i32 ||
1662       Value != ConstOp1->getZExtValue())
1663     C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1664 }
1665 
1666 // Return true if Op is either an unextended load, or a load suitable
1667 // for integer register-memory comparisons of type ICmpType.
1668 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1669   auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1670   if (Load) {
1671     // There are no instructions to compare a register with a memory byte.
1672     if (Load->getMemoryVT() == MVT::i8)
1673       return false;
1674     // Otherwise decide on extension type.
1675     switch (Load->getExtensionType()) {
1676     case ISD::NON_EXTLOAD:
1677       return true;
1678     case ISD::SEXTLOAD:
1679       return ICmpType != SystemZICMP::UnsignedOnly;
1680     case ISD::ZEXTLOAD:
1681       return ICmpType != SystemZICMP::SignedOnly;
1682     default:
1683       break;
1684     }
1685   }
1686   return false;
1687 }
1688 
1689 // Return true if it is better to swap the operands of C.
1690 static bool shouldSwapCmpOperands(const Comparison &C) {
1691   // Leave f128 comparisons alone, since they have no memory forms.
1692   if (C.Op0.getValueType() == MVT::f128)
1693     return false;
1694 
1695   // Always keep a floating-point constant second, since comparisons with
1696   // zero can use LOAD TEST and comparisons with other constants make a
1697   // natural memory operand.
1698   if (isa<ConstantFPSDNode>(C.Op1))
1699     return false;
1700 
1701   // Never swap comparisons with zero since there are many ways to optimize
1702   // those later.
1703   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1704   if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1705     return false;
1706 
1707   // Also keep natural memory operands second if the loaded value is
1708   // only used here.  Several comparisons have memory forms.
1709   if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1710     return false;
1711 
1712   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1713   // In that case we generally prefer the memory to be second.
1714   if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1715     // The only exceptions are when the second operand is a constant and
1716     // we can use things like CHHSI.
1717     if (!ConstOp1)
1718       return true;
1719     // The unsigned memory-immediate instructions can handle 16-bit
1720     // unsigned integers.
1721     if (C.ICmpType != SystemZICMP::SignedOnly &&
1722         isUInt<16>(ConstOp1->getZExtValue()))
1723       return false;
1724     // The signed memory-immediate instructions can handle 16-bit
1725     // signed integers.
1726     if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1727         isInt<16>(ConstOp1->getSExtValue()))
1728       return false;
1729     return true;
1730   }
1731 
1732   // Try to promote the use of CGFR and CLGFR.
1733   unsigned Opcode0 = C.Op0.getOpcode();
1734   if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1735     return true;
1736   if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1737     return true;
1738   if (C.ICmpType != SystemZICMP::SignedOnly &&
1739       Opcode0 == ISD::AND &&
1740       C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1741       cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1742     return true;
1743 
1744   return false;
1745 }
1746 
1747 // Return a version of comparison CC mask CCMask in which the LT and GT
1748 // actions are swapped.
1749 static unsigned reverseCCMask(unsigned CCMask) {
1750   return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1751           (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1752           (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1753           (CCMask & SystemZ::CCMASK_CMP_UO));
1754 }
1755 
1756 // Check whether C tests for equality between X and Y and whether X - Y
1757 // or Y - X is also computed.  In that case it's better to compare the
1758 // result of the subtraction against zero.
1759 static void adjustForSubtraction(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1760   if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1761       C.CCMask == SystemZ::CCMASK_CMP_NE) {
1762     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1763       SDNode *N = *I;
1764       if (N->getOpcode() == ISD::SUB &&
1765           ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1766            (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1767         C.Op0 = SDValue(N, 0);
1768         C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1769         return;
1770       }
1771     }
1772   }
1773 }
1774 
1775 // Check whether C compares a floating-point value with zero and if that
1776 // floating-point value is also negated.  In this case we can use the
1777 // negation to set CC, so avoiding separate LOAD AND TEST and
1778 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1779 static void adjustForFNeg(Comparison &C) {
1780   auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1781   if (C1 && C1->isZero()) {
1782     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1783       SDNode *N = *I;
1784       if (N->getOpcode() == ISD::FNEG) {
1785         C.Op0 = SDValue(N, 0);
1786         C.CCMask = reverseCCMask(C.CCMask);
1787         return;
1788       }
1789     }
1790   }
1791 }
1792 
1793 // Check whether C compares (shl X, 32) with 0 and whether X is
1794 // also sign-extended.  In that case it is better to test the result
1795 // of the sign extension using LTGFR.
1796 //
1797 // This case is important because InstCombine transforms a comparison
1798 // with (sext (trunc X)) into a comparison with (shl X, 32).
1799 static void adjustForLTGFR(Comparison &C) {
1800   // Check for a comparison between (shl X, 32) and 0.
1801   if (C.Op0.getOpcode() == ISD::SHL &&
1802       C.Op0.getValueType() == MVT::i64 &&
1803       C.Op1.getOpcode() == ISD::Constant &&
1804       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1805     auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1806     if (C1 && C1->getZExtValue() == 32) {
1807       SDValue ShlOp0 = C.Op0.getOperand(0);
1808       // See whether X has any SIGN_EXTEND_INREG uses.
1809       for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1810         SDNode *N = *I;
1811         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1812             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1813           C.Op0 = SDValue(N, 0);
1814           return;
1815         }
1816       }
1817     }
1818   }
1819 }
1820 
1821 // If C compares the truncation of an extending load, try to compare
1822 // the untruncated value instead.  This exposes more opportunities to
1823 // reuse CC.
1824 static void adjustICmpTruncate(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1825   if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1826       C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1827       C.Op1.getOpcode() == ISD::Constant &&
1828       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1829     auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1830     if (L->getMemoryVT().getStoreSizeInBits()
1831         <= C.Op0.getValueType().getSizeInBits()) {
1832       unsigned Type = L->getExtensionType();
1833       if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1834           (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1835         C.Op0 = C.Op0.getOperand(0);
1836         C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1837       }
1838     }
1839   }
1840 }
1841 
1842 // Return true if shift operation N has an in-range constant shift value.
1843 // Store it in ShiftVal if so.
1844 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1845   auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1846   if (!Shift)
1847     return false;
1848 
1849   uint64_t Amount = Shift->getZExtValue();
1850   if (Amount >= N.getValueType().getSizeInBits())
1851     return false;
1852 
1853   ShiftVal = Amount;
1854   return true;
1855 }
1856 
1857 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1858 // instruction and whether the CC value is descriptive enough to handle
1859 // a comparison of type Opcode between the AND result and CmpVal.
1860 // CCMask says which comparison result is being tested and BitSize is
1861 // the number of bits in the operands.  If TEST UNDER MASK can be used,
1862 // return the corresponding CC mask, otherwise return 0.
1863 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1864                                      uint64_t Mask, uint64_t CmpVal,
1865                                      unsigned ICmpType) {
1866   assert(Mask != 0 && "ANDs with zero should have been removed by now");
1867 
1868   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1869   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1870       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1871     return 0;
1872 
1873   // Work out the masks for the lowest and highest bits.
1874   unsigned HighShift = 63 - countLeadingZeros(Mask);
1875   uint64_t High = uint64_t(1) << HighShift;
1876   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1877 
1878   // Signed ordered comparisons are effectively unsigned if the sign
1879   // bit is dropped.
1880   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1881 
1882   // Check for equality comparisons with 0, or the equivalent.
1883   if (CmpVal == 0) {
1884     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1885       return SystemZ::CCMASK_TM_ALL_0;
1886     if (CCMask == SystemZ::CCMASK_CMP_NE)
1887       return SystemZ::CCMASK_TM_SOME_1;
1888   }
1889   if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
1890     if (CCMask == SystemZ::CCMASK_CMP_LT)
1891       return SystemZ::CCMASK_TM_ALL_0;
1892     if (CCMask == SystemZ::CCMASK_CMP_GE)
1893       return SystemZ::CCMASK_TM_SOME_1;
1894   }
1895   if (EffectivelyUnsigned && CmpVal < Low) {
1896     if (CCMask == SystemZ::CCMASK_CMP_LE)
1897       return SystemZ::CCMASK_TM_ALL_0;
1898     if (CCMask == SystemZ::CCMASK_CMP_GT)
1899       return SystemZ::CCMASK_TM_SOME_1;
1900   }
1901 
1902   // Check for equality comparisons with the mask, or the equivalent.
1903   if (CmpVal == Mask) {
1904     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1905       return SystemZ::CCMASK_TM_ALL_1;
1906     if (CCMask == SystemZ::CCMASK_CMP_NE)
1907       return SystemZ::CCMASK_TM_SOME_0;
1908   }
1909   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1910     if (CCMask == SystemZ::CCMASK_CMP_GT)
1911       return SystemZ::CCMASK_TM_ALL_1;
1912     if (CCMask == SystemZ::CCMASK_CMP_LE)
1913       return SystemZ::CCMASK_TM_SOME_0;
1914   }
1915   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1916     if (CCMask == SystemZ::CCMASK_CMP_GE)
1917       return SystemZ::CCMASK_TM_ALL_1;
1918     if (CCMask == SystemZ::CCMASK_CMP_LT)
1919       return SystemZ::CCMASK_TM_SOME_0;
1920   }
1921 
1922   // Check for ordered comparisons with the top bit.
1923   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1924     if (CCMask == SystemZ::CCMASK_CMP_LE)
1925       return SystemZ::CCMASK_TM_MSB_0;
1926     if (CCMask == SystemZ::CCMASK_CMP_GT)
1927       return SystemZ::CCMASK_TM_MSB_1;
1928   }
1929   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1930     if (CCMask == SystemZ::CCMASK_CMP_LT)
1931       return SystemZ::CCMASK_TM_MSB_0;
1932     if (CCMask == SystemZ::CCMASK_CMP_GE)
1933       return SystemZ::CCMASK_TM_MSB_1;
1934   }
1935 
1936   // If there are just two bits, we can do equality checks for Low and High
1937   // as well.
1938   if (Mask == Low + High) {
1939     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1940       return SystemZ::CCMASK_TM_MIXED_MSB_0;
1941     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1942       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1943     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1944       return SystemZ::CCMASK_TM_MIXED_MSB_1;
1945     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1946       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1947   }
1948 
1949   // Looks like we've exhausted our options.
1950   return 0;
1951 }
1952 
1953 // See whether C can be implemented as a TEST UNDER MASK instruction.
1954 // Update the arguments with the TM version if so.
1955 static void adjustForTestUnderMask(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1956   // Check that we have a comparison with a constant.
1957   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1958   if (!ConstOp1)
1959     return;
1960   uint64_t CmpVal = ConstOp1->getZExtValue();
1961 
1962   // Check whether the nonconstant input is an AND with a constant mask.
1963   Comparison NewC(C);
1964   uint64_t MaskVal;
1965   ConstantSDNode *Mask = nullptr;
1966   if (C.Op0.getOpcode() == ISD::AND) {
1967     NewC.Op0 = C.Op0.getOperand(0);
1968     NewC.Op1 = C.Op0.getOperand(1);
1969     Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
1970     if (!Mask)
1971       return;
1972     MaskVal = Mask->getZExtValue();
1973   } else {
1974     // There is no instruction to compare with a 64-bit immediate
1975     // so use TMHH instead if possible.  We need an unsigned ordered
1976     // comparison with an i64 immediate.
1977     if (NewC.Op0.getValueType() != MVT::i64 ||
1978         NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
1979         NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
1980         NewC.ICmpType == SystemZICMP::SignedOnly)
1981       return;
1982     // Convert LE and GT comparisons into LT and GE.
1983     if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
1984         NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
1985       if (CmpVal == uint64_t(-1))
1986         return;
1987       CmpVal += 1;
1988       NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1989     }
1990     // If the low N bits of Op1 are zero than the low N bits of Op0 can
1991     // be masked off without changing the result.
1992     MaskVal = -(CmpVal & -CmpVal);
1993     NewC.ICmpType = SystemZICMP::UnsignedOnly;
1994   }
1995   if (!MaskVal)
1996     return;
1997 
1998   // Check whether the combination of mask, comparison value and comparison
1999   // type are suitable.
2000   unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
2001   unsigned NewCCMask, ShiftVal;
2002   if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2003       NewC.Op0.getOpcode() == ISD::SHL &&
2004       isSimpleShift(NewC.Op0, ShiftVal) &&
2005       (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2006                                         MaskVal >> ShiftVal,
2007                                         CmpVal >> ShiftVal,
2008                                         SystemZICMP::Any))) {
2009     NewC.Op0 = NewC.Op0.getOperand(0);
2010     MaskVal >>= ShiftVal;
2011   } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2012              NewC.Op0.getOpcode() == ISD::SRL &&
2013              isSimpleShift(NewC.Op0, ShiftVal) &&
2014              (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2015                                                MaskVal << ShiftVal,
2016                                                CmpVal << ShiftVal,
2017                                                SystemZICMP::UnsignedOnly))) {
2018     NewC.Op0 = NewC.Op0.getOperand(0);
2019     MaskVal <<= ShiftVal;
2020   } else {
2021     NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2022                                      NewC.ICmpType);
2023     if (!NewCCMask)
2024       return;
2025   }
2026 
2027   // Go ahead and make the change.
2028   C.Opcode = SystemZISD::TM;
2029   C.Op0 = NewC.Op0;
2030   if (Mask && Mask->getZExtValue() == MaskVal)
2031     C.Op1 = SDValue(Mask, 0);
2032   else
2033     C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2034   C.CCValid = SystemZ::CCMASK_TM;
2035   C.CCMask = NewCCMask;
2036 }
2037 
2038 // Return a Comparison that tests the condition-code result of intrinsic
2039 // node Call against constant integer CC using comparison code Cond.
2040 // Opcode is the opcode of the SystemZISD operation for the intrinsic
2041 // and CCValid is the set of possible condition-code results.
2042 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2043                                   SDValue Call, unsigned CCValid, uint64_t CC,
2044                                   ISD::CondCode Cond) {
2045   Comparison C(Call, SDValue());
2046   C.Opcode = Opcode;
2047   C.CCValid = CCValid;
2048   if (Cond == ISD::SETEQ)
2049     // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2050     C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2051   else if (Cond == ISD::SETNE)
2052     // ...and the inverse of that.
2053     C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2054   else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2055     // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2056     // always true for CC>3.
2057     C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2058   else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2059     // ...and the inverse of that.
2060     C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2061   else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2062     // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2063     // always true for CC>3.
2064     C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2065   else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2066     // ...and the inverse of that.
2067     C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2068   else
2069     llvm_unreachable("Unexpected integer comparison type");
2070   C.CCMask &= CCValid;
2071   return C;
2072 }
2073 
2074 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2075 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2076                          ISD::CondCode Cond, SDLoc DL) {
2077   if (CmpOp1.getOpcode() == ISD::Constant) {
2078     uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2079     unsigned Opcode, CCValid;
2080     if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2081         CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2082         isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2083       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2084     if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2085         CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2086         isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2087       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2088   }
2089   Comparison C(CmpOp0, CmpOp1);
2090   C.CCMask = CCMaskForCondCode(Cond);
2091   if (C.Op0.getValueType().isFloatingPoint()) {
2092     C.CCValid = SystemZ::CCMASK_FCMP;
2093     C.Opcode = SystemZISD::FCMP;
2094     adjustForFNeg(C);
2095   } else {
2096     C.CCValid = SystemZ::CCMASK_ICMP;
2097     C.Opcode = SystemZISD::ICMP;
2098     // Choose the type of comparison.  Equality and inequality tests can
2099     // use either signed or unsigned comparisons.  The choice also doesn't
2100     // matter if both sign bits are known to be clear.  In those cases we
2101     // want to give the main isel code the freedom to choose whichever
2102     // form fits best.
2103     if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2104         C.CCMask == SystemZ::CCMASK_CMP_NE ||
2105         (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2106       C.ICmpType = SystemZICMP::Any;
2107     else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2108       C.ICmpType = SystemZICMP::UnsignedOnly;
2109     else
2110       C.ICmpType = SystemZICMP::SignedOnly;
2111     C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2112     adjustZeroCmp(DAG, DL, C);
2113     adjustSubwordCmp(DAG, DL, C);
2114     adjustForSubtraction(DAG, DL, C);
2115     adjustForLTGFR(C);
2116     adjustICmpTruncate(DAG, DL, C);
2117   }
2118 
2119   if (shouldSwapCmpOperands(C)) {
2120     std::swap(C.Op0, C.Op1);
2121     C.CCMask = reverseCCMask(C.CCMask);
2122   }
2123 
2124   adjustForTestUnderMask(DAG, DL, C);
2125   return C;
2126 }
2127 
2128 // Emit the comparison instruction described by C.
2129 static SDValue emitCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
2130   if (!C.Op1.getNode()) {
2131     SDValue Op;
2132     switch (C.Op0.getOpcode()) {
2133     case ISD::INTRINSIC_W_CHAIN:
2134       Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
2135       break;
2136     case ISD::INTRINSIC_WO_CHAIN:
2137       Op = emitIntrinsicWithGlue(DAG, C.Op0, C.Opcode);
2138       break;
2139     default:
2140       llvm_unreachable("Invalid comparison operands");
2141     }
2142     return SDValue(Op.getNode(), Op->getNumValues() - 1);
2143   }
2144   if (C.Opcode == SystemZISD::ICMP)
2145     return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
2146                        DAG.getConstant(C.ICmpType, DL, MVT::i32));
2147   if (C.Opcode == SystemZISD::TM) {
2148     bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2149                          bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2150     return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
2151                        DAG.getConstant(RegisterOnly, DL, MVT::i32));
2152   }
2153   return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
2154 }
2155 
2156 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
2157 // 64 bits.  Extend is the extension type to use.  Store the high part
2158 // in Hi and the low part in Lo.
2159 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
2160                             unsigned Extend, SDValue Op0, SDValue Op1,
2161                             SDValue &Hi, SDValue &Lo) {
2162   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2163   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2164   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2165   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2166                    DAG.getConstant(32, DL, MVT::i64));
2167   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2168   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2169 }
2170 
2171 // Lower a binary operation that produces two VT results, one in each
2172 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
2173 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
2174 // on the extended Op0 and (unextended) Op1.  Store the even register result
2175 // in Even and the odd register result in Odd.
2176 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
2177                              unsigned Extend, unsigned Opcode,
2178                              SDValue Op0, SDValue Op1,
2179                              SDValue &Even, SDValue &Odd) {
2180   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
2181   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
2182                                SDValue(In128, 0), Op1);
2183   bool Is32Bit = is32Bit(VT);
2184   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2185   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2186 }
2187 
2188 // Return an i32 value that is 1 if the CC value produced by Glue is
2189 // in the mask CCMask and 0 otherwise.  CC is known to have a value
2190 // in CCValid, so other values can be ignored.
2191 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
2192                          unsigned CCValid, unsigned CCMask) {
2193   IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
2194   SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
2195 
2196   if (Conversion.XORValue)
2197     Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
2198                          DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
2199 
2200   if (Conversion.AddValue)
2201     Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
2202                          DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
2203 
2204   // The SHR/AND sequence should get optimized to an RISBG.
2205   Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
2206                        DAG.getConstant(Conversion.Bit, DL, MVT::i32));
2207   if (Conversion.Bit != 31)
2208     Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
2209                          DAG.getConstant(1, DL, MVT::i32));
2210   return Result;
2211 }
2212 
2213 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2214 // be done directly.  IsFP is true if CC is for a floating-point rather than
2215 // integer comparison.
2216 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
2217   switch (CC) {
2218   case ISD::SETOEQ:
2219   case ISD::SETEQ:
2220     return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
2221 
2222   case ISD::SETOGE:
2223   case ISD::SETGE:
2224     return IsFP ? SystemZISD::VFCMPHE : static_cast<SystemZISD::NodeType>(0);
2225 
2226   case ISD::SETOGT:
2227   case ISD::SETGT:
2228     return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
2229 
2230   case ISD::SETUGT:
2231     return IsFP ? static_cast<SystemZISD::NodeType>(0) : SystemZISD::VICMPHL;
2232 
2233   default:
2234     return 0;
2235   }
2236 }
2237 
2238 // Return the SystemZISD vector comparison operation for CC or its inverse,
2239 // or 0 if neither can be done directly.  Indicate in Invert whether the
2240 // result is for the inverse of CC.  IsFP is true if CC is for a
2241 // floating-point rather than integer comparison.
2242 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2243                                             bool &Invert) {
2244   if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2245     Invert = false;
2246     return Opcode;
2247   }
2248 
2249   CC = ISD::getSetCCInverse(CC, !IsFP);
2250   if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2251     Invert = true;
2252     return Opcode;
2253   }
2254 
2255   return 0;
2256 }
2257 
2258 // Return a v2f64 that contains the extended form of elements Start and Start+1
2259 // of v4f32 value Op.
2260 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, SDLoc DL,
2261                                   SDValue Op) {
2262   int Mask[] = { Start, -1, Start + 1, -1 };
2263   Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2264   return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2265 }
2266 
2267 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2268 // producing a result of type VT.
2269 static SDValue getVectorCmp(SelectionDAG &DAG, unsigned Opcode, SDLoc DL,
2270                             EVT VT, SDValue CmpOp0, SDValue CmpOp1) {
2271   // There is no hardware support for v4f32, so extend the vector into
2272   // two v2f64s and compare those.
2273   if (CmpOp0.getValueType() == MVT::v4f32) {
2274     SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2275     SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2276     SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2277     SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2278     SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2279     SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2280     return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2281   }
2282   return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2283 }
2284 
2285 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2286 // an integer mask of type VT.
2287 static SDValue lowerVectorSETCC(SelectionDAG &DAG, SDLoc DL, EVT VT,
2288                                 ISD::CondCode CC, SDValue CmpOp0,
2289                                 SDValue CmpOp1) {
2290   bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2291   bool Invert = false;
2292   SDValue Cmp;
2293   switch (CC) {
2294     // Handle tests for order using (or (ogt y x) (oge x y)).
2295   case ISD::SETUO:
2296     Invert = true;
2297   case ISD::SETO: {
2298     assert(IsFP && "Unexpected integer comparison");
2299     SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2300     SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2301     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2302     break;
2303   }
2304 
2305     // Handle <> tests using (or (ogt y x) (ogt x y)).
2306   case ISD::SETUEQ:
2307     Invert = true;
2308   case ISD::SETONE: {
2309     assert(IsFP && "Unexpected integer comparison");
2310     SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2311     SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2312     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2313     break;
2314   }
2315 
2316     // Otherwise a single comparison is enough.  It doesn't really
2317     // matter whether we try the inversion or the swap first, since
2318     // there are no cases where both work.
2319   default:
2320     if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2321       Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2322     else {
2323       CC = ISD::getSetCCSwappedOperands(CC);
2324       if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2325         Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2326       else
2327         llvm_unreachable("Unhandled comparison");
2328     }
2329     break;
2330   }
2331   if (Invert) {
2332     SDValue Mask = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2333                                DAG.getConstant(65535, DL, MVT::i32));
2334     Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2335     Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2336   }
2337   return Cmp;
2338 }
2339 
2340 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2341                                           SelectionDAG &DAG) const {
2342   SDValue CmpOp0   = Op.getOperand(0);
2343   SDValue CmpOp1   = Op.getOperand(1);
2344   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2345   SDLoc DL(Op);
2346   EVT VT = Op.getValueType();
2347   if (VT.isVector())
2348     return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2349 
2350   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2351   SDValue Glue = emitCmp(DAG, DL, C);
2352   return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2353 }
2354 
2355 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2356   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2357   SDValue CmpOp0   = Op.getOperand(2);
2358   SDValue CmpOp1   = Op.getOperand(3);
2359   SDValue Dest     = Op.getOperand(4);
2360   SDLoc DL(Op);
2361 
2362   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2363   SDValue Glue = emitCmp(DAG, DL, C);
2364   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2365                      Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2366                      DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2367 }
2368 
2369 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2370 // allowing Pos and Neg to be wider than CmpOp.
2371 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2372   return (Neg.getOpcode() == ISD::SUB &&
2373           Neg.getOperand(0).getOpcode() == ISD::Constant &&
2374           cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2375           Neg.getOperand(1) == Pos &&
2376           (Pos == CmpOp ||
2377            (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2378             Pos.getOperand(0) == CmpOp)));
2379 }
2380 
2381 // Return the absolute or negative absolute of Op; IsNegative decides which.
2382 static SDValue getAbsolute(SelectionDAG &DAG, SDLoc DL, SDValue Op,
2383                            bool IsNegative) {
2384   Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2385   if (IsNegative)
2386     Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2387                      DAG.getConstant(0, DL, Op.getValueType()), Op);
2388   return Op;
2389 }
2390 
2391 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2392                                               SelectionDAG &DAG) const {
2393   SDValue CmpOp0   = Op.getOperand(0);
2394   SDValue CmpOp1   = Op.getOperand(1);
2395   SDValue TrueOp   = Op.getOperand(2);
2396   SDValue FalseOp  = Op.getOperand(3);
2397   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2398   SDLoc DL(Op);
2399 
2400   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2401 
2402   // Check for absolute and negative-absolute selections, including those
2403   // where the comparison value is sign-extended (for LPGFR and LNGFR).
2404   // This check supplements the one in DAGCombiner.
2405   if (C.Opcode == SystemZISD::ICMP &&
2406       C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2407       C.CCMask != SystemZ::CCMASK_CMP_NE &&
2408       C.Op1.getOpcode() == ISD::Constant &&
2409       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2410     if (isAbsolute(C.Op0, TrueOp, FalseOp))
2411       return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2412     if (isAbsolute(C.Op0, FalseOp, TrueOp))
2413       return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2414   }
2415 
2416   SDValue Glue = emitCmp(DAG, DL, C);
2417 
2418   // Special case for handling -1/0 results.  The shifts we use here
2419   // should get optimized with the IPM conversion sequence.
2420   auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2421   auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2422   if (TrueC && FalseC) {
2423     int64_t TrueVal = TrueC->getSExtValue();
2424     int64_t FalseVal = FalseC->getSExtValue();
2425     if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2426       // Invert the condition if we want -1 on false.
2427       if (TrueVal == 0)
2428         C.CCMask ^= C.CCValid;
2429       SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2430       EVT VT = Op.getValueType();
2431       // Extend the result to VT.  Upper bits are ignored.
2432       if (!is32Bit(VT))
2433         Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2434       // Sign-extend from the low bit.
2435       SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2436       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2437       return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2438     }
2439   }
2440 
2441   SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2442                    DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2443 
2444   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2445   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2446 }
2447 
2448 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2449                                                   SelectionDAG &DAG) const {
2450   SDLoc DL(Node);
2451   const GlobalValue *GV = Node->getGlobal();
2452   int64_t Offset = Node->getOffset();
2453   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2454   Reloc::Model RM = DAG.getTarget().getRelocationModel();
2455   CodeModel::Model CM = DAG.getTarget().getCodeModel();
2456 
2457   SDValue Result;
2458   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
2459     // Assign anchors at 1<<12 byte boundaries.
2460     uint64_t Anchor = Offset & ~uint64_t(0xfff);
2461     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2462     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2463 
2464     // The offset can be folded into the address if it is aligned to a halfword.
2465     Offset -= Anchor;
2466     if (Offset != 0 && (Offset & 1) == 0) {
2467       SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2468       Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2469       Offset = 0;
2470     }
2471   } else {
2472     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2473     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2474     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2475                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2476                          false, false, false, 0);
2477   }
2478 
2479   // If there was a non-zero offset that we didn't fold, create an explicit
2480   // addition for it.
2481   if (Offset != 0)
2482     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2483                          DAG.getConstant(Offset, DL, PtrVT));
2484 
2485   return Result;
2486 }
2487 
2488 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2489                                                  SelectionDAG &DAG,
2490                                                  unsigned Opcode,
2491                                                  SDValue GOTOffset) const {
2492   SDLoc DL(Node);
2493   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2494   SDValue Chain = DAG.getEntryNode();
2495   SDValue Glue;
2496 
2497   // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2498   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2499   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2500   Glue = Chain.getValue(1);
2501   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2502   Glue = Chain.getValue(1);
2503 
2504   // The first call operand is the chain and the second is the TLS symbol.
2505   SmallVector<SDValue, 8> Ops;
2506   Ops.push_back(Chain);
2507   Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2508                                            Node->getValueType(0),
2509                                            0, 0));
2510 
2511   // Add argument registers to the end of the list so that they are
2512   // known live into the call.
2513   Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2514   Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2515 
2516   // Add a register mask operand representing the call-preserved registers.
2517   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2518   const uint32_t *Mask =
2519       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
2520   assert(Mask && "Missing call preserved mask for calling convention");
2521   Ops.push_back(DAG.getRegisterMask(Mask));
2522 
2523   // Glue the call to the argument copies.
2524   Ops.push_back(Glue);
2525 
2526   // Emit the call.
2527   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2528   Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2529   Glue = Chain.getValue(1);
2530 
2531   // Copy the return value from %r2.
2532   return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2533 }
2534 
2535 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
2536                                                   SelectionDAG &DAG) const {
2537   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2538 
2539   // The high part of the thread pointer is in access register 0.
2540   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2541                              DAG.getConstant(0, DL, MVT::i32));
2542   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2543 
2544   // The low part of the thread pointer is in access register 1.
2545   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2546                              DAG.getConstant(1, DL, MVT::i32));
2547   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2548 
2549   // Merge them into a single 64-bit address.
2550   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2551                                     DAG.getConstant(32, DL, PtrVT));
2552   return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2553 }
2554 
2555 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2556                                                      SelectionDAG &DAG) const {
2557   if (DAG.getTarget().Options.EmulatedTLS)
2558     return LowerToTLSEmulatedModel(Node, DAG);
2559   SDLoc DL(Node);
2560   const GlobalValue *GV = Node->getGlobal();
2561   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2562   TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2563 
2564   SDValue TP = lowerThreadPointer(DL, DAG);
2565 
2566   // Get the offset of GA from the thread pointer, based on the TLS model.
2567   SDValue Offset;
2568   switch (model) {
2569     case TLSModel::GeneralDynamic: {
2570       // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2571       SystemZConstantPoolValue *CPV =
2572         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
2573 
2574       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2575       Offset = DAG.getLoad(
2576           PtrVT, DL, DAG.getEntryNode(), Offset,
2577           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2578           false, false, 0);
2579 
2580       // Call __tls_get_offset to retrieve the offset.
2581       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2582       break;
2583     }
2584 
2585     case TLSModel::LocalDynamic: {
2586       // Load the GOT offset of the module ID.
2587       SystemZConstantPoolValue *CPV =
2588         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
2589 
2590       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2591       Offset = DAG.getLoad(
2592           PtrVT, DL, DAG.getEntryNode(), Offset,
2593           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2594           false, false, 0);
2595 
2596       // Call __tls_get_offset to retrieve the module base offset.
2597       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2598 
2599       // Note: The SystemZLDCleanupPass will remove redundant computations
2600       // of the module base offset.  Count total number of local-dynamic
2601       // accesses to trigger execution of that pass.
2602       SystemZMachineFunctionInfo* MFI =
2603         DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
2604       MFI->incNumLocalDynamicTLSAccesses();
2605 
2606       // Add the per-symbol offset.
2607       CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
2608 
2609       SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2610       DTPOffset = DAG.getLoad(
2611           PtrVT, DL, DAG.getEntryNode(), DTPOffset,
2612           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2613           false, false, 0);
2614 
2615       Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2616       break;
2617     }
2618 
2619     case TLSModel::InitialExec: {
2620       // Load the offset from the GOT.
2621       Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2622                                           SystemZII::MO_INDNTPOFF);
2623       Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2624       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
2625                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2626                            false, false, false, 0);
2627       break;
2628     }
2629 
2630     case TLSModel::LocalExec: {
2631       // Force the offset into the constant pool and load it from there.
2632       SystemZConstantPoolValue *CPV =
2633         SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
2634 
2635       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2636       Offset = DAG.getLoad(
2637           PtrVT, DL, DAG.getEntryNode(), Offset,
2638           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2639           false, false, 0);
2640       break;
2641     }
2642   }
2643 
2644   // Add the base and offset together.
2645   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2646 }
2647 
2648 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2649                                                  SelectionDAG &DAG) const {
2650   SDLoc DL(Node);
2651   const BlockAddress *BA = Node->getBlockAddress();
2652   int64_t Offset = Node->getOffset();
2653   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2654 
2655   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2656   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2657   return Result;
2658 }
2659 
2660 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2661                                               SelectionDAG &DAG) const {
2662   SDLoc DL(JT);
2663   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2664   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2665 
2666   // Use LARL to load the address of the table.
2667   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2668 }
2669 
2670 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2671                                                  SelectionDAG &DAG) const {
2672   SDLoc DL(CP);
2673   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2674 
2675   SDValue Result;
2676   if (CP->isMachineConstantPoolEntry())
2677     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2678                                        CP->getAlignment());
2679   else
2680     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2681                                        CP->getAlignment(), CP->getOffset());
2682 
2683   // Use LARL to load the address of the constant pool entry.
2684   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2685 }
2686 
2687 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
2688                                               SelectionDAG &DAG) const {
2689   MachineFunction &MF = DAG.getMachineFunction();
2690   MachineFrameInfo *MFI = MF.getFrameInfo();
2691   MFI->setFrameAddressIsTaken(true);
2692 
2693   SDLoc DL(Op);
2694   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2695   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2696 
2697   // If the back chain frame index has not been allocated yet, do so.
2698   SystemZMachineFunctionInfo *FI = MF.getInfo<SystemZMachineFunctionInfo>();
2699   int BackChainIdx = FI->getFramePointerSaveIndex();
2700   if (!BackChainIdx) {
2701     // By definition, the frame address is the address of the back chain.
2702     BackChainIdx = MFI->CreateFixedObject(8, -SystemZMC::CallFrameSize, false);
2703     FI->setFramePointerSaveIndex(BackChainIdx);
2704   }
2705   SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
2706 
2707   // FIXME The frontend should detect this case.
2708   if (Depth > 0) {
2709     report_fatal_error("Unsupported stack frame traversal count");
2710   }
2711 
2712   return BackChain;
2713 }
2714 
2715 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
2716                                                SelectionDAG &DAG) const {
2717   MachineFunction &MF = DAG.getMachineFunction();
2718   MachineFrameInfo *MFI = MF.getFrameInfo();
2719   MFI->setReturnAddressIsTaken(true);
2720 
2721   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2722     return SDValue();
2723 
2724   SDLoc DL(Op);
2725   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2726   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2727 
2728   // FIXME The frontend should detect this case.
2729   if (Depth > 0) {
2730     report_fatal_error("Unsupported stack frame traversal count");
2731   }
2732 
2733   // Return R14D, which has the return address. Mark it an implicit live-in.
2734   unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
2735   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
2736 }
2737 
2738 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2739                                             SelectionDAG &DAG) const {
2740   SDLoc DL(Op);
2741   SDValue In = Op.getOperand(0);
2742   EVT InVT = In.getValueType();
2743   EVT ResVT = Op.getValueType();
2744 
2745   // Convert loads directly.  This is normally done by DAGCombiner,
2746   // but we need this case for bitcasts that are created during lowering
2747   // and which are then lowered themselves.
2748   if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2749     return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2750                        LoadN->getMemOperand());
2751 
2752   if (InVT == MVT::i32 && ResVT == MVT::f32) {
2753     SDValue In64;
2754     if (Subtarget.hasHighWord()) {
2755       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2756                                        MVT::i64);
2757       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2758                                        MVT::i64, SDValue(U64, 0), In);
2759     } else {
2760       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2761       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2762                          DAG.getConstant(32, DL, MVT::i64));
2763     }
2764     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2765     return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2766                                       DL, MVT::f32, Out64);
2767   }
2768   if (InVT == MVT::f32 && ResVT == MVT::i32) {
2769     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2770     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2771                                              MVT::f64, SDValue(U64, 0), In);
2772     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2773     if (Subtarget.hasHighWord())
2774       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2775                                         MVT::i32, Out64);
2776     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2777                                 DAG.getConstant(32, DL, MVT::i64));
2778     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2779   }
2780   llvm_unreachable("Unexpected bitcast combination");
2781 }
2782 
2783 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2784                                             SelectionDAG &DAG) const {
2785   MachineFunction &MF = DAG.getMachineFunction();
2786   SystemZMachineFunctionInfo *FuncInfo =
2787     MF.getInfo<SystemZMachineFunctionInfo>();
2788   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2789 
2790   SDValue Chain   = Op.getOperand(0);
2791   SDValue Addr    = Op.getOperand(1);
2792   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2793   SDLoc DL(Op);
2794 
2795   // The initial values of each field.
2796   const unsigned NumFields = 4;
2797   SDValue Fields[NumFields] = {
2798     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2799     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2800     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2801     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2802   };
2803 
2804   // Store each field into its respective slot.
2805   SDValue MemOps[NumFields];
2806   unsigned Offset = 0;
2807   for (unsigned I = 0; I < NumFields; ++I) {
2808     SDValue FieldAddr = Addr;
2809     if (Offset != 0)
2810       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2811                               DAG.getIntPtrConstant(Offset, DL));
2812     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2813                              MachinePointerInfo(SV, Offset),
2814                              false, false, 0);
2815     Offset += 8;
2816   }
2817   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2818 }
2819 
2820 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2821                                            SelectionDAG &DAG) const {
2822   SDValue Chain      = Op.getOperand(0);
2823   SDValue DstPtr     = Op.getOperand(1);
2824   SDValue SrcPtr     = Op.getOperand(2);
2825   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2826   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2827   SDLoc DL(Op);
2828 
2829   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2830                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2831                        /*isTailCall*/false,
2832                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2833 }
2834 
2835 SDValue SystemZTargetLowering::
2836 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2837   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
2838   bool RealignOpt = !DAG.getMachineFunction().getFunction()->
2839     hasFnAttribute("no-realign-stack");
2840 
2841   SDValue Chain = Op.getOperand(0);
2842   SDValue Size  = Op.getOperand(1);
2843   SDValue Align = Op.getOperand(2);
2844   SDLoc DL(Op);
2845 
2846   // If user has set the no alignment function attribute, ignore
2847   // alloca alignments.
2848   uint64_t AlignVal = (RealignOpt ?
2849                        dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0);
2850 
2851   uint64_t StackAlign = TFI->getStackAlignment();
2852   uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
2853   uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
2854 
2855   unsigned SPReg = getStackPointerRegisterToSaveRestore();
2856   SDValue NeededSpace = Size;
2857 
2858   // Get a reference to the stack pointer.
2859   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2860 
2861   // Add extra space for alignment if needed.
2862   if (ExtraAlignSpace)
2863     NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
2864                               DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2865 
2866   // Get the new stack pointer value.
2867   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
2868 
2869   // Copy the new stack pointer back.
2870   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2871 
2872   // The allocated data lives above the 160 bytes allocated for the standard
2873   // frame, plus any outgoing stack arguments.  We don't know how much that
2874   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2875   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2876   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2877 
2878   // Dynamically realign if needed.
2879   if (RequiredAlign > StackAlign) {
2880     Result =
2881       DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
2882                   DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2883     Result =
2884       DAG.getNode(ISD::AND, DL, MVT::i64, Result,
2885                   DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
2886   }
2887 
2888   SDValue Ops[2] = { Result, Chain };
2889   return DAG.getMergeValues(Ops, DL);
2890 }
2891 
2892 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2893                                               SelectionDAG &DAG) const {
2894   EVT VT = Op.getValueType();
2895   SDLoc DL(Op);
2896   SDValue Ops[2];
2897   if (is32Bit(VT))
2898     // Just do a normal 64-bit multiplication and extract the results.
2899     // We define this so that it can be used for constant division.
2900     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2901                     Op.getOperand(1), Ops[1], Ops[0]);
2902   else {
2903     // Do a full 128-bit multiplication based on UMUL_LOHI64:
2904     //
2905     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2906     //
2907     // but using the fact that the upper halves are either all zeros
2908     // or all ones:
2909     //
2910     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2911     //
2912     // and grouping the right terms together since they are quicker than the
2913     // multiplication:
2914     //
2915     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2916     SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
2917     SDValue LL = Op.getOperand(0);
2918     SDValue RL = Op.getOperand(1);
2919     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2920     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2921     // UMUL_LOHI64 returns the low result in the odd register and the high
2922     // result in the even register.  SMUL_LOHI is defined to return the
2923     // low half first, so the results are in reverse order.
2924     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2925                      LL, RL, Ops[1], Ops[0]);
2926     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2927     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2928     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2929     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2930   }
2931   return DAG.getMergeValues(Ops, DL);
2932 }
2933 
2934 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
2935                                               SelectionDAG &DAG) const {
2936   EVT VT = Op.getValueType();
2937   SDLoc DL(Op);
2938   SDValue Ops[2];
2939   if (is32Bit(VT))
2940     // Just do a normal 64-bit multiplication and extract the results.
2941     // We define this so that it can be used for constant division.
2942     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
2943                     Op.getOperand(1), Ops[1], Ops[0]);
2944   else
2945     // UMUL_LOHI64 returns the low result in the odd register and the high
2946     // result in the even register.  UMUL_LOHI is defined to return the
2947     // low half first, so the results are in reverse order.
2948     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2949                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2950   return DAG.getMergeValues(Ops, DL);
2951 }
2952 
2953 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
2954                                             SelectionDAG &DAG) const {
2955   SDValue Op0 = Op.getOperand(0);
2956   SDValue Op1 = Op.getOperand(1);
2957   EVT VT = Op.getValueType();
2958   SDLoc DL(Op);
2959   unsigned Opcode;
2960 
2961   // We use DSGF for 32-bit division.
2962   if (is32Bit(VT)) {
2963     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
2964     Opcode = SystemZISD::SDIVREM32;
2965   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
2966     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
2967     Opcode = SystemZISD::SDIVREM32;
2968   } else
2969     Opcode = SystemZISD::SDIVREM64;
2970 
2971   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
2972   // input is "don't care".  The instruction returns the remainder in
2973   // the even register and the quotient in the odd register.
2974   SDValue Ops[2];
2975   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
2976                    Op0, Op1, Ops[1], Ops[0]);
2977   return DAG.getMergeValues(Ops, DL);
2978 }
2979 
2980 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
2981                                             SelectionDAG &DAG) const {
2982   EVT VT = Op.getValueType();
2983   SDLoc DL(Op);
2984 
2985   // DL(G) uses a double-width dividend, so we need to clear the even
2986   // register in the GR128 input.  The instruction returns the remainder
2987   // in the even register and the quotient in the odd register.
2988   SDValue Ops[2];
2989   if (is32Bit(VT))
2990     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
2991                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2992   else
2993     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
2994                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2995   return DAG.getMergeValues(Ops, DL);
2996 }
2997 
2998 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
2999   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
3000 
3001   // Get the known-zero masks for each operand.
3002   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
3003   APInt KnownZero[2], KnownOne[2];
3004   DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
3005   DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
3006 
3007   // See if the upper 32 bits of one operand and the lower 32 bits of the
3008   // other are known zero.  They are the low and high operands respectively.
3009   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
3010                        KnownZero[1].getZExtValue() };
3011   unsigned High, Low;
3012   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3013     High = 1, Low = 0;
3014   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3015     High = 0, Low = 1;
3016   else
3017     return Op;
3018 
3019   SDValue LowOp = Ops[Low];
3020   SDValue HighOp = Ops[High];
3021 
3022   // If the high part is a constant, we're better off using IILH.
3023   if (HighOp.getOpcode() == ISD::Constant)
3024     return Op;
3025 
3026   // If the low part is a constant that is outside the range of LHI,
3027   // then we're better off using IILF.
3028   if (LowOp.getOpcode() == ISD::Constant) {
3029     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3030     if (!isInt<16>(Value))
3031       return Op;
3032   }
3033 
3034   // Check whether the high part is an AND that doesn't change the
3035   // high 32 bits and just masks out low bits.  We can skip it if so.
3036   if (HighOp.getOpcode() == ISD::AND &&
3037       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3038     SDValue HighOp0 = HighOp.getOperand(0);
3039     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3040     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3041       HighOp = HighOp0;
3042   }
3043 
3044   // Take advantage of the fact that all GR32 operations only change the
3045   // low 32 bits by truncating Low to an i32 and inserting it directly
3046   // using a subreg.  The interesting cases are those where the truncation
3047   // can be folded.
3048   SDLoc DL(Op);
3049   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3050   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3051                                    MVT::i64, HighOp, Low32);
3052 }
3053 
3054 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3055                                           SelectionDAG &DAG) const {
3056   EVT VT = Op.getValueType();
3057   SDLoc DL(Op);
3058   Op = Op.getOperand(0);
3059 
3060   // Handle vector types via VPOPCT.
3061   if (VT.isVector()) {
3062     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3063     Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3064     switch (VT.getVectorElementType().getSizeInBits()) {
3065     case 8:
3066       break;
3067     case 16: {
3068       Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3069       SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3070       SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3071       Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3072       Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3073       break;
3074     }
3075     case 32: {
3076       SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3077                                 DAG.getConstant(0, DL, MVT::i32));
3078       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3079       break;
3080     }
3081     case 64: {
3082       SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3083                                 DAG.getConstant(0, DL, MVT::i32));
3084       Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3085       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3086       break;
3087     }
3088     default:
3089       llvm_unreachable("Unexpected type");
3090     }
3091     return Op;
3092   }
3093 
3094   // Get the known-zero mask for the operand.
3095   APInt KnownZero, KnownOne;
3096   DAG.computeKnownBits(Op, KnownZero, KnownOne);
3097   unsigned NumSignificantBits = (~KnownZero).getActiveBits();
3098   if (NumSignificantBits == 0)
3099     return DAG.getConstant(0, DL, VT);
3100 
3101   // Skip known-zero high parts of the operand.
3102   int64_t OrigBitSize = VT.getSizeInBits();
3103   int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3104   BitSize = std::min(BitSize, OrigBitSize);
3105 
3106   // The POPCNT instruction counts the number of bits in each byte.
3107   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3108   Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3109   Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3110 
3111   // Add up per-byte counts in a binary tree.  All bits of Op at
3112   // position larger than BitSize remain zero throughout.
3113   for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3114     SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3115     if (BitSize != OrigBitSize)
3116       Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3117                         DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3118     Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3119   }
3120 
3121   // Extract overall result from high byte.
3122   if (BitSize > 8)
3123     Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3124                      DAG.getConstant(BitSize - 8, DL, VT));
3125 
3126   return Op;
3127 }
3128 
3129 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3130                                                  SelectionDAG &DAG) const {
3131   SDLoc DL(Op);
3132   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3133     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3134   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
3135     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3136 
3137   // The only fence that needs an instruction is a sequentially-consistent
3138   // cross-thread fence.
3139   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3140       FenceScope == CrossThread) {
3141     return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3142                                       Op.getOperand(0)),
3143                    0);
3144   }
3145 
3146   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3147   return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3148 }
3149 
3150 // Op is an atomic load.  Lower it into a normal volatile load.
3151 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3152                                                 SelectionDAG &DAG) const {
3153   auto *Node = cast<AtomicSDNode>(Op.getNode());
3154   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3155                         Node->getChain(), Node->getBasePtr(),
3156                         Node->getMemoryVT(), Node->getMemOperand());
3157 }
3158 
3159 // Op is an atomic store.  Lower it into a normal volatile store followed
3160 // by a serialization.
3161 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3162                                                  SelectionDAG &DAG) const {
3163   auto *Node = cast<AtomicSDNode>(Op.getNode());
3164   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3165                                     Node->getBasePtr(), Node->getMemoryVT(),
3166                                     Node->getMemOperand());
3167   return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
3168                                     Chain), 0);
3169 }
3170 
3171 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
3172 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3173 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3174                                                    SelectionDAG &DAG,
3175                                                    unsigned Opcode) const {
3176   auto *Node = cast<AtomicSDNode>(Op.getNode());
3177 
3178   // 32-bit operations need no code outside the main loop.
3179   EVT NarrowVT = Node->getMemoryVT();
3180   EVT WideVT = MVT::i32;
3181   if (NarrowVT == WideVT)
3182     return Op;
3183 
3184   int64_t BitSize = NarrowVT.getSizeInBits();
3185   SDValue ChainIn = Node->getChain();
3186   SDValue Addr = Node->getBasePtr();
3187   SDValue Src2 = Node->getVal();
3188   MachineMemOperand *MMO = Node->getMemOperand();
3189   SDLoc DL(Node);
3190   EVT PtrVT = Addr.getValueType();
3191 
3192   // Convert atomic subtracts of constants into additions.
3193   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3194     if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3195       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
3196       Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3197     }
3198 
3199   // Get the address of the containing word.
3200   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3201                                     DAG.getConstant(-4, DL, PtrVT));
3202 
3203   // Get the number of bits that the word must be rotated left in order
3204   // to bring the field to the top bits of a GR32.
3205   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3206                                  DAG.getConstant(3, DL, PtrVT));
3207   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3208 
3209   // Get the complementing shift amount, for rotating a field in the top
3210   // bits back to its proper position.
3211   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3212                                     DAG.getConstant(0, DL, WideVT), BitShift);
3213 
3214   // Extend the source operand to 32 bits and prepare it for the inner loop.
3215   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3216   // operations require the source to be shifted in advance.  (This shift
3217   // can be folded if the source is constant.)  For AND and NAND, the lower
3218   // bits must be set, while for other opcodes they should be left clear.
3219   if (Opcode != SystemZISD::ATOMIC_SWAPW)
3220     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3221                        DAG.getConstant(32 - BitSize, DL, WideVT));
3222   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3223       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
3224     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3225                        DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3226 
3227   // Construct the ATOMIC_LOADW_* node.
3228   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3229   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3230                     DAG.getConstant(BitSize, DL, WideVT) };
3231   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3232                                              NarrowVT, MMO);
3233 
3234   // Rotate the result of the final CS so that the field is in the lower
3235   // bits of a GR32, then truncate it.
3236   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3237                                     DAG.getConstant(BitSize, DL, WideVT));
3238   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3239 
3240   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3241   return DAG.getMergeValues(RetOps, DL);
3242 }
3243 
3244 // Op is an ATOMIC_LOAD_SUB operation.  Lower 8- and 16-bit operations
3245 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3246 // operations into additions.
3247 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3248                                                     SelectionDAG &DAG) const {
3249   auto *Node = cast<AtomicSDNode>(Op.getNode());
3250   EVT MemVT = Node->getMemoryVT();
3251   if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3252     // A full-width operation.
3253     assert(Op.getValueType() == MemVT && "Mismatched VTs");
3254     SDValue Src2 = Node->getVal();
3255     SDValue NegSrc2;
3256     SDLoc DL(Src2);
3257 
3258     if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3259       // Use an addition if the operand is constant and either LAA(G) is
3260       // available or the negative value is in the range of A(G)FHI.
3261       int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3262       if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3263         NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3264     } else if (Subtarget.hasInterlockedAccess1())
3265       // Use LAA(G) if available.
3266       NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3267                             Src2);
3268 
3269     if (NegSrc2.getNode())
3270       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3271                            Node->getChain(), Node->getBasePtr(), NegSrc2,
3272                            Node->getMemOperand(), Node->getOrdering(),
3273                            Node->getSynchScope());
3274 
3275     // Use the node as-is.
3276     return Op;
3277   }
3278 
3279   return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3280 }
3281 
3282 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
3283 // into a fullword ATOMIC_CMP_SWAPW operation.
3284 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3285                                                     SelectionDAG &DAG) const {
3286   auto *Node = cast<AtomicSDNode>(Op.getNode());
3287 
3288   // We have native support for 32-bit compare and swap.
3289   EVT NarrowVT = Node->getMemoryVT();
3290   EVT WideVT = MVT::i32;
3291   if (NarrowVT == WideVT)
3292     return Op;
3293 
3294   int64_t BitSize = NarrowVT.getSizeInBits();
3295   SDValue ChainIn = Node->getOperand(0);
3296   SDValue Addr = Node->getOperand(1);
3297   SDValue CmpVal = Node->getOperand(2);
3298   SDValue SwapVal = Node->getOperand(3);
3299   MachineMemOperand *MMO = Node->getMemOperand();
3300   SDLoc DL(Node);
3301   EVT PtrVT = Addr.getValueType();
3302 
3303   // Get the address of the containing word.
3304   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3305                                     DAG.getConstant(-4, DL, PtrVT));
3306 
3307   // Get the number of bits that the word must be rotated left in order
3308   // to bring the field to the top bits of a GR32.
3309   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3310                                  DAG.getConstant(3, DL, PtrVT));
3311   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3312 
3313   // Get the complementing shift amount, for rotating a field in the top
3314   // bits back to its proper position.
3315   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3316                                     DAG.getConstant(0, DL, WideVT), BitShift);
3317 
3318   // Construct the ATOMIC_CMP_SWAPW node.
3319   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3320   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
3321                     NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
3322   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
3323                                              VTList, Ops, NarrowVT, MMO);
3324   return AtomicOp;
3325 }
3326 
3327 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
3328                                               SelectionDAG &DAG) const {
3329   MachineFunction &MF = DAG.getMachineFunction();
3330   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3331   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
3332                             SystemZ::R15D, Op.getValueType());
3333 }
3334 
3335 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
3336                                                  SelectionDAG &DAG) const {
3337   MachineFunction &MF = DAG.getMachineFunction();
3338   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3339   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
3340                           SystemZ::R15D, Op.getOperand(1));
3341 }
3342 
3343 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
3344                                              SelectionDAG &DAG) const {
3345   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3346   if (!IsData)
3347     // Just preserve the chain.
3348     return Op.getOperand(0);
3349 
3350   SDLoc DL(Op);
3351   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3352   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
3353   auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
3354   SDValue Ops[] = {
3355     Op.getOperand(0),
3356     DAG.getConstant(Code, DL, MVT::i32),
3357     Op.getOperand(1)
3358   };
3359   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
3360                                  Node->getVTList(), Ops,
3361                                  Node->getMemoryVT(), Node->getMemOperand());
3362 }
3363 
3364 // Return an i32 that contains the value of CC immediately after After,
3365 // whose final operand must be MVT::Glue.
3366 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3367   SDLoc DL(After);
3368   SDValue Glue = SDValue(After, After->getNumValues() - 1);
3369   SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3370   return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3371                      DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
3372 }
3373 
3374 SDValue
3375 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3376                                               SelectionDAG &DAG) const {
3377   unsigned Opcode, CCValid;
3378   if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3379     assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3380     SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3381     SDValue CC = getCCResult(DAG, Glued.getNode());
3382     DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3383     return SDValue();
3384   }
3385 
3386   return SDValue();
3387 }
3388 
3389 SDValue
3390 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
3391                                                SelectionDAG &DAG) const {
3392   unsigned Opcode, CCValid;
3393   if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
3394     SDValue Glued = emitIntrinsicWithGlue(DAG, Op, Opcode);
3395     SDValue CC = getCCResult(DAG, Glued.getNode());
3396     if (Op->getNumValues() == 1)
3397       return CC;
3398     assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
3399     return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), Glued,
3400                        CC);
3401   }
3402 
3403   unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3404   switch (Id) {
3405   case Intrinsic::thread_pointer:
3406     return lowerThreadPointer(SDLoc(Op), DAG);
3407 
3408   case Intrinsic::s390_vpdi:
3409     return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
3410                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3411 
3412   case Intrinsic::s390_vperm:
3413     return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
3414                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3415 
3416   case Intrinsic::s390_vuphb:
3417   case Intrinsic::s390_vuphh:
3418   case Intrinsic::s390_vuphf:
3419     return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
3420                        Op.getOperand(1));
3421 
3422   case Intrinsic::s390_vuplhb:
3423   case Intrinsic::s390_vuplhh:
3424   case Intrinsic::s390_vuplhf:
3425     return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
3426                        Op.getOperand(1));
3427 
3428   case Intrinsic::s390_vuplb:
3429   case Intrinsic::s390_vuplhw:
3430   case Intrinsic::s390_vuplf:
3431     return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
3432                        Op.getOperand(1));
3433 
3434   case Intrinsic::s390_vupllb:
3435   case Intrinsic::s390_vupllh:
3436   case Intrinsic::s390_vupllf:
3437     return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
3438                        Op.getOperand(1));
3439 
3440   case Intrinsic::s390_vsumb:
3441   case Intrinsic::s390_vsumh:
3442   case Intrinsic::s390_vsumgh:
3443   case Intrinsic::s390_vsumgf:
3444   case Intrinsic::s390_vsumqf:
3445   case Intrinsic::s390_vsumqg:
3446     return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
3447                        Op.getOperand(1), Op.getOperand(2));
3448   }
3449 
3450   return SDValue();
3451 }
3452 
3453 namespace {
3454 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3455 // of a VPERM with permute vector Bytes.  If Opcode takes three operands,
3456 // Operand is the constant third operand, otherwise it is the number of
3457 // bytes in each element of the result.
3458 struct Permute {
3459   unsigned Opcode;
3460   unsigned Operand;
3461   unsigned char Bytes[SystemZ::VectorBytes];
3462 };
3463 }
3464 
3465 static const Permute PermuteForms[] = {
3466   // VMRHG
3467   { SystemZISD::MERGE_HIGH, 8,
3468     { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3469   // VMRHF
3470   { SystemZISD::MERGE_HIGH, 4,
3471     { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3472   // VMRHH
3473   { SystemZISD::MERGE_HIGH, 2,
3474     { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3475   // VMRHB
3476   { SystemZISD::MERGE_HIGH, 1,
3477     { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3478   // VMRLG
3479   { SystemZISD::MERGE_LOW, 8,
3480     { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3481   // VMRLF
3482   { SystemZISD::MERGE_LOW, 4,
3483     { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3484   // VMRLH
3485   { SystemZISD::MERGE_LOW, 2,
3486     { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3487   // VMRLB
3488   { SystemZISD::MERGE_LOW, 1,
3489     { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3490   // VPKG
3491   { SystemZISD::PACK, 4,
3492     { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3493   // VPKF
3494   { SystemZISD::PACK, 2,
3495     { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3496   // VPKH
3497   { SystemZISD::PACK, 1,
3498     { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3499   // VPDI V1, V2, 4  (low half of V1, high half of V2)
3500   { SystemZISD::PERMUTE_DWORDS, 4,
3501     { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3502   // VPDI V1, V2, 1  (high half of V1, low half of V2)
3503   { SystemZISD::PERMUTE_DWORDS, 1,
3504     { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3505 };
3506 
3507 // Called after matching a vector shuffle against a particular pattern.
3508 // Both the original shuffle and the pattern have two vector operands.
3509 // OpNos[0] is the operand of the original shuffle that should be used for
3510 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3511 // OpNos[1] is the same for operand 1 of the pattern.  Resolve these -1s and
3512 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3513 // for operands 0 and 1 of the pattern.
3514 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3515   if (OpNos[0] < 0) {
3516     if (OpNos[1] < 0)
3517       return false;
3518     OpNo0 = OpNo1 = OpNos[1];
3519   } else if (OpNos[1] < 0) {
3520     OpNo0 = OpNo1 = OpNos[0];
3521   } else {
3522     OpNo0 = OpNos[0];
3523     OpNo1 = OpNos[1];
3524   }
3525   return true;
3526 }
3527 
3528 // Bytes is a VPERM-like permute vector, except that -1 is used for
3529 // undefined bytes.  Return true if the VPERM can be implemented using P.
3530 // When returning true set OpNo0 to the VPERM operand that should be
3531 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3532 //
3533 // For example, if swapping the VPERM operands allows P to match, OpNo0
3534 // will be 1 and OpNo1 will be 0.  If instead Bytes only refers to one
3535 // operand, but rewriting it to use two duplicated operands allows it to
3536 // match P, then OpNo0 and OpNo1 will be the same.
3537 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3538                          unsigned &OpNo0, unsigned &OpNo1) {
3539   int OpNos[] = { -1, -1 };
3540   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3541     int Elt = Bytes[I];
3542     if (Elt >= 0) {
3543       // Make sure that the two permute vectors use the same suboperand
3544       // byte number.  Only the operand numbers (the high bits) are
3545       // allowed to differ.
3546       if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3547         return false;
3548       int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3549       int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3550       // Make sure that the operand mappings are consistent with previous
3551       // elements.
3552       if (OpNos[ModelOpNo] == 1 - RealOpNo)
3553         return false;
3554       OpNos[ModelOpNo] = RealOpNo;
3555     }
3556   }
3557   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3558 }
3559 
3560 // As above, but search for a matching permute.
3561 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3562                                    unsigned &OpNo0, unsigned &OpNo1) {
3563   for (auto &P : PermuteForms)
3564     if (matchPermute(Bytes, P, OpNo0, OpNo1))
3565       return &P;
3566   return nullptr;
3567 }
3568 
3569 // Bytes is a VPERM-like permute vector, except that -1 is used for
3570 // undefined bytes.  This permute is an operand of an outer permute.
3571 // See whether redistributing the -1 bytes gives a shuffle that can be
3572 // implemented using P.  If so, set Transform to a VPERM-like permute vector
3573 // that, when applied to the result of P, gives the original permute in Bytes.
3574 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3575                                const Permute &P,
3576                                SmallVectorImpl<int> &Transform) {
3577   unsigned To = 0;
3578   for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3579     int Elt = Bytes[From];
3580     if (Elt < 0)
3581       // Byte number From of the result is undefined.
3582       Transform[From] = -1;
3583     else {
3584       while (P.Bytes[To] != Elt) {
3585         To += 1;
3586         if (To == SystemZ::VectorBytes)
3587           return false;
3588       }
3589       Transform[From] = To;
3590     }
3591   }
3592   return true;
3593 }
3594 
3595 // As above, but search for a matching permute.
3596 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3597                                          SmallVectorImpl<int> &Transform) {
3598   for (auto &P : PermuteForms)
3599     if (matchDoublePermute(Bytes, P, Transform))
3600       return &P;
3601   return nullptr;
3602 }
3603 
3604 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3605 // as if it had type vNi8.
3606 static void getVPermMask(ShuffleVectorSDNode *VSN,
3607                          SmallVectorImpl<int> &Bytes) {
3608   EVT VT = VSN->getValueType(0);
3609   unsigned NumElements = VT.getVectorNumElements();
3610   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3611   Bytes.resize(NumElements * BytesPerElement, -1);
3612   for (unsigned I = 0; I < NumElements; ++I) {
3613     int Index = VSN->getMaskElt(I);
3614     if (Index >= 0)
3615       for (unsigned J = 0; J < BytesPerElement; ++J)
3616         Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3617   }
3618 }
3619 
3620 // Bytes is a VPERM-like permute vector, except that -1 is used for
3621 // undefined bytes.  See whether bytes [Start, Start + BytesPerElement) of
3622 // the result come from a contiguous sequence of bytes from one input.
3623 // Set Base to the selector for the first byte if so.
3624 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3625                             unsigned BytesPerElement, int &Base) {
3626   Base = -1;
3627   for (unsigned I = 0; I < BytesPerElement; ++I) {
3628     if (Bytes[Start + I] >= 0) {
3629       unsigned Elem = Bytes[Start + I];
3630       if (Base < 0) {
3631         Base = Elem - I;
3632         // Make sure the bytes would come from one input operand.
3633         if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3634           return false;
3635       } else if (unsigned(Base) != Elem - I)
3636         return false;
3637     }
3638   }
3639   return true;
3640 }
3641 
3642 // Bytes is a VPERM-like permute vector, except that -1 is used for
3643 // undefined bytes.  Return true if it can be performed using VSLDI.
3644 // When returning true, set StartIndex to the shift amount and OpNo0
3645 // and OpNo1 to the VPERM operands that should be used as the first
3646 // and second shift operand respectively.
3647 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3648                                unsigned &StartIndex, unsigned &OpNo0,
3649                                unsigned &OpNo1) {
3650   int OpNos[] = { -1, -1 };
3651   int Shift = -1;
3652   for (unsigned I = 0; I < 16; ++I) {
3653     int Index = Bytes[I];
3654     if (Index >= 0) {
3655       int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3656       int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3657       int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3658       if (Shift < 0)
3659         Shift = ExpectedShift;
3660       else if (Shift != ExpectedShift)
3661         return false;
3662       // Make sure that the operand mappings are consistent with previous
3663       // elements.
3664       if (OpNos[ModelOpNo] == 1 - RealOpNo)
3665         return false;
3666       OpNos[ModelOpNo] = RealOpNo;
3667     }
3668   }
3669   StartIndex = Shift;
3670   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3671 }
3672 
3673 // Create a node that performs P on operands Op0 and Op1, casting the
3674 // operands to the appropriate type.  The type of the result is determined by P.
3675 static SDValue getPermuteNode(SelectionDAG &DAG, SDLoc DL,
3676                               const Permute &P, SDValue Op0, SDValue Op1) {
3677   // VPDI (PERMUTE_DWORDS) always operates on v2i64s.  The input
3678   // elements of a PACK are twice as wide as the outputs.
3679   unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3680                       P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3681                       P.Operand);
3682   // Cast both operands to the appropriate type.
3683   MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3684                               SystemZ::VectorBytes / InBytes);
3685   Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3686   Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3687   SDValue Op;
3688   if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3689     SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3690     Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3691   } else if (P.Opcode == SystemZISD::PACK) {
3692     MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3693                                  SystemZ::VectorBytes / P.Operand);
3694     Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3695   } else {
3696     Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3697   }
3698   return Op;
3699 }
3700 
3701 // Bytes is a VPERM-like permute vector, except that -1 is used for
3702 // undefined bytes.  Implement it on operands Ops[0] and Ops[1] using
3703 // VSLDI or VPERM.
3704 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, SDLoc DL, SDValue *Ops,
3705                                      const SmallVectorImpl<int> &Bytes) {
3706   for (unsigned I = 0; I < 2; ++I)
3707     Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3708 
3709   // First see whether VSLDI can be used.
3710   unsigned StartIndex, OpNo0, OpNo1;
3711   if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3712     return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3713                        Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3714 
3715   // Fall back on VPERM.  Construct an SDNode for the permute vector.
3716   SDValue IndexNodes[SystemZ::VectorBytes];
3717   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3718     if (Bytes[I] >= 0)
3719       IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3720     else
3721       IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3722   SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
3723   return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3724 }
3725 
3726 namespace {
3727 // Describes a general N-operand vector shuffle.
3728 struct GeneralShuffle {
3729   GeneralShuffle(EVT vt) : VT(vt) {}
3730   void addUndef();
3731   void add(SDValue, unsigned);
3732   SDValue getNode(SelectionDAG &, SDLoc);
3733 
3734   // The operands of the shuffle.
3735   SmallVector<SDValue, SystemZ::VectorBytes> Ops;
3736 
3737   // Index I is -1 if byte I of the result is undefined.  Otherwise the
3738   // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3739   // Bytes[I] / SystemZ::VectorBytes.
3740   SmallVector<int, SystemZ::VectorBytes> Bytes;
3741 
3742   // The type of the shuffle result.
3743   EVT VT;
3744 };
3745 }
3746 
3747 // Add an extra undefined element to the shuffle.
3748 void GeneralShuffle::addUndef() {
3749   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3750   for (unsigned I = 0; I < BytesPerElement; ++I)
3751     Bytes.push_back(-1);
3752 }
3753 
3754 // Add an extra element to the shuffle, taking it from element Elem of Op.
3755 // A null Op indicates a vector input whose value will be calculated later;
3756 // there is at most one such input per shuffle and it always has the same
3757 // type as the result.
3758 void GeneralShuffle::add(SDValue Op, unsigned Elem) {
3759   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3760 
3761   // The source vector can have wider elements than the result,
3762   // either through an explicit TRUNCATE or because of type legalization.
3763   // We want the least significant part.
3764   EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3765   unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3766   assert(FromBytesPerElement >= BytesPerElement &&
3767          "Invalid EXTRACT_VECTOR_ELT");
3768   unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3769                    (FromBytesPerElement - BytesPerElement));
3770 
3771   // Look through things like shuffles and bitcasts.
3772   while (Op.getNode()) {
3773     if (Op.getOpcode() == ISD::BITCAST)
3774       Op = Op.getOperand(0);
3775     else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3776       // See whether the bytes we need come from a contiguous part of one
3777       // operand.
3778       SmallVector<int, SystemZ::VectorBytes> OpBytes;
3779       getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3780       int NewByte;
3781       if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3782         break;
3783       if (NewByte < 0) {
3784         addUndef();
3785         return;
3786       }
3787       Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3788       Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3789     } else if (Op.isUndef()) {
3790       addUndef();
3791       return;
3792     } else
3793       break;
3794   }
3795 
3796   // Make sure that the source of the extraction is in Ops.
3797   unsigned OpNo = 0;
3798   for (; OpNo < Ops.size(); ++OpNo)
3799     if (Ops[OpNo] == Op)
3800       break;
3801   if (OpNo == Ops.size())
3802     Ops.push_back(Op);
3803 
3804   // Add the element to Bytes.
3805   unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3806   for (unsigned I = 0; I < BytesPerElement; ++I)
3807     Bytes.push_back(Base + I);
3808 }
3809 
3810 // Return SDNodes for the completed shuffle.
3811 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, SDLoc DL) {
3812   assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3813 
3814   if (Ops.size() == 0)
3815     return DAG.getUNDEF(VT);
3816 
3817   // Make sure that there are at least two shuffle operands.
3818   if (Ops.size() == 1)
3819     Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3820 
3821   // Create a tree of shuffles, deferring root node until after the loop.
3822   // Try to redistribute the undefined elements of non-root nodes so that
3823   // the non-root shuffles match something like a pack or merge, then adjust
3824   // the parent node's permute vector to compensate for the new order.
3825   // Among other things, this copes with vectors like <2 x i16> that were
3826   // padded with undefined elements during type legalization.
3827   //
3828   // In the best case this redistribution will lead to the whole tree
3829   // using packs and merges.  It should rarely be a loss in other cases.
3830   unsigned Stride = 1;
3831   for (; Stride * 2 < Ops.size(); Stride *= 2) {
3832     for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3833       SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3834 
3835       // Create a mask for just these two operands.
3836       SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
3837       for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3838         unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3839         unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3840         if (OpNo == I)
3841           NewBytes[J] = Byte;
3842         else if (OpNo == I + Stride)
3843           NewBytes[J] = SystemZ::VectorBytes + Byte;
3844         else
3845           NewBytes[J] = -1;
3846       }
3847       // See if it would be better to reorganize NewMask to avoid using VPERM.
3848       SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
3849       if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
3850         Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
3851         // Applying NewBytesMap to Ops[I] gets back to NewBytes.
3852         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3853           if (NewBytes[J] >= 0) {
3854             assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
3855                    "Invalid double permute");
3856             Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
3857           } else
3858             assert(NewBytesMap[J] < 0 && "Invalid double permute");
3859         }
3860       } else {
3861         // Just use NewBytes on the operands.
3862         Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
3863         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
3864           if (NewBytes[J] >= 0)
3865             Bytes[J] = I * SystemZ::VectorBytes + J;
3866       }
3867     }
3868   }
3869 
3870   // Now we just have 2 inputs.  Put the second operand in Ops[1].
3871   if (Stride > 1) {
3872     Ops[1] = Ops[Stride];
3873     for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3874       if (Bytes[I] >= int(SystemZ::VectorBytes))
3875         Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
3876   }
3877 
3878   // Look for an instruction that can do the permute without resorting
3879   // to VPERM.
3880   unsigned OpNo0, OpNo1;
3881   SDValue Op;
3882   if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
3883     Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
3884   else
3885     Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
3886   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3887 }
3888 
3889 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
3890 static bool isScalarToVector(SDValue Op) {
3891   for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
3892     if (!Op.getOperand(I).isUndef())
3893       return false;
3894   return true;
3895 }
3896 
3897 // Return a vector of type VT that contains Value in the first element.
3898 // The other elements don't matter.
3899 static SDValue buildScalarToVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3900                                    SDValue Value) {
3901   // If we have a constant, replicate it to all elements and let the
3902   // BUILD_VECTOR lowering take care of it.
3903   if (Value.getOpcode() == ISD::Constant ||
3904       Value.getOpcode() == ISD::ConstantFP) {
3905     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
3906     return DAG.getBuildVector(VT, DL, Ops);
3907   }
3908   if (Value.isUndef())
3909     return DAG.getUNDEF(VT);
3910   return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
3911 }
3912 
3913 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
3914 // element 1.  Used for cases in which replication is cheap.
3915 static SDValue buildMergeScalars(SelectionDAG &DAG, SDLoc DL, EVT VT,
3916                                  SDValue Op0, SDValue Op1) {
3917   if (Op0.isUndef()) {
3918     if (Op1.isUndef())
3919       return DAG.getUNDEF(VT);
3920     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
3921   }
3922   if (Op1.isUndef())
3923     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
3924   return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
3925                      buildScalarToVector(DAG, DL, VT, Op0),
3926                      buildScalarToVector(DAG, DL, VT, Op1));
3927 }
3928 
3929 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
3930 // vector for them.
3931 static SDValue joinDwords(SelectionDAG &DAG, SDLoc DL, SDValue Op0,
3932                           SDValue Op1) {
3933   if (Op0.isUndef() && Op1.isUndef())
3934     return DAG.getUNDEF(MVT::v2i64);
3935   // If one of the two inputs is undefined then replicate the other one,
3936   // in order to avoid using another register unnecessarily.
3937   if (Op0.isUndef())
3938     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3939   else if (Op1.isUndef())
3940     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3941   else {
3942     Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3943     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3944   }
3945   return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
3946 }
3947 
3948 // Try to represent constant BUILD_VECTOR node BVN using a
3949 // SystemZISD::BYTE_MASK-style mask.  Store the mask value in Mask
3950 // on success.
3951 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
3952   EVT ElemVT = BVN->getValueType(0).getVectorElementType();
3953   unsigned BytesPerElement = ElemVT.getStoreSize();
3954   for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
3955     SDValue Op = BVN->getOperand(I);
3956     if (!Op.isUndef()) {
3957       uint64_t Value;
3958       if (Op.getOpcode() == ISD::Constant)
3959         Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
3960       else if (Op.getOpcode() == ISD::ConstantFP)
3961         Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
3962                  .getZExtValue());
3963       else
3964         return false;
3965       for (unsigned J = 0; J < BytesPerElement; ++J) {
3966         uint64_t Byte = (Value >> (J * 8)) & 0xff;
3967         if (Byte == 0xff)
3968           Mask |= 1ULL << ((E - I - 1) * BytesPerElement + J);
3969         else if (Byte != 0)
3970           return false;
3971       }
3972     }
3973   }
3974   return true;
3975 }
3976 
3977 // Try to load a vector constant in which BitsPerElement-bit value Value
3978 // is replicated to fill the vector.  VT is the type of the resulting
3979 // constant, which may have elements of a different size from BitsPerElement.
3980 // Return the SDValue of the constant on success, otherwise return
3981 // an empty value.
3982 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG,
3983                                        const SystemZInstrInfo *TII,
3984                                        SDLoc DL, EVT VT, uint64_t Value,
3985                                        unsigned BitsPerElement) {
3986   // Signed 16-bit values can be replicated using VREPI.
3987   int64_t SignedValue = SignExtend64(Value, BitsPerElement);
3988   if (isInt<16>(SignedValue)) {
3989     MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3990                                  SystemZ::VectorBits / BitsPerElement);
3991     SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
3992                              DAG.getConstant(SignedValue, DL, MVT::i32));
3993     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3994   }
3995   // See whether rotating the constant left some N places gives a value that
3996   // is one less than a power of 2 (i.e. all zeros followed by all ones).
3997   // If so we can use VGM.
3998   unsigned Start, End;
3999   if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
4000     // isRxSBGMask returns the bit numbers for a full 64-bit value,
4001     // with 0 denoting 1 << 63 and 63 denoting 1.  Convert them to
4002     // bit numbers for an BitsPerElement value, so that 0 denotes
4003     // 1 << (BitsPerElement-1).
4004     Start -= 64 - BitsPerElement;
4005     End -= 64 - BitsPerElement;
4006     MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4007                                  SystemZ::VectorBits / BitsPerElement);
4008     SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
4009                              DAG.getConstant(Start, DL, MVT::i32),
4010                              DAG.getConstant(End, DL, MVT::i32));
4011     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4012   }
4013   return SDValue();
4014 }
4015 
4016 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4017 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4018 // the non-EXTRACT_VECTOR_ELT elements.  See if the given BUILD_VECTOR
4019 // would benefit from this representation and return it if so.
4020 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
4021                                      BuildVectorSDNode *BVN) {
4022   EVT VT = BVN->getValueType(0);
4023   unsigned NumElements = VT.getVectorNumElements();
4024 
4025   // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4026   // on byte vectors.  If there are non-EXTRACT_VECTOR_ELT elements that still
4027   // need a BUILD_VECTOR, add an additional placeholder operand for that
4028   // BUILD_VECTOR and store its operands in ResidueOps.
4029   GeneralShuffle GS(VT);
4030   SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
4031   bool FoundOne = false;
4032   for (unsigned I = 0; I < NumElements; ++I) {
4033     SDValue Op = BVN->getOperand(I);
4034     if (Op.getOpcode() == ISD::TRUNCATE)
4035       Op = Op.getOperand(0);
4036     if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4037         Op.getOperand(1).getOpcode() == ISD::Constant) {
4038       unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4039       GS.add(Op.getOperand(0), Elem);
4040       FoundOne = true;
4041     } else if (Op.isUndef()) {
4042       GS.addUndef();
4043     } else {
4044       GS.add(SDValue(), ResidueOps.size());
4045       ResidueOps.push_back(BVN->getOperand(I));
4046     }
4047   }
4048 
4049   // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4050   if (!FoundOne)
4051     return SDValue();
4052 
4053   // Create the BUILD_VECTOR for the remaining elements, if any.
4054   if (!ResidueOps.empty()) {
4055     while (ResidueOps.size() < NumElements)
4056       ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4057     for (auto &Op : GS.Ops) {
4058       if (!Op.getNode()) {
4059         Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4060         break;
4061       }
4062     }
4063   }
4064   return GS.getNode(DAG, SDLoc(BVN));
4065 }
4066 
4067 // Combine GPR scalar values Elems into a vector of type VT.
4068 static SDValue buildVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
4069                            SmallVectorImpl<SDValue> &Elems) {
4070   // See whether there is a single replicated value.
4071   SDValue Single;
4072   unsigned int NumElements = Elems.size();
4073   unsigned int Count = 0;
4074   for (auto Elem : Elems) {
4075     if (!Elem.isUndef()) {
4076       if (!Single.getNode())
4077         Single = Elem;
4078       else if (Elem != Single) {
4079         Single = SDValue();
4080         break;
4081       }
4082       Count += 1;
4083     }
4084   }
4085   // There are three cases here:
4086   //
4087   // - if the only defined element is a loaded one, the best sequence
4088   //   is a replicating load.
4089   //
4090   // - otherwise, if the only defined element is an i64 value, we will
4091   //   end up with the same VLVGP sequence regardless of whether we short-cut
4092   //   for replication or fall through to the later code.
4093   //
4094   // - otherwise, if the only defined element is an i32 or smaller value,
4095   //   we would need 2 instructions to replicate it: VLVGP followed by VREPx.
4096   //   This is only a win if the single defined element is used more than once.
4097   //   In other cases we're better off using a single VLVGx.
4098   if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
4099     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
4100 
4101   // The best way of building a v2i64 from two i64s is to use VLVGP.
4102   if (VT == MVT::v2i64)
4103     return joinDwords(DAG, DL, Elems[0], Elems[1]);
4104 
4105   // Use a 64-bit merge high to combine two doubles.
4106   if (VT == MVT::v2f64)
4107     return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4108 
4109   // Build v4f32 values directly from the FPRs:
4110   //
4111   //   <Axxx> <Bxxx> <Cxxxx> <Dxxx>
4112   //         V              V         VMRHF
4113   //      <ABxx>         <CDxx>
4114   //                V                 VMRHG
4115   //              <ABCD>
4116   if (VT == MVT::v4f32) {
4117     SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4118     SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
4119     // Avoid unnecessary undefs by reusing the other operand.
4120     if (Op01.isUndef())
4121       Op01 = Op23;
4122     else if (Op23.isUndef())
4123       Op23 = Op01;
4124     // Merging identical replications is a no-op.
4125     if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
4126       return Op01;
4127     Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
4128     Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
4129     SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
4130                              DL, MVT::v2i64, Op01, Op23);
4131     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4132   }
4133 
4134   // Collect the constant terms.
4135   SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
4136   SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
4137 
4138   unsigned NumConstants = 0;
4139   for (unsigned I = 0; I < NumElements; ++I) {
4140     SDValue Elem = Elems[I];
4141     if (Elem.getOpcode() == ISD::Constant ||
4142         Elem.getOpcode() == ISD::ConstantFP) {
4143       NumConstants += 1;
4144       Constants[I] = Elem;
4145       Done[I] = true;
4146     }
4147   }
4148   // If there was at least one constant, fill in the other elements of
4149   // Constants with undefs to get a full vector constant and use that
4150   // as the starting point.
4151   SDValue Result;
4152   if (NumConstants > 0) {
4153     for (unsigned I = 0; I < NumElements; ++I)
4154       if (!Constants[I].getNode())
4155         Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4156     Result = DAG.getBuildVector(VT, DL, Constants);
4157   } else {
4158     // Otherwise try to use VLVGP to start the sequence in order to
4159     // avoid a false dependency on any previous contents of the vector
4160     // register.  This only makes sense if one of the associated elements
4161     // is defined.
4162     unsigned I1 = NumElements / 2 - 1;
4163     unsigned I2 = NumElements - 1;
4164     bool Def1 = !Elems[I1].isUndef();
4165     bool Def2 = !Elems[I2].isUndef();
4166     if (Def1 || Def2) {
4167       SDValue Elem1 = Elems[Def1 ? I1 : I2];
4168       SDValue Elem2 = Elems[Def2 ? I2 : I1];
4169       Result = DAG.getNode(ISD::BITCAST, DL, VT,
4170                            joinDwords(DAG, DL, Elem1, Elem2));
4171       Done[I1] = true;
4172       Done[I2] = true;
4173     } else
4174       Result = DAG.getUNDEF(VT);
4175   }
4176 
4177   // Use VLVGx to insert the other elements.
4178   for (unsigned I = 0; I < NumElements; ++I)
4179     if (!Done[I] && !Elems[I].isUndef())
4180       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4181                            DAG.getConstant(I, DL, MVT::i32));
4182   return Result;
4183 }
4184 
4185 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4186                                                  SelectionDAG &DAG) const {
4187   const SystemZInstrInfo *TII =
4188     static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4189   auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4190   SDLoc DL(Op);
4191   EVT VT = Op.getValueType();
4192 
4193   if (BVN->isConstant()) {
4194     // Try using VECTOR GENERATE BYTE MASK.  This is the architecturally-
4195     // preferred way of creating all-zero and all-one vectors so give it
4196     // priority over other methods below.
4197     uint64_t Mask = 0;
4198     if (tryBuildVectorByteMask(BVN, Mask)) {
4199       SDValue Op = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
4200                                DAG.getConstant(Mask, DL, MVT::i32));
4201       return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4202     }
4203 
4204     // Try using some form of replication.
4205     APInt SplatBits, SplatUndef;
4206     unsigned SplatBitSize;
4207     bool HasAnyUndefs;
4208     if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4209                              8, true) &&
4210         SplatBitSize <= 64) {
4211       // First try assuming that any undefined bits above the highest set bit
4212       // and below the lowest set bit are 1s.  This increases the likelihood of
4213       // being able to use a sign-extended element value in VECTOR REPLICATE
4214       // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
4215       uint64_t SplatBitsZ = SplatBits.getZExtValue();
4216       uint64_t SplatUndefZ = SplatUndef.getZExtValue();
4217       uint64_t Lower = (SplatUndefZ
4218                         & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
4219       uint64_t Upper = (SplatUndefZ
4220                         & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
4221       uint64_t Value = SplatBitsZ | Upper | Lower;
4222       SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
4223                                            SplatBitSize);
4224       if (Op.getNode())
4225         return Op;
4226 
4227       // Now try assuming that any undefined bits between the first and
4228       // last defined set bits are set.  This increases the chances of
4229       // using a non-wraparound mask.
4230       uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
4231       Value = SplatBitsZ | Middle;
4232       Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
4233       if (Op.getNode())
4234         return Op;
4235     }
4236 
4237     // Fall back to loading it from memory.
4238     return SDValue();
4239   }
4240 
4241   // See if we should use shuffles to construct the vector from other vectors.
4242   if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
4243     return Res;
4244 
4245   // Detect SCALAR_TO_VECTOR conversions.
4246   if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
4247     return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4248 
4249   // Otherwise use buildVector to build the vector up from GPRs.
4250   unsigned NumElements = Op.getNumOperands();
4251   SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
4252   for (unsigned I = 0; I < NumElements; ++I)
4253     Ops[I] = Op.getOperand(I);
4254   return buildVector(DAG, DL, VT, Ops);
4255 }
4256 
4257 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4258                                                    SelectionDAG &DAG) const {
4259   auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4260   SDLoc DL(Op);
4261   EVT VT = Op.getValueType();
4262   unsigned NumElements = VT.getVectorNumElements();
4263 
4264   if (VSN->isSplat()) {
4265     SDValue Op0 = Op.getOperand(0);
4266     unsigned Index = VSN->getSplatIndex();
4267     assert(Index < VT.getVectorNumElements() &&
4268            "Splat index should be defined and in first operand");
4269     // See whether the value we're splatting is directly available as a scalar.
4270     if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4271         Op0.getOpcode() == ISD::BUILD_VECTOR)
4272       return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4273     // Otherwise keep it as a vector-to-vector operation.
4274     return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4275                        DAG.getConstant(Index, DL, MVT::i32));
4276   }
4277 
4278   GeneralShuffle GS(VT);
4279   for (unsigned I = 0; I < NumElements; ++I) {
4280     int Elt = VSN->getMaskElt(I);
4281     if (Elt < 0)
4282       GS.addUndef();
4283     else
4284       GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4285              unsigned(Elt) % NumElements);
4286   }
4287   return GS.getNode(DAG, SDLoc(VSN));
4288 }
4289 
4290 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4291                                                      SelectionDAG &DAG) const {
4292   SDLoc DL(Op);
4293   // Just insert the scalar into element 0 of an undefined vector.
4294   return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4295                      Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4296                      Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4297 }
4298 
4299 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4300                                                       SelectionDAG &DAG) const {
4301   // Handle insertions of floating-point values.
4302   SDLoc DL(Op);
4303   SDValue Op0 = Op.getOperand(0);
4304   SDValue Op1 = Op.getOperand(1);
4305   SDValue Op2 = Op.getOperand(2);
4306   EVT VT = Op.getValueType();
4307 
4308   // Insertions into constant indices of a v2f64 can be done using VPDI.
4309   // However, if the inserted value is a bitcast or a constant then it's
4310   // better to use GPRs, as below.
4311   if (VT == MVT::v2f64 &&
4312       Op1.getOpcode() != ISD::BITCAST &&
4313       Op1.getOpcode() != ISD::ConstantFP &&
4314       Op2.getOpcode() == ISD::Constant) {
4315     uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
4316     unsigned Mask = VT.getVectorNumElements() - 1;
4317     if (Index <= Mask)
4318       return Op;
4319   }
4320 
4321   // Otherwise bitcast to the equivalent integer form and insert via a GPR.
4322   MVT IntVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
4323   MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
4324   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
4325                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
4326                             DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
4327   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4328 }
4329 
4330 SDValue
4331 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4332                                                SelectionDAG &DAG) const {
4333   // Handle extractions of floating-point values.
4334   SDLoc DL(Op);
4335   SDValue Op0 = Op.getOperand(0);
4336   SDValue Op1 = Op.getOperand(1);
4337   EVT VT = Op.getValueType();
4338   EVT VecVT = Op0.getValueType();
4339 
4340   // Extractions of constant indices can be done directly.
4341   if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
4342     uint64_t Index = CIndexN->getZExtValue();
4343     unsigned Mask = VecVT.getVectorNumElements() - 1;
4344     if (Index <= Mask)
4345       return Op;
4346   }
4347 
4348   // Otherwise bitcast to the equivalent integer form and extract via a GPR.
4349   MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
4350   MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
4351   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
4352                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
4353   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4354 }
4355 
4356 SDValue
4357 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
4358                                               unsigned UnpackHigh) const {
4359   SDValue PackedOp = Op.getOperand(0);
4360   EVT OutVT = Op.getValueType();
4361   EVT InVT = PackedOp.getValueType();
4362   unsigned ToBits = OutVT.getVectorElementType().getSizeInBits();
4363   unsigned FromBits = InVT.getVectorElementType().getSizeInBits();
4364   do {
4365     FromBits *= 2;
4366     EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
4367                                  SystemZ::VectorBits / FromBits);
4368     PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
4369   } while (FromBits != ToBits);
4370   return PackedOp;
4371 }
4372 
4373 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
4374                                           unsigned ByScalar) const {
4375   // Look for cases where a vector shift can use the *_BY_SCALAR form.
4376   SDValue Op0 = Op.getOperand(0);
4377   SDValue Op1 = Op.getOperand(1);
4378   SDLoc DL(Op);
4379   EVT VT = Op.getValueType();
4380   unsigned ElemBitSize = VT.getVectorElementType().getSizeInBits();
4381 
4382   // See whether the shift vector is a splat represented as BUILD_VECTOR.
4383   if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
4384     APInt SplatBits, SplatUndef;
4385     unsigned SplatBitSize;
4386     bool HasAnyUndefs;
4387     // Check for constant splats.  Use ElemBitSize as the minimum element
4388     // width and reject splats that need wider elements.
4389     if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4390                              ElemBitSize, true) &&
4391         SplatBitSize == ElemBitSize) {
4392       SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
4393                                       DL, MVT::i32);
4394       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4395     }
4396     // Check for variable splats.
4397     BitVector UndefElements;
4398     SDValue Splat = BVN->getSplatValue(&UndefElements);
4399     if (Splat) {
4400       // Since i32 is the smallest legal type, we either need a no-op
4401       // or a truncation.
4402       SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
4403       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4404     }
4405   }
4406 
4407   // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
4408   // and the shift amount is directly available in a GPR.
4409   if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
4410     if (VSN->isSplat()) {
4411       SDValue VSNOp0 = VSN->getOperand(0);
4412       unsigned Index = VSN->getSplatIndex();
4413       assert(Index < VT.getVectorNumElements() &&
4414              "Splat index should be defined and in first operand");
4415       if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4416           VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
4417         // Since i32 is the smallest legal type, we either need a no-op
4418         // or a truncation.
4419         SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
4420                                     VSNOp0.getOperand(Index));
4421         return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4422       }
4423     }
4424   }
4425 
4426   // Otherwise just treat the current form as legal.
4427   return Op;
4428 }
4429 
4430 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
4431                                               SelectionDAG &DAG) const {
4432   switch (Op.getOpcode()) {
4433   case ISD::FRAMEADDR:
4434     return lowerFRAMEADDR(Op, DAG);
4435   case ISD::RETURNADDR:
4436     return lowerRETURNADDR(Op, DAG);
4437   case ISD::BR_CC:
4438     return lowerBR_CC(Op, DAG);
4439   case ISD::SELECT_CC:
4440     return lowerSELECT_CC(Op, DAG);
4441   case ISD::SETCC:
4442     return lowerSETCC(Op, DAG);
4443   case ISD::GlobalAddress:
4444     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
4445   case ISD::GlobalTLSAddress:
4446     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
4447   case ISD::BlockAddress:
4448     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
4449   case ISD::JumpTable:
4450     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
4451   case ISD::ConstantPool:
4452     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
4453   case ISD::BITCAST:
4454     return lowerBITCAST(Op, DAG);
4455   case ISD::VASTART:
4456     return lowerVASTART(Op, DAG);
4457   case ISD::VACOPY:
4458     return lowerVACOPY(Op, DAG);
4459   case ISD::DYNAMIC_STACKALLOC:
4460     return lowerDYNAMIC_STACKALLOC(Op, DAG);
4461   case ISD::SMUL_LOHI:
4462     return lowerSMUL_LOHI(Op, DAG);
4463   case ISD::UMUL_LOHI:
4464     return lowerUMUL_LOHI(Op, DAG);
4465   case ISD::SDIVREM:
4466     return lowerSDIVREM(Op, DAG);
4467   case ISD::UDIVREM:
4468     return lowerUDIVREM(Op, DAG);
4469   case ISD::OR:
4470     return lowerOR(Op, DAG);
4471   case ISD::CTPOP:
4472     return lowerCTPOP(Op, DAG);
4473   case ISD::ATOMIC_FENCE:
4474     return lowerATOMIC_FENCE(Op, DAG);
4475   case ISD::ATOMIC_SWAP:
4476     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
4477   case ISD::ATOMIC_STORE:
4478     return lowerATOMIC_STORE(Op, DAG);
4479   case ISD::ATOMIC_LOAD:
4480     return lowerATOMIC_LOAD(Op, DAG);
4481   case ISD::ATOMIC_LOAD_ADD:
4482     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
4483   case ISD::ATOMIC_LOAD_SUB:
4484     return lowerATOMIC_LOAD_SUB(Op, DAG);
4485   case ISD::ATOMIC_LOAD_AND:
4486     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
4487   case ISD::ATOMIC_LOAD_OR:
4488     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
4489   case ISD::ATOMIC_LOAD_XOR:
4490     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
4491   case ISD::ATOMIC_LOAD_NAND:
4492     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
4493   case ISD::ATOMIC_LOAD_MIN:
4494     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
4495   case ISD::ATOMIC_LOAD_MAX:
4496     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
4497   case ISD::ATOMIC_LOAD_UMIN:
4498     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
4499   case ISD::ATOMIC_LOAD_UMAX:
4500     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
4501   case ISD::ATOMIC_CMP_SWAP:
4502     return lowerATOMIC_CMP_SWAP(Op, DAG);
4503   case ISD::STACKSAVE:
4504     return lowerSTACKSAVE(Op, DAG);
4505   case ISD::STACKRESTORE:
4506     return lowerSTACKRESTORE(Op, DAG);
4507   case ISD::PREFETCH:
4508     return lowerPREFETCH(Op, DAG);
4509   case ISD::INTRINSIC_W_CHAIN:
4510     return lowerINTRINSIC_W_CHAIN(Op, DAG);
4511   case ISD::INTRINSIC_WO_CHAIN:
4512     return lowerINTRINSIC_WO_CHAIN(Op, DAG);
4513   case ISD::BUILD_VECTOR:
4514     return lowerBUILD_VECTOR(Op, DAG);
4515   case ISD::VECTOR_SHUFFLE:
4516     return lowerVECTOR_SHUFFLE(Op, DAG);
4517   case ISD::SCALAR_TO_VECTOR:
4518     return lowerSCALAR_TO_VECTOR(Op, DAG);
4519   case ISD::INSERT_VECTOR_ELT:
4520     return lowerINSERT_VECTOR_ELT(Op, DAG);
4521   case ISD::EXTRACT_VECTOR_ELT:
4522     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4523   case ISD::SIGN_EXTEND_VECTOR_INREG:
4524     return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
4525   case ISD::ZERO_EXTEND_VECTOR_INREG:
4526     return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
4527   case ISD::SHL:
4528     return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
4529   case ISD::SRL:
4530     return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
4531   case ISD::SRA:
4532     return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
4533   default:
4534     llvm_unreachable("Unexpected node to lower");
4535   }
4536 }
4537 
4538 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
4539 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
4540   switch ((SystemZISD::NodeType)Opcode) {
4541     case SystemZISD::FIRST_NUMBER: break;
4542     OPCODE(RET_FLAG);
4543     OPCODE(CALL);
4544     OPCODE(SIBCALL);
4545     OPCODE(TLS_GDCALL);
4546     OPCODE(TLS_LDCALL);
4547     OPCODE(PCREL_WRAPPER);
4548     OPCODE(PCREL_OFFSET);
4549     OPCODE(IABS);
4550     OPCODE(ICMP);
4551     OPCODE(FCMP);
4552     OPCODE(TM);
4553     OPCODE(BR_CCMASK);
4554     OPCODE(SELECT_CCMASK);
4555     OPCODE(ADJDYNALLOC);
4556     OPCODE(EXTRACT_ACCESS);
4557     OPCODE(POPCNT);
4558     OPCODE(UMUL_LOHI64);
4559     OPCODE(SDIVREM32);
4560     OPCODE(SDIVREM64);
4561     OPCODE(UDIVREM32);
4562     OPCODE(UDIVREM64);
4563     OPCODE(MVC);
4564     OPCODE(MVC_LOOP);
4565     OPCODE(NC);
4566     OPCODE(NC_LOOP);
4567     OPCODE(OC);
4568     OPCODE(OC_LOOP);
4569     OPCODE(XC);
4570     OPCODE(XC_LOOP);
4571     OPCODE(CLC);
4572     OPCODE(CLC_LOOP);
4573     OPCODE(STPCPY);
4574     OPCODE(STRCMP);
4575     OPCODE(SEARCH_STRING);
4576     OPCODE(IPM);
4577     OPCODE(SERIALIZE);
4578     OPCODE(MEMBARRIER);
4579     OPCODE(TBEGIN);
4580     OPCODE(TBEGIN_NOFLOAT);
4581     OPCODE(TEND);
4582     OPCODE(BYTE_MASK);
4583     OPCODE(ROTATE_MASK);
4584     OPCODE(REPLICATE);
4585     OPCODE(JOIN_DWORDS);
4586     OPCODE(SPLAT);
4587     OPCODE(MERGE_HIGH);
4588     OPCODE(MERGE_LOW);
4589     OPCODE(SHL_DOUBLE);
4590     OPCODE(PERMUTE_DWORDS);
4591     OPCODE(PERMUTE);
4592     OPCODE(PACK);
4593     OPCODE(PACKS_CC);
4594     OPCODE(PACKLS_CC);
4595     OPCODE(UNPACK_HIGH);
4596     OPCODE(UNPACKL_HIGH);
4597     OPCODE(UNPACK_LOW);
4598     OPCODE(UNPACKL_LOW);
4599     OPCODE(VSHL_BY_SCALAR);
4600     OPCODE(VSRL_BY_SCALAR);
4601     OPCODE(VSRA_BY_SCALAR);
4602     OPCODE(VSUM);
4603     OPCODE(VICMPE);
4604     OPCODE(VICMPH);
4605     OPCODE(VICMPHL);
4606     OPCODE(VICMPES);
4607     OPCODE(VICMPHS);
4608     OPCODE(VICMPHLS);
4609     OPCODE(VFCMPE);
4610     OPCODE(VFCMPH);
4611     OPCODE(VFCMPHE);
4612     OPCODE(VFCMPES);
4613     OPCODE(VFCMPHS);
4614     OPCODE(VFCMPHES);
4615     OPCODE(VFTCI);
4616     OPCODE(VEXTEND);
4617     OPCODE(VROUND);
4618     OPCODE(VTM);
4619     OPCODE(VFAE_CC);
4620     OPCODE(VFAEZ_CC);
4621     OPCODE(VFEE_CC);
4622     OPCODE(VFEEZ_CC);
4623     OPCODE(VFENE_CC);
4624     OPCODE(VFENEZ_CC);
4625     OPCODE(VISTR_CC);
4626     OPCODE(VSTRC_CC);
4627     OPCODE(VSTRCZ_CC);
4628     OPCODE(ATOMIC_SWAPW);
4629     OPCODE(ATOMIC_LOADW_ADD);
4630     OPCODE(ATOMIC_LOADW_SUB);
4631     OPCODE(ATOMIC_LOADW_AND);
4632     OPCODE(ATOMIC_LOADW_OR);
4633     OPCODE(ATOMIC_LOADW_XOR);
4634     OPCODE(ATOMIC_LOADW_NAND);
4635     OPCODE(ATOMIC_LOADW_MIN);
4636     OPCODE(ATOMIC_LOADW_MAX);
4637     OPCODE(ATOMIC_LOADW_UMIN);
4638     OPCODE(ATOMIC_LOADW_UMAX);
4639     OPCODE(ATOMIC_CMP_SWAPW);
4640     OPCODE(PREFETCH);
4641   }
4642   return nullptr;
4643 #undef OPCODE
4644 }
4645 
4646 // Return true if VT is a vector whose elements are a whole number of bytes
4647 // in width.
4648 static bool canTreatAsByteVector(EVT VT) {
4649   return VT.isVector() && VT.getVectorElementType().getSizeInBits() % 8 == 0;
4650 }
4651 
4652 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
4653 // producing a result of type ResVT.  Op is a possibly bitcast version
4654 // of the input vector and Index is the index (based on type VecVT) that
4655 // should be extracted.  Return the new extraction if a simplification
4656 // was possible or if Force is true.
4657 SDValue SystemZTargetLowering::combineExtract(SDLoc DL, EVT ResVT, EVT VecVT,
4658                                               SDValue Op, unsigned Index,
4659                                               DAGCombinerInfo &DCI,
4660                                               bool Force) const {
4661   SelectionDAG &DAG = DCI.DAG;
4662 
4663   // The number of bytes being extracted.
4664   unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4665 
4666   for (;;) {
4667     unsigned Opcode = Op.getOpcode();
4668     if (Opcode == ISD::BITCAST)
4669       // Look through bitcasts.
4670       Op = Op.getOperand(0);
4671     else if (Opcode == ISD::VECTOR_SHUFFLE &&
4672              canTreatAsByteVector(Op.getValueType())) {
4673       // Get a VPERM-like permute mask and see whether the bytes covered
4674       // by the extracted element are a contiguous sequence from one
4675       // source operand.
4676       SmallVector<int, SystemZ::VectorBytes> Bytes;
4677       getVPermMask(cast<ShuffleVectorSDNode>(Op), Bytes);
4678       int First;
4679       if (!getShuffleInput(Bytes, Index * BytesPerElement,
4680                            BytesPerElement, First))
4681         break;
4682       if (First < 0)
4683         return DAG.getUNDEF(ResVT);
4684       // Make sure the contiguous sequence starts at a multiple of the
4685       // original element size.
4686       unsigned Byte = unsigned(First) % Bytes.size();
4687       if (Byte % BytesPerElement != 0)
4688         break;
4689       // We can get the extracted value directly from an input.
4690       Index = Byte / BytesPerElement;
4691       Op = Op.getOperand(unsigned(First) / Bytes.size());
4692       Force = true;
4693     } else if (Opcode == ISD::BUILD_VECTOR &&
4694                canTreatAsByteVector(Op.getValueType())) {
4695       // We can only optimize this case if the BUILD_VECTOR elements are
4696       // at least as wide as the extracted value.
4697       EVT OpVT = Op.getValueType();
4698       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4699       if (OpBytesPerElement < BytesPerElement)
4700         break;
4701       // Make sure that the least-significant bit of the extracted value
4702       // is the least significant bit of an input.
4703       unsigned End = (Index + 1) * BytesPerElement;
4704       if (End % OpBytesPerElement != 0)
4705         break;
4706       // We're extracting the low part of one operand of the BUILD_VECTOR.
4707       Op = Op.getOperand(End / OpBytesPerElement - 1);
4708       if (!Op.getValueType().isInteger()) {
4709         EVT VT = MVT::getIntegerVT(Op.getValueType().getSizeInBits());
4710         Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
4711         DCI.AddToWorklist(Op.getNode());
4712       }
4713       EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
4714       Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
4715       if (VT != ResVT) {
4716         DCI.AddToWorklist(Op.getNode());
4717         Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
4718       }
4719       return Op;
4720     } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
4721                 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
4722                 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
4723                canTreatAsByteVector(Op.getValueType()) &&
4724                canTreatAsByteVector(Op.getOperand(0).getValueType())) {
4725       // Make sure that only the unextended bits are significant.
4726       EVT ExtVT = Op.getValueType();
4727       EVT OpVT = Op.getOperand(0).getValueType();
4728       unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
4729       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4730       unsigned Byte = Index * BytesPerElement;
4731       unsigned SubByte = Byte % ExtBytesPerElement;
4732       unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
4733       if (SubByte < MinSubByte ||
4734           SubByte + BytesPerElement > ExtBytesPerElement)
4735         break;
4736       // Get the byte offset of the unextended element
4737       Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
4738       // ...then add the byte offset relative to that element.
4739       Byte += SubByte - MinSubByte;
4740       if (Byte % BytesPerElement != 0)
4741         break;
4742       Op = Op.getOperand(0);
4743       Index = Byte / BytesPerElement;
4744       Force = true;
4745     } else
4746       break;
4747   }
4748   if (Force) {
4749     if (Op.getValueType() != VecVT) {
4750       Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
4751       DCI.AddToWorklist(Op.getNode());
4752     }
4753     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
4754                        DAG.getConstant(Index, DL, MVT::i32));
4755   }
4756   return SDValue();
4757 }
4758 
4759 // Optimize vector operations in scalar value Op on the basis that Op
4760 // is truncated to TruncVT.
4761 SDValue
4762 SystemZTargetLowering::combineTruncateExtract(SDLoc DL, EVT TruncVT, SDValue Op,
4763                                               DAGCombinerInfo &DCI) const {
4764   // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
4765   // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
4766   // of type TruncVT.
4767   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4768       TruncVT.getSizeInBits() % 8 == 0) {
4769     SDValue Vec = Op.getOperand(0);
4770     EVT VecVT = Vec.getValueType();
4771     if (canTreatAsByteVector(VecVT)) {
4772       if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4773         unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4774         unsigned TruncBytes = TruncVT.getStoreSize();
4775         if (BytesPerElement % TruncBytes == 0) {
4776           // Calculate the value of Y' in the above description.  We are
4777           // splitting the original elements into Scale equal-sized pieces
4778           // and for truncation purposes want the last (least-significant)
4779           // of these pieces for IndexN.  This is easiest to do by calculating
4780           // the start index of the following element and then subtracting 1.
4781           unsigned Scale = BytesPerElement / TruncBytes;
4782           unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
4783 
4784           // Defer the creation of the bitcast from X to combineExtract,
4785           // which might be able to optimize the extraction.
4786           VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
4787                                    VecVT.getStoreSize() / TruncBytes);
4788           EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
4789           return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
4790         }
4791       }
4792     }
4793   }
4794   return SDValue();
4795 }
4796 
4797 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
4798                                                  DAGCombinerInfo &DCI) const {
4799   SelectionDAG &DAG = DCI.DAG;
4800   unsigned Opcode = N->getOpcode();
4801   if (Opcode == ISD::SIGN_EXTEND) {
4802     // Convert (sext (ashr (shl X, C1), C2)) to
4803     // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
4804     // cheap as narrower ones.
4805     SDValue N0 = N->getOperand(0);
4806     EVT VT = N->getValueType(0);
4807     if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
4808       auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4809       SDValue Inner = N0.getOperand(0);
4810       if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
4811         if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
4812           unsigned Extra = (VT.getSizeInBits() -
4813                             N0.getValueType().getSizeInBits());
4814           unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
4815           unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
4816           EVT ShiftVT = N0.getOperand(1).getValueType();
4817           SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
4818                                     Inner.getOperand(0));
4819           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
4820                                     DAG.getConstant(NewShlAmt, SDLoc(Inner),
4821                                                     ShiftVT));
4822           return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
4823                              DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
4824         }
4825       }
4826     }
4827   }
4828   if (Opcode == SystemZISD::MERGE_HIGH ||
4829       Opcode == SystemZISD::MERGE_LOW) {
4830     SDValue Op0 = N->getOperand(0);
4831     SDValue Op1 = N->getOperand(1);
4832     if (Op0.getOpcode() == ISD::BITCAST)
4833       Op0 = Op0.getOperand(0);
4834     if (Op0.getOpcode() == SystemZISD::BYTE_MASK &&
4835         cast<ConstantSDNode>(Op0.getOperand(0))->getZExtValue() == 0) {
4836       // (z_merge_* 0, 0) -> 0.  This is mostly useful for using VLLEZF
4837       // for v4f32.
4838       if (Op1 == N->getOperand(0))
4839         return Op1;
4840       // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
4841       EVT VT = Op1.getValueType();
4842       unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
4843       if (ElemBytes <= 4) {
4844         Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
4845                   SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
4846         EVT InVT = VT.changeVectorElementTypeToInteger();
4847         EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
4848                                      SystemZ::VectorBytes / ElemBytes / 2);
4849         if (VT != InVT) {
4850           Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
4851           DCI.AddToWorklist(Op1.getNode());
4852         }
4853         SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
4854         DCI.AddToWorklist(Op.getNode());
4855         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
4856       }
4857     }
4858   }
4859   // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
4860   // for the extraction to be done on a vMiN value, so that we can use VSTE.
4861   // If X has wider elements then convert it to:
4862   // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
4863   if (Opcode == ISD::STORE) {
4864     auto *SN = cast<StoreSDNode>(N);
4865     EVT MemVT = SN->getMemoryVT();
4866     if (MemVT.isInteger()) {
4867       if (SDValue Value =
4868               combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
4869         DCI.AddToWorklist(Value.getNode());
4870 
4871         // Rewrite the store with the new form of stored value.
4872         return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
4873                                  SN->getBasePtr(), SN->getMemoryVT(),
4874                                  SN->getMemOperand());
4875       }
4876     }
4877   }
4878   // Try to simplify a vector extraction.
4879   if (Opcode == ISD::EXTRACT_VECTOR_ELT) {
4880     if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
4881       SDValue Op0 = N->getOperand(0);
4882       EVT VecVT = Op0.getValueType();
4883       return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
4884                             IndexN->getZExtValue(), DCI, false);
4885     }
4886   }
4887   // (join_dwords X, X) == (replicate X)
4888   if (Opcode == SystemZISD::JOIN_DWORDS &&
4889       N->getOperand(0) == N->getOperand(1))
4890     return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
4891                        N->getOperand(0));
4892   // (fround (extract_vector_elt X 0))
4893   // (fround (extract_vector_elt X 1)) ->
4894   // (extract_vector_elt (VROUND X) 0)
4895   // (extract_vector_elt (VROUND X) 1)
4896   //
4897   // This is a special case since the target doesn't really support v2f32s.
4898   if (Opcode == ISD::FP_ROUND) {
4899     SDValue Op0 = N->getOperand(0);
4900     if (N->getValueType(0) == MVT::f32 &&
4901         Op0.hasOneUse() &&
4902         Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4903         Op0.getOperand(0).getValueType() == MVT::v2f64 &&
4904         Op0.getOperand(1).getOpcode() == ISD::Constant &&
4905         cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
4906       SDValue Vec = Op0.getOperand(0);
4907       for (auto *U : Vec->uses()) {
4908         if (U != Op0.getNode() &&
4909             U->hasOneUse() &&
4910             U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4911             U->getOperand(0) == Vec &&
4912             U->getOperand(1).getOpcode() == ISD::Constant &&
4913             cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
4914           SDValue OtherRound = SDValue(*U->use_begin(), 0);
4915           if (OtherRound.getOpcode() == ISD::FP_ROUND &&
4916               OtherRound.getOperand(0) == SDValue(U, 0) &&
4917               OtherRound.getValueType() == MVT::f32) {
4918             SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
4919                                          MVT::v4f32, Vec);
4920             DCI.AddToWorklist(VRound.getNode());
4921             SDValue Extract1 =
4922               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
4923                           VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
4924             DCI.AddToWorklist(Extract1.getNode());
4925             DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
4926             SDValue Extract0 =
4927               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
4928                           VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
4929             return Extract0;
4930           }
4931         }
4932       }
4933     }
4934   }
4935   return SDValue();
4936 }
4937 
4938 //===----------------------------------------------------------------------===//
4939 // Custom insertion
4940 //===----------------------------------------------------------------------===//
4941 
4942 // Create a new basic block after MBB.
4943 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
4944   MachineFunction &MF = *MBB->getParent();
4945   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
4946   MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
4947   return NewMBB;
4948 }
4949 
4950 // Split MBB after MI and return the new block (the one that contains
4951 // instructions after MI).
4952 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
4953                                           MachineBasicBlock *MBB) {
4954   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4955   NewMBB->splice(NewMBB->begin(), MBB,
4956                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
4957   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4958   return NewMBB;
4959 }
4960 
4961 // Split MBB before MI and return the new block (the one that contains MI).
4962 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
4963                                            MachineBasicBlock *MBB) {
4964   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4965   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
4966   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4967   return NewMBB;
4968 }
4969 
4970 // Force base value Base into a register before MI.  Return the register.
4971 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
4972                          const SystemZInstrInfo *TII) {
4973   if (Base.isReg())
4974     return Base.getReg();
4975 
4976   MachineBasicBlock *MBB = MI->getParent();
4977   MachineFunction &MF = *MBB->getParent();
4978   MachineRegisterInfo &MRI = MF.getRegInfo();
4979 
4980   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
4981   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
4982     .addOperand(Base).addImm(0).addReg(0);
4983   return Reg;
4984 }
4985 
4986 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
4987 MachineBasicBlock *
4988 SystemZTargetLowering::emitSelect(MachineInstr *MI,
4989                                   MachineBasicBlock *MBB) const {
4990   const SystemZInstrInfo *TII =
4991       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4992 
4993   unsigned DestReg  = MI->getOperand(0).getReg();
4994   unsigned TrueReg  = MI->getOperand(1).getReg();
4995   unsigned FalseReg = MI->getOperand(2).getReg();
4996   unsigned CCValid  = MI->getOperand(3).getImm();
4997   unsigned CCMask   = MI->getOperand(4).getImm();
4998   DebugLoc DL       = MI->getDebugLoc();
4999 
5000   MachineBasicBlock *StartMBB = MBB;
5001   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
5002   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
5003 
5004   //  StartMBB:
5005   //   BRC CCMask, JoinMBB
5006   //   # fallthrough to FalseMBB
5007   MBB = StartMBB;
5008   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5009     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
5010   MBB->addSuccessor(JoinMBB);
5011   MBB->addSuccessor(FalseMBB);
5012 
5013   //  FalseMBB:
5014   //   # fallthrough to JoinMBB
5015   MBB = FalseMBB;
5016   MBB->addSuccessor(JoinMBB);
5017 
5018   //  JoinMBB:
5019   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
5020   //  ...
5021   MBB = JoinMBB;
5022   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
5023     .addReg(TrueReg).addMBB(StartMBB)
5024     .addReg(FalseReg).addMBB(FalseMBB);
5025 
5026   MI->eraseFromParent();
5027   return JoinMBB;
5028 }
5029 
5030 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
5031 // StoreOpcode is the store to use and Invert says whether the store should
5032 // happen when the condition is false rather than true.  If a STORE ON
5033 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
5034 MachineBasicBlock *
5035 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
5036                                      MachineBasicBlock *MBB,
5037                                      unsigned StoreOpcode, unsigned STOCOpcode,
5038                                      bool Invert) const {
5039   const SystemZInstrInfo *TII =
5040       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5041 
5042   unsigned SrcReg     = MI->getOperand(0).getReg();
5043   MachineOperand Base = MI->getOperand(1);
5044   int64_t Disp        = MI->getOperand(2).getImm();
5045   unsigned IndexReg   = MI->getOperand(3).getReg();
5046   unsigned CCValid    = MI->getOperand(4).getImm();
5047   unsigned CCMask     = MI->getOperand(5).getImm();
5048   DebugLoc DL         = MI->getDebugLoc();
5049 
5050   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
5051 
5052   // Use STOCOpcode if possible.  We could use different store patterns in
5053   // order to avoid matching the index register, but the performance trade-offs
5054   // might be more complicated in that case.
5055   if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
5056     if (Invert)
5057       CCMask ^= CCValid;
5058     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
5059       .addReg(SrcReg).addOperand(Base).addImm(Disp)
5060       .addImm(CCValid).addImm(CCMask);
5061     MI->eraseFromParent();
5062     return MBB;
5063   }
5064 
5065   // Get the condition needed to branch around the store.
5066   if (!Invert)
5067     CCMask ^= CCValid;
5068 
5069   MachineBasicBlock *StartMBB = MBB;
5070   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
5071   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
5072 
5073   //  StartMBB:
5074   //   BRC CCMask, JoinMBB
5075   //   # fallthrough to FalseMBB
5076   MBB = StartMBB;
5077   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5078     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
5079   MBB->addSuccessor(JoinMBB);
5080   MBB->addSuccessor(FalseMBB);
5081 
5082   //  FalseMBB:
5083   //   store %SrcReg, %Disp(%Index,%Base)
5084   //   # fallthrough to JoinMBB
5085   MBB = FalseMBB;
5086   BuildMI(MBB, DL, TII->get(StoreOpcode))
5087     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
5088   MBB->addSuccessor(JoinMBB);
5089 
5090   MI->eraseFromParent();
5091   return JoinMBB;
5092 }
5093 
5094 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
5095 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
5096 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
5097 // BitSize is the width of the field in bits, or 0 if this is a partword
5098 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
5099 // is one of the operands.  Invert says whether the field should be
5100 // inverted after performing BinOpcode (e.g. for NAND).
5101 MachineBasicBlock *
5102 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
5103                                             MachineBasicBlock *MBB,
5104                                             unsigned BinOpcode,
5105                                             unsigned BitSize,
5106                                             bool Invert) const {
5107   MachineFunction &MF = *MBB->getParent();
5108   const SystemZInstrInfo *TII =
5109       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5110   MachineRegisterInfo &MRI = MF.getRegInfo();
5111   bool IsSubWord = (BitSize < 32);
5112 
5113   // Extract the operands.  Base can be a register or a frame index.
5114   // Src2 can be a register or immediate.
5115   unsigned Dest        = MI->getOperand(0).getReg();
5116   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
5117   int64_t Disp         = MI->getOperand(2).getImm();
5118   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
5119   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
5120   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
5121   DebugLoc DL          = MI->getDebugLoc();
5122   if (IsSubWord)
5123     BitSize = MI->getOperand(6).getImm();
5124 
5125   // Subword operations use 32-bit registers.
5126   const TargetRegisterClass *RC = (BitSize <= 32 ?
5127                                    &SystemZ::GR32BitRegClass :
5128                                    &SystemZ::GR64BitRegClass);
5129   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
5130   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5131 
5132   // Get the right opcodes for the displacement.
5133   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
5134   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5135   assert(LOpcode && CSOpcode && "Displacement out of range");
5136 
5137   // Create virtual registers for temporary results.
5138   unsigned OrigVal       = MRI.createVirtualRegister(RC);
5139   unsigned OldVal        = MRI.createVirtualRegister(RC);
5140   unsigned NewVal        = (BinOpcode || IsSubWord ?
5141                             MRI.createVirtualRegister(RC) : Src2.getReg());
5142   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5143   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5144 
5145   // Insert a basic block for the main loop.
5146   MachineBasicBlock *StartMBB = MBB;
5147   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
5148   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
5149 
5150   //  StartMBB:
5151   //   ...
5152   //   %OrigVal = L Disp(%Base)
5153   //   # fall through to LoopMMB
5154   MBB = StartMBB;
5155   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
5156     .addOperand(Base).addImm(Disp).addReg(0);
5157   MBB->addSuccessor(LoopMBB);
5158 
5159   //  LoopMBB:
5160   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
5161   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5162   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
5163   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
5164   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
5165   //   JNE LoopMBB
5166   //   # fall through to DoneMMB
5167   MBB = LoopMBB;
5168   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5169     .addReg(OrigVal).addMBB(StartMBB)
5170     .addReg(Dest).addMBB(LoopMBB);
5171   if (IsSubWord)
5172     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5173       .addReg(OldVal).addReg(BitShift).addImm(0);
5174   if (Invert) {
5175     // Perform the operation normally and then invert every bit of the field.
5176     unsigned Tmp = MRI.createVirtualRegister(RC);
5177     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
5178       .addReg(RotatedOldVal).addOperand(Src2);
5179     if (BitSize <= 32)
5180       // XILF with the upper BitSize bits set.
5181       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
5182         .addReg(Tmp).addImm(-1U << (32 - BitSize));
5183     else {
5184       // Use LCGR and add -1 to the result, which is more compact than
5185       // an XILF, XILH pair.
5186       unsigned Tmp2 = MRI.createVirtualRegister(RC);
5187       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
5188       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
5189         .addReg(Tmp2).addImm(-1);
5190     }
5191   } else if (BinOpcode)
5192     // A simply binary operation.
5193     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
5194       .addReg(RotatedOldVal).addOperand(Src2);
5195   else if (IsSubWord)
5196     // Use RISBG to rotate Src2 into position and use it to replace the
5197     // field in RotatedOldVal.
5198     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
5199       .addReg(RotatedOldVal).addReg(Src2.getReg())
5200       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
5201   if (IsSubWord)
5202     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5203       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5204   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5205     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
5206   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5207     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5208   MBB->addSuccessor(LoopMBB);
5209   MBB->addSuccessor(DoneMBB);
5210 
5211   MI->eraseFromParent();
5212   return DoneMBB;
5213 }
5214 
5215 // Implement EmitInstrWithCustomInserter for pseudo
5216 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
5217 // instruction that should be used to compare the current field with the
5218 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
5219 // for when the current field should be kept.  BitSize is the width of
5220 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
5221 MachineBasicBlock *
5222 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
5223                                             MachineBasicBlock *MBB,
5224                                             unsigned CompareOpcode,
5225                                             unsigned KeepOldMask,
5226                                             unsigned BitSize) const {
5227   MachineFunction &MF = *MBB->getParent();
5228   const SystemZInstrInfo *TII =
5229       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5230   MachineRegisterInfo &MRI = MF.getRegInfo();
5231   bool IsSubWord = (BitSize < 32);
5232 
5233   // Extract the operands.  Base can be a register or a frame index.
5234   unsigned Dest        = MI->getOperand(0).getReg();
5235   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
5236   int64_t  Disp        = MI->getOperand(2).getImm();
5237   unsigned Src2        = MI->getOperand(3).getReg();
5238   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
5239   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
5240   DebugLoc DL          = MI->getDebugLoc();
5241   if (IsSubWord)
5242     BitSize = MI->getOperand(6).getImm();
5243 
5244   // Subword operations use 32-bit registers.
5245   const TargetRegisterClass *RC = (BitSize <= 32 ?
5246                                    &SystemZ::GR32BitRegClass :
5247                                    &SystemZ::GR64BitRegClass);
5248   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
5249   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5250 
5251   // Get the right opcodes for the displacement.
5252   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
5253   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5254   assert(LOpcode && CSOpcode && "Displacement out of range");
5255 
5256   // Create virtual registers for temporary results.
5257   unsigned OrigVal       = MRI.createVirtualRegister(RC);
5258   unsigned OldVal        = MRI.createVirtualRegister(RC);
5259   unsigned NewVal        = MRI.createVirtualRegister(RC);
5260   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5261   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
5262   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5263 
5264   // Insert 3 basic blocks for the loop.
5265   MachineBasicBlock *StartMBB  = MBB;
5266   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
5267   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
5268   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
5269   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
5270 
5271   //  StartMBB:
5272   //   ...
5273   //   %OrigVal     = L Disp(%Base)
5274   //   # fall through to LoopMMB
5275   MBB = StartMBB;
5276   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
5277     .addOperand(Base).addImm(Disp).addReg(0);
5278   MBB->addSuccessor(LoopMBB);
5279 
5280   //  LoopMBB:
5281   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
5282   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5283   //   CompareOpcode %RotatedOldVal, %Src2
5284   //   BRC KeepOldMask, UpdateMBB
5285   MBB = LoopMBB;
5286   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5287     .addReg(OrigVal).addMBB(StartMBB)
5288     .addReg(Dest).addMBB(UpdateMBB);
5289   if (IsSubWord)
5290     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5291       .addReg(OldVal).addReg(BitShift).addImm(0);
5292   BuildMI(MBB, DL, TII->get(CompareOpcode))
5293     .addReg(RotatedOldVal).addReg(Src2);
5294   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5295     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
5296   MBB->addSuccessor(UpdateMBB);
5297   MBB->addSuccessor(UseAltMBB);
5298 
5299   //  UseAltMBB:
5300   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
5301   //   # fall through to UpdateMMB
5302   MBB = UseAltMBB;
5303   if (IsSubWord)
5304     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
5305       .addReg(RotatedOldVal).addReg(Src2)
5306       .addImm(32).addImm(31 + BitSize).addImm(0);
5307   MBB->addSuccessor(UpdateMBB);
5308 
5309   //  UpdateMBB:
5310   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
5311   //                        [ %RotatedAltVal, UseAltMBB ]
5312   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
5313   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
5314   //   JNE LoopMBB
5315   //   # fall through to DoneMMB
5316   MBB = UpdateMBB;
5317   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
5318     .addReg(RotatedOldVal).addMBB(LoopMBB)
5319     .addReg(RotatedAltVal).addMBB(UseAltMBB);
5320   if (IsSubWord)
5321     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5322       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5323   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5324     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
5325   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5326     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5327   MBB->addSuccessor(LoopMBB);
5328   MBB->addSuccessor(DoneMBB);
5329 
5330   MI->eraseFromParent();
5331   return DoneMBB;
5332 }
5333 
5334 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
5335 // instruction MI.
5336 MachineBasicBlock *
5337 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
5338                                           MachineBasicBlock *MBB) const {
5339 
5340   MachineFunction &MF = *MBB->getParent();
5341   const SystemZInstrInfo *TII =
5342       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5343   MachineRegisterInfo &MRI = MF.getRegInfo();
5344 
5345   // Extract the operands.  Base can be a register or a frame index.
5346   unsigned Dest        = MI->getOperand(0).getReg();
5347   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
5348   int64_t  Disp        = MI->getOperand(2).getImm();
5349   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
5350   unsigned OrigSwapVal = MI->getOperand(4).getReg();
5351   unsigned BitShift    = MI->getOperand(5).getReg();
5352   unsigned NegBitShift = MI->getOperand(6).getReg();
5353   int64_t  BitSize     = MI->getOperand(7).getImm();
5354   DebugLoc DL          = MI->getDebugLoc();
5355 
5356   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
5357 
5358   // Get the right opcodes for the displacement.
5359   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
5360   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
5361   assert(LOpcode && CSOpcode && "Displacement out of range");
5362 
5363   // Create virtual registers for temporary results.
5364   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
5365   unsigned OldVal       = MRI.createVirtualRegister(RC);
5366   unsigned CmpVal       = MRI.createVirtualRegister(RC);
5367   unsigned SwapVal      = MRI.createVirtualRegister(RC);
5368   unsigned StoreVal     = MRI.createVirtualRegister(RC);
5369   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
5370   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
5371   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
5372 
5373   // Insert 2 basic blocks for the loop.
5374   MachineBasicBlock *StartMBB = MBB;
5375   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
5376   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
5377   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
5378 
5379   //  StartMBB:
5380   //   ...
5381   //   %OrigOldVal     = L Disp(%Base)
5382   //   # fall through to LoopMMB
5383   MBB = StartMBB;
5384   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
5385     .addOperand(Base).addImm(Disp).addReg(0);
5386   MBB->addSuccessor(LoopMBB);
5387 
5388   //  LoopMBB:
5389   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
5390   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
5391   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
5392   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
5393   //                      ^^ The low BitSize bits contain the field
5394   //                         of interest.
5395   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
5396   //                      ^^ Replace the upper 32-BitSize bits of the
5397   //                         comparison value with those that we loaded,
5398   //                         so that we can use a full word comparison.
5399   //   CR %Dest, %RetryCmpVal
5400   //   JNE DoneMBB
5401   //   # Fall through to SetMBB
5402   MBB = LoopMBB;
5403   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5404     .addReg(OrigOldVal).addMBB(StartMBB)
5405     .addReg(RetryOldVal).addMBB(SetMBB);
5406   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
5407     .addReg(OrigCmpVal).addMBB(StartMBB)
5408     .addReg(RetryCmpVal).addMBB(SetMBB);
5409   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
5410     .addReg(OrigSwapVal).addMBB(StartMBB)
5411     .addReg(RetrySwapVal).addMBB(SetMBB);
5412   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
5413     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
5414   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
5415     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5416   BuildMI(MBB, DL, TII->get(SystemZ::CR))
5417     .addReg(Dest).addReg(RetryCmpVal);
5418   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5419     .addImm(SystemZ::CCMASK_ICMP)
5420     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
5421   MBB->addSuccessor(DoneMBB);
5422   MBB->addSuccessor(SetMBB);
5423 
5424   //  SetMBB:
5425   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
5426   //                      ^^ Replace the upper 32-BitSize bits of the new
5427   //                         value with those that we loaded.
5428   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
5429   //                      ^^ Rotate the new field to its proper position.
5430   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
5431   //   JNE LoopMBB
5432   //   # fall through to ExitMMB
5433   MBB = SetMBB;
5434   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
5435     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5436   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
5437     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
5438   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
5439     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
5440   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5441     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5442   MBB->addSuccessor(LoopMBB);
5443   MBB->addSuccessor(DoneMBB);
5444 
5445   MI->eraseFromParent();
5446   return DoneMBB;
5447 }
5448 
5449 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
5450 // if the high register of the GR128 value must be cleared or false if
5451 // it's "don't care".  SubReg is subreg_l32 when extending a GR32
5452 // and subreg_l64 when extending a GR64.
5453 MachineBasicBlock *
5454 SystemZTargetLowering::emitExt128(MachineInstr *MI,
5455                                   MachineBasicBlock *MBB,
5456                                   bool ClearEven, unsigned SubReg) const {
5457   MachineFunction &MF = *MBB->getParent();
5458   const SystemZInstrInfo *TII =
5459       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5460   MachineRegisterInfo &MRI = MF.getRegInfo();
5461   DebugLoc DL = MI->getDebugLoc();
5462 
5463   unsigned Dest  = MI->getOperand(0).getReg();
5464   unsigned Src   = MI->getOperand(1).getReg();
5465   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5466 
5467   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
5468   if (ClearEven) {
5469     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5470     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
5471 
5472     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
5473       .addImm(0);
5474     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
5475       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
5476     In128 = NewIn128;
5477   }
5478   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
5479     .addReg(In128).addReg(Src).addImm(SubReg);
5480 
5481   MI->eraseFromParent();
5482   return MBB;
5483 }
5484 
5485 MachineBasicBlock *
5486 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
5487                                          MachineBasicBlock *MBB,
5488                                          unsigned Opcode) const {
5489   MachineFunction &MF = *MBB->getParent();
5490   const SystemZInstrInfo *TII =
5491       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5492   MachineRegisterInfo &MRI = MF.getRegInfo();
5493   DebugLoc DL = MI->getDebugLoc();
5494 
5495   MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
5496   uint64_t       DestDisp = MI->getOperand(1).getImm();
5497   MachineOperand SrcBase  = earlyUseOperand(MI->getOperand(2));
5498   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
5499   uint64_t       Length   = MI->getOperand(4).getImm();
5500 
5501   // When generating more than one CLC, all but the last will need to
5502   // branch to the end when a difference is found.
5503   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
5504                                splitBlockAfter(MI, MBB) : nullptr);
5505 
5506   // Check for the loop form, in which operand 5 is the trip count.
5507   if (MI->getNumExplicitOperands() > 5) {
5508     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
5509 
5510     uint64_t StartCountReg = MI->getOperand(5).getReg();
5511     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
5512     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
5513                               forceReg(MI, DestBase, TII));
5514 
5515     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
5516     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
5517     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
5518                             MRI.createVirtualRegister(RC));
5519     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
5520     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
5521                             MRI.createVirtualRegister(RC));
5522 
5523     RC = &SystemZ::GR64BitRegClass;
5524     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
5525     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
5526 
5527     MachineBasicBlock *StartMBB = MBB;
5528     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5529     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5530     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
5531 
5532     //  StartMBB:
5533     //   # fall through to LoopMMB
5534     MBB->addSuccessor(LoopMBB);
5535 
5536     //  LoopMBB:
5537     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
5538     //                      [ %NextDestReg, NextMBB ]
5539     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
5540     //                     [ %NextSrcReg, NextMBB ]
5541     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
5542     //                       [ %NextCountReg, NextMBB ]
5543     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
5544     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
5545     //   ( JLH EndMBB )
5546     //
5547     // The prefetch is used only for MVC.  The JLH is used only for CLC.
5548     MBB = LoopMBB;
5549 
5550     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
5551       .addReg(StartDestReg).addMBB(StartMBB)
5552       .addReg(NextDestReg).addMBB(NextMBB);
5553     if (!HaveSingleBase)
5554       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
5555         .addReg(StartSrcReg).addMBB(StartMBB)
5556         .addReg(NextSrcReg).addMBB(NextMBB);
5557     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
5558       .addReg(StartCountReg).addMBB(StartMBB)
5559       .addReg(NextCountReg).addMBB(NextMBB);
5560     if (Opcode == SystemZ::MVC)
5561       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
5562         .addImm(SystemZ::PFD_WRITE)
5563         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
5564     BuildMI(MBB, DL, TII->get(Opcode))
5565       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
5566       .addReg(ThisSrcReg).addImm(SrcDisp);
5567     if (EndMBB) {
5568       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5569         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5570         .addMBB(EndMBB);
5571       MBB->addSuccessor(EndMBB);
5572       MBB->addSuccessor(NextMBB);
5573     }
5574 
5575     // NextMBB:
5576     //   %NextDestReg = LA 256(%ThisDestReg)
5577     //   %NextSrcReg = LA 256(%ThisSrcReg)
5578     //   %NextCountReg = AGHI %ThisCountReg, -1
5579     //   CGHI %NextCountReg, 0
5580     //   JLH LoopMBB
5581     //   # fall through to DoneMMB
5582     //
5583     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
5584     MBB = NextMBB;
5585 
5586     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
5587       .addReg(ThisDestReg).addImm(256).addReg(0);
5588     if (!HaveSingleBase)
5589       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
5590         .addReg(ThisSrcReg).addImm(256).addReg(0);
5591     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
5592       .addReg(ThisCountReg).addImm(-1);
5593     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
5594       .addReg(NextCountReg).addImm(0);
5595     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5596       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5597       .addMBB(LoopMBB);
5598     MBB->addSuccessor(LoopMBB);
5599     MBB->addSuccessor(DoneMBB);
5600 
5601     DestBase = MachineOperand::CreateReg(NextDestReg, false);
5602     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
5603     Length &= 255;
5604     MBB = DoneMBB;
5605   }
5606   // Handle any remaining bytes with straight-line code.
5607   while (Length > 0) {
5608     uint64_t ThisLength = std::min(Length, uint64_t(256));
5609     // The previous iteration might have created out-of-range displacements.
5610     // Apply them using LAY if so.
5611     if (!isUInt<12>(DestDisp)) {
5612       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5613       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5614         .addOperand(DestBase).addImm(DestDisp).addReg(0);
5615       DestBase = MachineOperand::CreateReg(Reg, false);
5616       DestDisp = 0;
5617     }
5618     if (!isUInt<12>(SrcDisp)) {
5619       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5620       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5621         .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
5622       SrcBase = MachineOperand::CreateReg(Reg, false);
5623       SrcDisp = 0;
5624     }
5625     BuildMI(*MBB, MI, DL, TII->get(Opcode))
5626       .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
5627       .addOperand(SrcBase).addImm(SrcDisp);
5628     DestDisp += ThisLength;
5629     SrcDisp += ThisLength;
5630     Length -= ThisLength;
5631     // If there's another CLC to go, branch to the end if a difference
5632     // was found.
5633     if (EndMBB && Length > 0) {
5634       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
5635       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5636         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5637         .addMBB(EndMBB);
5638       MBB->addSuccessor(EndMBB);
5639       MBB->addSuccessor(NextMBB);
5640       MBB = NextMBB;
5641     }
5642   }
5643   if (EndMBB) {
5644     MBB->addSuccessor(EndMBB);
5645     MBB = EndMBB;
5646     MBB->addLiveIn(SystemZ::CC);
5647   }
5648 
5649   MI->eraseFromParent();
5650   return MBB;
5651 }
5652 
5653 // Decompose string pseudo-instruction MI into a loop that continually performs
5654 // Opcode until CC != 3.
5655 MachineBasicBlock *
5656 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
5657                                          MachineBasicBlock *MBB,
5658                                          unsigned Opcode) const {
5659   MachineFunction &MF = *MBB->getParent();
5660   const SystemZInstrInfo *TII =
5661       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5662   MachineRegisterInfo &MRI = MF.getRegInfo();
5663   DebugLoc DL = MI->getDebugLoc();
5664 
5665   uint64_t End1Reg   = MI->getOperand(0).getReg();
5666   uint64_t Start1Reg = MI->getOperand(1).getReg();
5667   uint64_t Start2Reg = MI->getOperand(2).getReg();
5668   uint64_t CharReg   = MI->getOperand(3).getReg();
5669 
5670   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
5671   uint64_t This1Reg = MRI.createVirtualRegister(RC);
5672   uint64_t This2Reg = MRI.createVirtualRegister(RC);
5673   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
5674 
5675   MachineBasicBlock *StartMBB = MBB;
5676   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5677   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5678 
5679   //  StartMBB:
5680   //   # fall through to LoopMMB
5681   MBB->addSuccessor(LoopMBB);
5682 
5683   //  LoopMBB:
5684   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
5685   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
5686   //   R0L = %CharReg
5687   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
5688   //   JO LoopMBB
5689   //   # fall through to DoneMMB
5690   //
5691   // The load of R0L can be hoisted by post-RA LICM.
5692   MBB = LoopMBB;
5693 
5694   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
5695     .addReg(Start1Reg).addMBB(StartMBB)
5696     .addReg(End1Reg).addMBB(LoopMBB);
5697   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
5698     .addReg(Start2Reg).addMBB(StartMBB)
5699     .addReg(End2Reg).addMBB(LoopMBB);
5700   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
5701   BuildMI(MBB, DL, TII->get(Opcode))
5702     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
5703     .addReg(This1Reg).addReg(This2Reg);
5704   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5705     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
5706   MBB->addSuccessor(LoopMBB);
5707   MBB->addSuccessor(DoneMBB);
5708 
5709   DoneMBB->addLiveIn(SystemZ::CC);
5710 
5711   MI->eraseFromParent();
5712   return DoneMBB;
5713 }
5714 
5715 // Update TBEGIN instruction with final opcode and register clobbers.
5716 MachineBasicBlock *
5717 SystemZTargetLowering::emitTransactionBegin(MachineInstr *MI,
5718                                             MachineBasicBlock *MBB,
5719                                             unsigned Opcode,
5720                                             bool NoFloat) const {
5721   MachineFunction &MF = *MBB->getParent();
5722   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
5723   const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
5724 
5725   // Update opcode.
5726   MI->setDesc(TII->get(Opcode));
5727 
5728   // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
5729   // Make sure to add the corresponding GRSM bits if they are missing.
5730   uint64_t Control = MI->getOperand(2).getImm();
5731   static const unsigned GPRControlBit[16] = {
5732     0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
5733     0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
5734   };
5735   Control |= GPRControlBit[15];
5736   if (TFI->hasFP(MF))
5737     Control |= GPRControlBit[11];
5738   MI->getOperand(2).setImm(Control);
5739 
5740   // Add GPR clobbers.
5741   for (int I = 0; I < 16; I++) {
5742     if ((Control & GPRControlBit[I]) == 0) {
5743       unsigned Reg = SystemZMC::GR64Regs[I];
5744       MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5745     }
5746   }
5747 
5748   // Add FPR/VR clobbers.
5749   if (!NoFloat && (Control & 4) != 0) {
5750     if (Subtarget.hasVector()) {
5751       for (int I = 0; I < 32; I++) {
5752         unsigned Reg = SystemZMC::VR128Regs[I];
5753         MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5754       }
5755     } else {
5756       for (int I = 0; I < 16; I++) {
5757         unsigned Reg = SystemZMC::FP64Regs[I];
5758         MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5759       }
5760     }
5761   }
5762 
5763   return MBB;
5764 }
5765 
5766 MachineBasicBlock *
5767 SystemZTargetLowering::emitLoadAndTestCmp0(MachineInstr *MI,
5768                                           MachineBasicBlock *MBB,
5769                                           unsigned Opcode) const {
5770   MachineFunction &MF = *MBB->getParent();
5771   MachineRegisterInfo *MRI = &MF.getRegInfo();
5772   const SystemZInstrInfo *TII =
5773       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5774   DebugLoc DL = MI->getDebugLoc();
5775 
5776   unsigned SrcReg = MI->getOperand(0).getReg();
5777 
5778   // Create new virtual register of the same class as source.
5779   const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
5780   unsigned DstReg = MRI->createVirtualRegister(RC);
5781 
5782   // Replace pseudo with a normal load-and-test that models the def as
5783   // well.
5784   BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
5785     .addReg(SrcReg);
5786   MI->eraseFromParent();
5787 
5788   return MBB;
5789 }
5790 
5791 MachineBasicBlock *SystemZTargetLowering::
5792 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
5793   switch (MI->getOpcode()) {
5794   case SystemZ::Select32Mux:
5795   case SystemZ::Select32:
5796   case SystemZ::SelectF32:
5797   case SystemZ::Select64:
5798   case SystemZ::SelectF64:
5799   case SystemZ::SelectF128:
5800     return emitSelect(MI, MBB);
5801 
5802   case SystemZ::CondStore8Mux:
5803     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
5804   case SystemZ::CondStore8MuxInv:
5805     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
5806   case SystemZ::CondStore16Mux:
5807     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
5808   case SystemZ::CondStore16MuxInv:
5809     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
5810   case SystemZ::CondStore8:
5811     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
5812   case SystemZ::CondStore8Inv:
5813     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
5814   case SystemZ::CondStore16:
5815     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
5816   case SystemZ::CondStore16Inv:
5817     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
5818   case SystemZ::CondStore32:
5819     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
5820   case SystemZ::CondStore32Inv:
5821     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
5822   case SystemZ::CondStore64:
5823     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
5824   case SystemZ::CondStore64Inv:
5825     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
5826   case SystemZ::CondStoreF32:
5827     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
5828   case SystemZ::CondStoreF32Inv:
5829     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
5830   case SystemZ::CondStoreF64:
5831     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
5832   case SystemZ::CondStoreF64Inv:
5833     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
5834 
5835   case SystemZ::AEXT128_64:
5836     return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
5837   case SystemZ::ZEXT128_32:
5838     return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
5839   case SystemZ::ZEXT128_64:
5840     return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
5841 
5842   case SystemZ::ATOMIC_SWAPW:
5843     return emitAtomicLoadBinary(MI, MBB, 0, 0);
5844   case SystemZ::ATOMIC_SWAP_32:
5845     return emitAtomicLoadBinary(MI, MBB, 0, 32);
5846   case SystemZ::ATOMIC_SWAP_64:
5847     return emitAtomicLoadBinary(MI, MBB, 0, 64);
5848 
5849   case SystemZ::ATOMIC_LOADW_AR:
5850     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
5851   case SystemZ::ATOMIC_LOADW_AFI:
5852     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
5853   case SystemZ::ATOMIC_LOAD_AR:
5854     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
5855   case SystemZ::ATOMIC_LOAD_AHI:
5856     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
5857   case SystemZ::ATOMIC_LOAD_AFI:
5858     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
5859   case SystemZ::ATOMIC_LOAD_AGR:
5860     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
5861   case SystemZ::ATOMIC_LOAD_AGHI:
5862     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
5863   case SystemZ::ATOMIC_LOAD_AGFI:
5864     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
5865 
5866   case SystemZ::ATOMIC_LOADW_SR:
5867     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
5868   case SystemZ::ATOMIC_LOAD_SR:
5869     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
5870   case SystemZ::ATOMIC_LOAD_SGR:
5871     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
5872 
5873   case SystemZ::ATOMIC_LOADW_NR:
5874     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
5875   case SystemZ::ATOMIC_LOADW_NILH:
5876     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
5877   case SystemZ::ATOMIC_LOAD_NR:
5878     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
5879   case SystemZ::ATOMIC_LOAD_NILL:
5880     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
5881   case SystemZ::ATOMIC_LOAD_NILH:
5882     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
5883   case SystemZ::ATOMIC_LOAD_NILF:
5884     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
5885   case SystemZ::ATOMIC_LOAD_NGR:
5886     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
5887   case SystemZ::ATOMIC_LOAD_NILL64:
5888     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
5889   case SystemZ::ATOMIC_LOAD_NILH64:
5890     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
5891   case SystemZ::ATOMIC_LOAD_NIHL64:
5892     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
5893   case SystemZ::ATOMIC_LOAD_NIHH64:
5894     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
5895   case SystemZ::ATOMIC_LOAD_NILF64:
5896     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
5897   case SystemZ::ATOMIC_LOAD_NIHF64:
5898     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
5899 
5900   case SystemZ::ATOMIC_LOADW_OR:
5901     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
5902   case SystemZ::ATOMIC_LOADW_OILH:
5903     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
5904   case SystemZ::ATOMIC_LOAD_OR:
5905     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
5906   case SystemZ::ATOMIC_LOAD_OILL:
5907     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
5908   case SystemZ::ATOMIC_LOAD_OILH:
5909     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
5910   case SystemZ::ATOMIC_LOAD_OILF:
5911     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
5912   case SystemZ::ATOMIC_LOAD_OGR:
5913     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
5914   case SystemZ::ATOMIC_LOAD_OILL64:
5915     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
5916   case SystemZ::ATOMIC_LOAD_OILH64:
5917     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
5918   case SystemZ::ATOMIC_LOAD_OIHL64:
5919     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
5920   case SystemZ::ATOMIC_LOAD_OIHH64:
5921     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
5922   case SystemZ::ATOMIC_LOAD_OILF64:
5923     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
5924   case SystemZ::ATOMIC_LOAD_OIHF64:
5925     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
5926 
5927   case SystemZ::ATOMIC_LOADW_XR:
5928     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
5929   case SystemZ::ATOMIC_LOADW_XILF:
5930     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
5931   case SystemZ::ATOMIC_LOAD_XR:
5932     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
5933   case SystemZ::ATOMIC_LOAD_XILF:
5934     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
5935   case SystemZ::ATOMIC_LOAD_XGR:
5936     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
5937   case SystemZ::ATOMIC_LOAD_XILF64:
5938     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
5939   case SystemZ::ATOMIC_LOAD_XIHF64:
5940     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
5941 
5942   case SystemZ::ATOMIC_LOADW_NRi:
5943     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
5944   case SystemZ::ATOMIC_LOADW_NILHi:
5945     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
5946   case SystemZ::ATOMIC_LOAD_NRi:
5947     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
5948   case SystemZ::ATOMIC_LOAD_NILLi:
5949     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
5950   case SystemZ::ATOMIC_LOAD_NILHi:
5951     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
5952   case SystemZ::ATOMIC_LOAD_NILFi:
5953     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
5954   case SystemZ::ATOMIC_LOAD_NGRi:
5955     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
5956   case SystemZ::ATOMIC_LOAD_NILL64i:
5957     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
5958   case SystemZ::ATOMIC_LOAD_NILH64i:
5959     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
5960   case SystemZ::ATOMIC_LOAD_NIHL64i:
5961     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
5962   case SystemZ::ATOMIC_LOAD_NIHH64i:
5963     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
5964   case SystemZ::ATOMIC_LOAD_NILF64i:
5965     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
5966   case SystemZ::ATOMIC_LOAD_NIHF64i:
5967     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
5968 
5969   case SystemZ::ATOMIC_LOADW_MIN:
5970     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5971                                 SystemZ::CCMASK_CMP_LE, 0);
5972   case SystemZ::ATOMIC_LOAD_MIN_32:
5973     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5974                                 SystemZ::CCMASK_CMP_LE, 32);
5975   case SystemZ::ATOMIC_LOAD_MIN_64:
5976     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5977                                 SystemZ::CCMASK_CMP_LE, 64);
5978 
5979   case SystemZ::ATOMIC_LOADW_MAX:
5980     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5981                                 SystemZ::CCMASK_CMP_GE, 0);
5982   case SystemZ::ATOMIC_LOAD_MAX_32:
5983     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5984                                 SystemZ::CCMASK_CMP_GE, 32);
5985   case SystemZ::ATOMIC_LOAD_MAX_64:
5986     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5987                                 SystemZ::CCMASK_CMP_GE, 64);
5988 
5989   case SystemZ::ATOMIC_LOADW_UMIN:
5990     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5991                                 SystemZ::CCMASK_CMP_LE, 0);
5992   case SystemZ::ATOMIC_LOAD_UMIN_32:
5993     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5994                                 SystemZ::CCMASK_CMP_LE, 32);
5995   case SystemZ::ATOMIC_LOAD_UMIN_64:
5996     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5997                                 SystemZ::CCMASK_CMP_LE, 64);
5998 
5999   case SystemZ::ATOMIC_LOADW_UMAX:
6000     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6001                                 SystemZ::CCMASK_CMP_GE, 0);
6002   case SystemZ::ATOMIC_LOAD_UMAX_32:
6003     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6004                                 SystemZ::CCMASK_CMP_GE, 32);
6005   case SystemZ::ATOMIC_LOAD_UMAX_64:
6006     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
6007                                 SystemZ::CCMASK_CMP_GE, 64);
6008 
6009   case SystemZ::ATOMIC_CMP_SWAPW:
6010     return emitAtomicCmpSwapW(MI, MBB);
6011   case SystemZ::MVCSequence:
6012   case SystemZ::MVCLoop:
6013     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
6014   case SystemZ::NCSequence:
6015   case SystemZ::NCLoop:
6016     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
6017   case SystemZ::OCSequence:
6018   case SystemZ::OCLoop:
6019     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
6020   case SystemZ::XCSequence:
6021   case SystemZ::XCLoop:
6022     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
6023   case SystemZ::CLCSequence:
6024   case SystemZ::CLCLoop:
6025     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
6026   case SystemZ::CLSTLoop:
6027     return emitStringWrapper(MI, MBB, SystemZ::CLST);
6028   case SystemZ::MVSTLoop:
6029     return emitStringWrapper(MI, MBB, SystemZ::MVST);
6030   case SystemZ::SRSTLoop:
6031     return emitStringWrapper(MI, MBB, SystemZ::SRST);
6032   case SystemZ::TBEGIN:
6033     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
6034   case SystemZ::TBEGIN_nofloat:
6035     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
6036   case SystemZ::TBEGINC:
6037     return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
6038   case SystemZ::LTEBRCompare_VecPseudo:
6039     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
6040   case SystemZ::LTDBRCompare_VecPseudo:
6041     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
6042   case SystemZ::LTXBRCompare_VecPseudo:
6043     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
6044 
6045   default:
6046     llvm_unreachable("Unexpected instr type to insert");
6047   }
6048 }
6049