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