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