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