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