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