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