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