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