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