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