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