1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SystemZTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SystemZISelLowering.h"
15 #include "SystemZCallingConv.h"
16 #include "SystemZConstantPoolValue.h"
17 #include "SystemZMachineFunctionInfo.h"
18 #include "SystemZTargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include <cctype>
26 
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "systemz-lower"
30 
31 namespace {
32 // Represents a sequence for extracting a 0/1 value from an IPM result:
33 // (((X ^ XORValue) + AddValue) >> Bit)
34 struct IPMConversion {
35   IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
36     : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
37 
38   int64_t XORValue;
39   int64_t AddValue;
40   unsigned Bit;
41 };
42 
43 // Represents information about a comparison.
44 struct Comparison {
45   Comparison(SDValue Op0In, SDValue Op1In)
46     : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
47 
48   // The operands to the comparison.
49   SDValue Op0, Op1;
50 
51   // The opcode that should be used to compare Op0 and Op1.
52   unsigned Opcode;
53 
54   // A SystemZICMP value.  Only used for integer comparisons.
55   unsigned ICmpType;
56 
57   // The mask of CC values that Opcode can produce.
58   unsigned CCValid;
59 
60   // The mask of CC values for which the original condition is true.
61   unsigned CCMask;
62 };
63 } // end anonymous namespace
64 
65 // Classify VT as either 32 or 64 bit.
66 static bool is32Bit(EVT VT) {
67   switch (VT.getSimpleVT().SimpleTy) {
68   case MVT::i32:
69     return true;
70   case MVT::i64:
71     return false;
72   default:
73     llvm_unreachable("Unsupported type");
74   }
75 }
76 
77 // Return a version of MachineOperand that can be safely used before the
78 // final use.
79 static MachineOperand earlyUseOperand(MachineOperand Op) {
80   if (Op.isReg())
81     Op.setIsKill(false);
82   return Op;
83 }
84 
85 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM,
86                                              const SystemZSubtarget &STI)
87     : TargetLowering(TM), Subtarget(STI) {
88   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
89 
90   // Set up the register classes.
91   if (Subtarget.hasHighWord())
92     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
93   else
94     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
95   addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
96   if (Subtarget.hasVector()) {
97     addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
98     addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
99   } else {
100     addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
101     addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
102   }
103   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
104 
105   if (Subtarget.hasVector()) {
106     addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
107     addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
108     addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
109     addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
110     addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
111     addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
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(2);
131 
132   // Handle operations that are handled in a similar way for all types.
133   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
134        I <= MVT::LAST_FP_VALUETYPE;
135        ++I) {
136     MVT VT = MVT::SimpleValueType(I);
137     if (isTypeLegal(VT)) {
138       // Lower SET_CC into an IPM-based sequence.
139       setOperationAction(ISD::SETCC, VT, Custom);
140 
141       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
142       setOperationAction(ISD::SELECT, VT, Expand);
143 
144       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
145       setOperationAction(ISD::SELECT_CC, VT, Custom);
146       setOperationAction(ISD::BR_CC,     VT, Custom);
147     }
148   }
149 
150   // Expand jump table branches as address arithmetic followed by an
151   // indirect jump.
152   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
153 
154   // Expand BRCOND into a BR_CC (see above).
155   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
156 
157   // Handle integer types.
158   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
159        I <= MVT::LAST_INTEGER_VALUETYPE;
160        ++I) {
161     MVT VT = MVT::SimpleValueType(I);
162     if (isTypeLegal(VT)) {
163       // Expand individual DIV and REMs into DIVREMs.
164       setOperationAction(ISD::SDIV, VT, Expand);
165       setOperationAction(ISD::UDIV, VT, Expand);
166       setOperationAction(ISD::SREM, VT, Expand);
167       setOperationAction(ISD::UREM, VT, Expand);
168       setOperationAction(ISD::SDIVREM, VT, Custom);
169       setOperationAction(ISD::UDIVREM, VT, Custom);
170 
171       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
172       // stores, putting a serialization instruction after the stores.
173       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
174       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
175 
176       // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
177       // available, or if the operand is constant.
178       setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
179 
180       // Use POPCNT on z196 and above.
181       if (Subtarget.hasPopulationCount())
182         setOperationAction(ISD::CTPOP, VT, Custom);
183       else
184         setOperationAction(ISD::CTPOP, VT, Expand);
185 
186       // No special instructions for these.
187       setOperationAction(ISD::CTTZ,            VT, Expand);
188       setOperationAction(ISD::ROTR,            VT, Expand);
189 
190       // Use *MUL_LOHI where possible instead of MULH*.
191       setOperationAction(ISD::MULHS, VT, Expand);
192       setOperationAction(ISD::MULHU, VT, Expand);
193       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
194       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
195 
196       // Only z196 and above have native support for conversions to unsigned.
197       // On z10, promoting to i64 doesn't generate an inexact condition for
198       // values that are outside the i32 range but in the i64 range, so use
199       // the default expansion.
200       if (!Subtarget.hasFPExtension())
201         setOperationAction(ISD::FP_TO_UINT, VT, Expand);
202     }
203   }
204 
205   // Type legalization will convert 8- and 16-bit atomic operations into
206   // forms that operate on i32s (but still keeping the original memory VT).
207   // Lower them into full i32 operations.
208   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
209   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
210   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
211   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
212   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
213   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
214   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
215   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
216   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
217   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
218   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
219   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
220 
221   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
222 
223   // Traps are legal, as we will convert them to "j .+2".
224   setOperationAction(ISD::TRAP, MVT::Other, Legal);
225 
226   // z10 has instructions for signed but not unsigned FP conversion.
227   // Handle unsigned 32-bit types as signed 64-bit types.
228   if (!Subtarget.hasFPExtension()) {
229     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
230     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
231   }
232 
233   // We have native support for a 64-bit CTLZ, via FLOGR.
234   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
235   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
236 
237   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
238   setOperationAction(ISD::OR, MVT::i64, Custom);
239 
240   // FIXME: Can we support these natively?
241   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
242   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
243   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
244 
245   // We have native instructions for i8, i16 and i32 extensions, but not i1.
246   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
247   for (MVT VT : MVT::integer_valuetypes()) {
248     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
249     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
250     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1, Promote);
251   }
252 
253   // Handle the various types of symbolic address.
254   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
255   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
256   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
257   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
258   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
259 
260   // We need to handle dynamic allocations specially because of the
261   // 160-byte area at the bottom of the stack.
262   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
263   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom);
264 
265   // Use custom expanders so that we can force the function to use
266   // a frame pointer.
267   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
268   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
269 
270   // Handle prefetches with PFD or PFDRL.
271   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
272 
273   for (MVT VT : MVT::vector_valuetypes()) {
274     // Assume by default that all vector operations need to be expanded.
275     for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
276       if (getOperationAction(Opcode, VT) == Legal)
277         setOperationAction(Opcode, VT, Expand);
278 
279     // Likewise all truncating stores and extending loads.
280     for (MVT InnerVT : MVT::vector_valuetypes()) {
281       setTruncStoreAction(VT, InnerVT, Expand);
282       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
283       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
284       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
285     }
286 
287     if (isTypeLegal(VT)) {
288       // These operations are legal for anything that can be stored in a
289       // vector register, even if there is no native support for the format
290       // as such.  In particular, we can do these for v4f32 even though there
291       // are no specific instructions for that format.
292       setOperationAction(ISD::LOAD, VT, Legal);
293       setOperationAction(ISD::STORE, VT, Legal);
294       setOperationAction(ISD::VSELECT, VT, Legal);
295       setOperationAction(ISD::BITCAST, VT, Legal);
296       setOperationAction(ISD::UNDEF, VT, Legal);
297 
298       // Likewise, except that we need to replace the nodes with something
299       // more specific.
300       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
301       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
302     }
303   }
304 
305   // Handle integer vector types.
306   for (MVT VT : MVT::integer_vector_valuetypes()) {
307     if (isTypeLegal(VT)) {
308       // These operations have direct equivalents.
309       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
310       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
311       setOperationAction(ISD::ADD, VT, Legal);
312       setOperationAction(ISD::SUB, VT, Legal);
313       if (VT != MVT::v2i64)
314         setOperationAction(ISD::MUL, VT, Legal);
315       setOperationAction(ISD::AND, VT, Legal);
316       setOperationAction(ISD::OR, VT, Legal);
317       setOperationAction(ISD::XOR, VT, Legal);
318       setOperationAction(ISD::CTPOP, VT, Custom);
319       setOperationAction(ISD::CTTZ, VT, Legal);
320       setOperationAction(ISD::CTLZ, VT, Legal);
321 
322       // Convert a GPR scalar to a vector by inserting it into element 0.
323       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
324 
325       // Use a series of unpacks for extensions.
326       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
327       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
328 
329       // Detect shifts by a scalar amount and convert them into
330       // V*_BY_SCALAR.
331       setOperationAction(ISD::SHL, VT, Custom);
332       setOperationAction(ISD::SRA, VT, Custom);
333       setOperationAction(ISD::SRL, VT, Custom);
334 
335       // At present ROTL isn't matched by DAGCombiner.  ROTR should be
336       // converted into ROTL.
337       setOperationAction(ISD::ROTL, VT, Expand);
338       setOperationAction(ISD::ROTR, VT, Expand);
339 
340       // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
341       // and inverting the result as necessary.
342       setOperationAction(ISD::SETCC, VT, Custom);
343     }
344   }
345 
346   if (Subtarget.hasVector()) {
347     // There should be no need to check for float types other than v2f64
348     // since <2 x f32> isn't a legal type.
349     setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
350     setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
351     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
352     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
353   }
354 
355   // Handle floating-point types.
356   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
357        I <= MVT::LAST_FP_VALUETYPE;
358        ++I) {
359     MVT VT = MVT::SimpleValueType(I);
360     if (isTypeLegal(VT)) {
361       // We can use FI for FRINT.
362       setOperationAction(ISD::FRINT, VT, Legal);
363 
364       // We can use the extended form of FI for other rounding operations.
365       if (Subtarget.hasFPExtension()) {
366         setOperationAction(ISD::FNEARBYINT, VT, Legal);
367         setOperationAction(ISD::FFLOOR, VT, Legal);
368         setOperationAction(ISD::FCEIL, VT, Legal);
369         setOperationAction(ISD::FTRUNC, VT, Legal);
370         setOperationAction(ISD::FROUND, VT, Legal);
371       }
372 
373       // No special instructions for these.
374       setOperationAction(ISD::FSIN, VT, Expand);
375       setOperationAction(ISD::FCOS, VT, Expand);
376       setOperationAction(ISD::FSINCOS, VT, Expand);
377       setOperationAction(ISD::FREM, VT, Expand);
378       setOperationAction(ISD::FPOW, VT, Expand);
379     }
380   }
381 
382   // Handle floating-point vector types.
383   if (Subtarget.hasVector()) {
384     // Scalar-to-vector conversion is just a subreg.
385     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
386     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
387 
388     // Some insertions and extractions can be done directly but others
389     // need to go via integers.
390     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
391     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
392     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
393     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
394 
395     // These operations have direct equivalents.
396     setOperationAction(ISD::FADD, MVT::v2f64, Legal);
397     setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
398     setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
399     setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
400     setOperationAction(ISD::FMA, MVT::v2f64, Legal);
401     setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
402     setOperationAction(ISD::FABS, MVT::v2f64, Legal);
403     setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
404     setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
405     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
406     setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
407     setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
408     setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
409     setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
410   }
411 
412   // We have fused multiply-addition for f32 and f64 but not f128.
413   setOperationAction(ISD::FMA, MVT::f32,  Legal);
414   setOperationAction(ISD::FMA, MVT::f64,  Legal);
415   setOperationAction(ISD::FMA, MVT::f128, Expand);
416 
417   // Needed so that we don't try to implement f128 constant loads using
418   // a load-and-extend of a f80 constant (in cases where the constant
419   // would fit in an f80).
420   for (MVT VT : MVT::fp_valuetypes())
421     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
422 
423   // Floating-point truncation and stores need to be done separately.
424   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
425   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
426   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
427 
428   // We have 64-bit FPR<->GPR moves, but need special handling for
429   // 32-bit forms.
430   if (!Subtarget.hasVector()) {
431     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
432     setOperationAction(ISD::BITCAST, MVT::f32, Custom);
433   }
434 
435   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
436   // structure, but VAEND is a no-op.
437   setOperationAction(ISD::VASTART, MVT::Other, Custom);
438   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
439   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
440 
441   // Codes for which we want to perform some z-specific combinations.
442   setTargetDAGCombine(ISD::SIGN_EXTEND);
443   setTargetDAGCombine(ISD::STORE);
444   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
445   setTargetDAGCombine(ISD::FP_ROUND);
446   setTargetDAGCombine(ISD::BSWAP);
447   setTargetDAGCombine(ISD::SHL);
448   setTargetDAGCombine(ISD::SRA);
449   setTargetDAGCombine(ISD::SRL);
450   setTargetDAGCombine(ISD::ROTL);
451 
452   // Handle intrinsics.
453   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
454   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
455 
456   // We want to use MVC in preference to even a single load/store pair.
457   MaxStoresPerMemcpy = 0;
458   MaxStoresPerMemcpyOptSize = 0;
459 
460   // The main memset sequence is a byte store followed by an MVC.
461   // Two STC or MV..I stores win over that, but the kind of fused stores
462   // generated by target-independent code don't when the byte value is
463   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
464   // than "STC;MVC".  Handle the choice in target-specific code instead.
465   MaxStoresPerMemset = 0;
466   MaxStoresPerMemsetOptSize = 0;
467 }
468 
469 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
470                                               LLVMContext &, EVT VT) const {
471   if (!VT.isVector())
472     return MVT::i32;
473   return VT.changeVectorElementTypeToInteger();
474 }
475 
476 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
477   VT = VT.getScalarType();
478 
479   if (!VT.isSimple())
480     return false;
481 
482   switch (VT.getSimpleVT().SimpleTy) {
483   case MVT::f32:
484   case MVT::f64:
485     return true;
486   case MVT::f128:
487     return false;
488   default:
489     break;
490   }
491 
492   return false;
493 }
494 
495 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
496   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
497   return Imm.isZero() || Imm.isNegZero();
498 }
499 
500 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
501   // We can use CGFI or CLGFI.
502   return isInt<32>(Imm) || isUInt<32>(Imm);
503 }
504 
505 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
506   // We can use ALGFI or SLGFI.
507   return isUInt<32>(Imm) || isUInt<32>(-Imm);
508 }
509 
510 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
511                                                            unsigned,
512                                                            unsigned,
513                                                            bool *Fast) const {
514   // Unaligned accesses should never be slower than the expanded version.
515   // We check specifically for aligned accesses in the few cases where
516   // they are required.
517   if (Fast)
518     *Fast = true;
519   return true;
520 }
521 
522 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
523                                                   const AddrMode &AM, Type *Ty,
524                                                   unsigned AS) const {
525   // Punt on globals for now, although they can be used in limited
526   // RELATIVE LONG cases.
527   if (AM.BaseGV)
528     return false;
529 
530   // Require a 20-bit signed offset.
531   if (!isInt<20>(AM.BaseOffs))
532     return false;
533 
534   // Indexing is OK but no scale factor can be applied.
535   return AM.Scale == 0 || AM.Scale == 1;
536 }
537 
538 bool SystemZTargetLowering::isFoldableMemAccessOffset(Instruction *I,
539                                                       int64_t Offset) const {
540   // This only applies to z13.
541   if (!Subtarget.hasVector())
542     return true;
543 
544   // * Use LDE instead of LE/LEY to avoid partial register
545   //   dependencies (LDE only supports small offsets).
546   // * Utilize the vector registers to hold floating point
547   //   values (vector load / store instructions only support small
548   //   offsets).
549 
550   assert (isa<LoadInst>(I) || isa<StoreInst>(I));
551   Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
552                        I->getOperand(0)->getType());
553   bool IsFPAccess = MemAccessTy->isFloatingPointTy();
554   bool IsVectorAccess = MemAccessTy->isVectorTy();
555 
556   // A store of an extracted vector element will be combined into a VSTE type
557   // instruction.
558   if (!IsVectorAccess && isa<StoreInst>(I)) {
559     Value *DataOp = I->getOperand(0);
560     if (isa<ExtractElementInst>(DataOp))
561       IsVectorAccess = true;
562   }
563 
564   // A load which gets inserted into a vector element will be combined into a
565   // VLE type instruction.
566   if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
567     User *LoadUser = *I->user_begin();
568     if (isa<InsertElementInst>(LoadUser))
569       IsVectorAccess = true;
570   }
571 
572   if (!isUInt<12>(Offset) && (IsFPAccess || IsVectorAccess))
573     return false;
574 
575   return true;
576 }
577 
578 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
579   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
580     return false;
581   unsigned FromBits = FromType->getPrimitiveSizeInBits();
582   unsigned ToBits = ToType->getPrimitiveSizeInBits();
583   return FromBits > ToBits;
584 }
585 
586 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
587   if (!FromVT.isInteger() || !ToVT.isInteger())
588     return false;
589   unsigned FromBits = FromVT.getSizeInBits();
590   unsigned ToBits = ToVT.getSizeInBits();
591   return FromBits > ToBits;
592 }
593 
594 //===----------------------------------------------------------------------===//
595 // Inline asm support
596 //===----------------------------------------------------------------------===//
597 
598 TargetLowering::ConstraintType
599 SystemZTargetLowering::getConstraintType(StringRef Constraint) const {
600   if (Constraint.size() == 1) {
601     switch (Constraint[0]) {
602     case 'a': // Address register
603     case 'd': // Data register (equivalent to 'r')
604     case 'f': // Floating-point register
605     case 'h': // High-part register
606     case 'r': // General-purpose register
607       return C_RegisterClass;
608 
609     case 'Q': // Memory with base and unsigned 12-bit displacement
610     case 'R': // Likewise, plus an index
611     case 'S': // Memory with base and signed 20-bit displacement
612     case 'T': // Likewise, plus an index
613     case 'm': // Equivalent to 'T'.
614       return C_Memory;
615 
616     case 'I': // Unsigned 8-bit constant
617     case 'J': // Unsigned 12-bit constant
618     case 'K': // Signed 16-bit constant
619     case 'L': // Signed 20-bit displacement (on all targets we support)
620     case 'M': // 0x7fffffff
621       return C_Other;
622 
623     default:
624       break;
625     }
626   }
627   return TargetLowering::getConstraintType(Constraint);
628 }
629 
630 TargetLowering::ConstraintWeight SystemZTargetLowering::
631 getSingleConstraintMatchWeight(AsmOperandInfo &info,
632                                const char *constraint) const {
633   ConstraintWeight weight = CW_Invalid;
634   Value *CallOperandVal = info.CallOperandVal;
635   // If we don't have a value, we can't do a match,
636   // but allow it at the lowest weight.
637   if (!CallOperandVal)
638     return CW_Default;
639   Type *type = CallOperandVal->getType();
640   // Look at the constraint type.
641   switch (*constraint) {
642   default:
643     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
644     break;
645 
646   case 'a': // Address register
647   case 'd': // Data register (equivalent to 'r')
648   case 'h': // High-part register
649   case 'r': // General-purpose register
650     if (CallOperandVal->getType()->isIntegerTy())
651       weight = CW_Register;
652     break;
653 
654   case 'f': // Floating-point register
655     if (type->isFloatingPointTy())
656       weight = CW_Register;
657     break;
658 
659   case 'I': // Unsigned 8-bit constant
660     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
661       if (isUInt<8>(C->getZExtValue()))
662         weight = CW_Constant;
663     break;
664 
665   case 'J': // Unsigned 12-bit constant
666     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
667       if (isUInt<12>(C->getZExtValue()))
668         weight = CW_Constant;
669     break;
670 
671   case 'K': // Signed 16-bit constant
672     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
673       if (isInt<16>(C->getSExtValue()))
674         weight = CW_Constant;
675     break;
676 
677   case 'L': // Signed 20-bit displacement (on all targets we support)
678     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
679       if (isInt<20>(C->getSExtValue()))
680         weight = CW_Constant;
681     break;
682 
683   case 'M': // 0x7fffffff
684     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
685       if (C->getZExtValue() == 0x7fffffff)
686         weight = CW_Constant;
687     break;
688   }
689   return weight;
690 }
691 
692 // Parse a "{tNNN}" register constraint for which the register type "t"
693 // has already been verified.  MC is the class associated with "t" and
694 // Map maps 0-based register numbers to LLVM register numbers.
695 static std::pair<unsigned, const TargetRegisterClass *>
696 parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC,
697                     const unsigned *Map) {
698   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
699   if (isdigit(Constraint[2])) {
700     unsigned Index;
701     bool Failed =
702         Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
703     if (!Failed && Index < 16 && Map[Index])
704       return std::make_pair(Map[Index], RC);
705   }
706   return std::make_pair(0U, nullptr);
707 }
708 
709 std::pair<unsigned, const TargetRegisterClass *>
710 SystemZTargetLowering::getRegForInlineAsmConstraint(
711     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
712   if (Constraint.size() == 1) {
713     // GCC Constraint Letters
714     switch (Constraint[0]) {
715     default: break;
716     case 'd': // Data register (equivalent to 'r')
717     case 'r': // General-purpose register
718       if (VT == MVT::i64)
719         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
720       else if (VT == MVT::i128)
721         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
722       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
723 
724     case 'a': // Address register
725       if (VT == MVT::i64)
726         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
727       else if (VT == MVT::i128)
728         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
729       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
730 
731     case 'h': // High-part register (an LLVM extension)
732       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
733 
734     case 'f': // Floating-point register
735       if (VT == MVT::f64)
736         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
737       else if (VT == MVT::f128)
738         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
739       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
740     }
741   }
742   if (Constraint.size() > 0 && Constraint[0] == '{') {
743     // We need to override the default register parsing for GPRs and FPRs
744     // because the interpretation depends on VT.  The internal names of
745     // the registers are also different from the external names
746     // (F0D and F0S instead of F0, etc.).
747     if (Constraint[1] == 'r') {
748       if (VT == MVT::i32)
749         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
750                                    SystemZMC::GR32Regs);
751       if (VT == MVT::i128)
752         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
753                                    SystemZMC::GR128Regs);
754       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
755                                  SystemZMC::GR64Regs);
756     }
757     if (Constraint[1] == 'f') {
758       if (VT == MVT::f32)
759         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
760                                    SystemZMC::FP32Regs);
761       if (VT == MVT::f128)
762         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
763                                    SystemZMC::FP128Regs);
764       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
765                                  SystemZMC::FP64Regs);
766     }
767   }
768   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
769 }
770 
771 void SystemZTargetLowering::
772 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
773                              std::vector<SDValue> &Ops,
774                              SelectionDAG &DAG) const {
775   // Only support length 1 constraints for now.
776   if (Constraint.length() == 1) {
777     switch (Constraint[0]) {
778     case 'I': // Unsigned 8-bit constant
779       if (auto *C = dyn_cast<ConstantSDNode>(Op))
780         if (isUInt<8>(C->getZExtValue()))
781           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
782                                               Op.getValueType()));
783       return;
784 
785     case 'J': // Unsigned 12-bit constant
786       if (auto *C = dyn_cast<ConstantSDNode>(Op))
787         if (isUInt<12>(C->getZExtValue()))
788           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
789                                               Op.getValueType()));
790       return;
791 
792     case 'K': // Signed 16-bit constant
793       if (auto *C = dyn_cast<ConstantSDNode>(Op))
794         if (isInt<16>(C->getSExtValue()))
795           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
796                                               Op.getValueType()));
797       return;
798 
799     case 'L': // Signed 20-bit displacement (on all targets we support)
800       if (auto *C = dyn_cast<ConstantSDNode>(Op))
801         if (isInt<20>(C->getSExtValue()))
802           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
803                                               Op.getValueType()));
804       return;
805 
806     case 'M': // 0x7fffffff
807       if (auto *C = dyn_cast<ConstantSDNode>(Op))
808         if (C->getZExtValue() == 0x7fffffff)
809           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
810                                               Op.getValueType()));
811       return;
812     }
813   }
814   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
815 }
816 
817 //===----------------------------------------------------------------------===//
818 // Calling conventions
819 //===----------------------------------------------------------------------===//
820 
821 #include "SystemZGenCallingConv.inc"
822 
823 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
824                                                      Type *ToType) const {
825   return isTruncateFree(FromType, ToType);
826 }
827 
828 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
829   return CI->isTailCall();
830 }
831 
832 // We do not yet support 128-bit single-element vector types.  If the user
833 // attempts to use such types as function argument or return type, prefer
834 // to error out instead of emitting code violating the ABI.
835 static void VerifyVectorType(MVT VT, EVT ArgVT) {
836   if (ArgVT.isVector() && !VT.isVector())
837     report_fatal_error("Unsupported vector argument or return type");
838 }
839 
840 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
841   for (unsigned i = 0; i < Ins.size(); ++i)
842     VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
843 }
844 
845 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
846   for (unsigned i = 0; i < Outs.size(); ++i)
847     VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
848 }
849 
850 // Value is a value that has been passed to us in the location described by VA
851 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
852 // any loads onto Chain.
853 static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL,
854                                    CCValAssign &VA, SDValue Chain,
855                                    SDValue Value) {
856   // If the argument has been promoted from a smaller type, insert an
857   // assertion to capture this.
858   if (VA.getLocInfo() == CCValAssign::SExt)
859     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
860                         DAG.getValueType(VA.getValVT()));
861   else if (VA.getLocInfo() == CCValAssign::ZExt)
862     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
863                         DAG.getValueType(VA.getValVT()));
864 
865   if (VA.isExtInLoc())
866     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
867   else if (VA.getLocInfo() == CCValAssign::BCvt) {
868     // If this is a short vector argument loaded from the stack,
869     // extend from i64 to full vector size and then bitcast.
870     assert(VA.getLocVT() == MVT::i64);
871     assert(VA.getValVT().isVector());
872     Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
873     Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
874   } else
875     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
876   return Value;
877 }
878 
879 // Value is a value of type VA.getValVT() that we need to copy into
880 // the location described by VA.  Return a copy of Value converted to
881 // VA.getValVT().  The caller is responsible for handling indirect values.
882 static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL,
883                                    CCValAssign &VA, SDValue Value) {
884   switch (VA.getLocInfo()) {
885   case CCValAssign::SExt:
886     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
887   case CCValAssign::ZExt:
888     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
889   case CCValAssign::AExt:
890     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
891   case CCValAssign::BCvt:
892     // If this is a short vector argument to be stored to the stack,
893     // bitcast to v2i64 and then extract first element.
894     assert(VA.getLocVT() == MVT::i64);
895     assert(VA.getValVT().isVector());
896     Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
897     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
898                        DAG.getConstant(0, DL, MVT::i32));
899   case CCValAssign::Full:
900     return Value;
901   default:
902     llvm_unreachable("Unhandled getLocInfo()");
903   }
904 }
905 
906 SDValue SystemZTargetLowering::LowerFormalArguments(
907     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
908     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
909     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
910   MachineFunction &MF = DAG.getMachineFunction();
911   MachineFrameInfo &MFI = MF.getFrameInfo();
912   MachineRegisterInfo &MRI = MF.getRegInfo();
913   SystemZMachineFunctionInfo *FuncInfo =
914       MF.getInfo<SystemZMachineFunctionInfo>();
915   auto *TFL =
916       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
917   EVT PtrVT = getPointerTy(DAG.getDataLayout());
918 
919   // Detect unsupported vector argument types.
920   if (Subtarget.hasVector())
921     VerifyVectorTypes(Ins);
922 
923   // Assign locations to all of the incoming arguments.
924   SmallVector<CCValAssign, 16> ArgLocs;
925   SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
926   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
927 
928   unsigned NumFixedGPRs = 0;
929   unsigned NumFixedFPRs = 0;
930   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
931     SDValue ArgValue;
932     CCValAssign &VA = ArgLocs[I];
933     EVT LocVT = VA.getLocVT();
934     if (VA.isRegLoc()) {
935       // Arguments passed in registers
936       const TargetRegisterClass *RC;
937       switch (LocVT.getSimpleVT().SimpleTy) {
938       default:
939         // Integers smaller than i64 should be promoted to i64.
940         llvm_unreachable("Unexpected argument type");
941       case MVT::i32:
942         NumFixedGPRs += 1;
943         RC = &SystemZ::GR32BitRegClass;
944         break;
945       case MVT::i64:
946         NumFixedGPRs += 1;
947         RC = &SystemZ::GR64BitRegClass;
948         break;
949       case MVT::f32:
950         NumFixedFPRs += 1;
951         RC = &SystemZ::FP32BitRegClass;
952         break;
953       case MVT::f64:
954         NumFixedFPRs += 1;
955         RC = &SystemZ::FP64BitRegClass;
956         break;
957       case MVT::v16i8:
958       case MVT::v8i16:
959       case MVT::v4i32:
960       case MVT::v2i64:
961       case MVT::v4f32:
962       case MVT::v2f64:
963         RC = &SystemZ::VR128BitRegClass;
964         break;
965       }
966 
967       unsigned VReg = MRI.createVirtualRegister(RC);
968       MRI.addLiveIn(VA.getLocReg(), VReg);
969       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
970     } else {
971       assert(VA.isMemLoc() && "Argument not register or memory");
972 
973       // Create the frame index object for this incoming parameter.
974       int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
975                                      VA.getLocMemOffset(), true);
976 
977       // Create the SelectionDAG nodes corresponding to a load
978       // from this parameter.  Unpromoted ints and floats are
979       // passed as right-justified 8-byte values.
980       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
981       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
982         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
983                           DAG.getIntPtrConstant(4, DL));
984       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
985                              MachinePointerInfo::getFixedStack(MF, FI));
986     }
987 
988     // Convert the value of the argument register into the value that's
989     // being passed.
990     if (VA.getLocInfo() == CCValAssign::Indirect) {
991       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
992                                    MachinePointerInfo()));
993       // If the original argument was split (e.g. i128), we need
994       // to load all parts of it here (using the same address).
995       unsigned ArgIndex = Ins[I].OrigArgIndex;
996       assert (Ins[I].PartOffset == 0);
997       while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
998         CCValAssign &PartVA = ArgLocs[I + 1];
999         unsigned PartOffset = Ins[I + 1].PartOffset;
1000         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1001                                       DAG.getIntPtrConstant(PartOffset, DL));
1002         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1003                                      MachinePointerInfo()));
1004         ++I;
1005       }
1006     } else
1007       InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1008   }
1009 
1010   if (IsVarArg) {
1011     // Save the number of non-varargs registers for later use by va_start, etc.
1012     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1013     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1014 
1015     // Likewise the address (in the form of a frame index) of where the
1016     // first stack vararg would be.  The 1-byte size here is arbitrary.
1017     int64_t StackSize = CCInfo.getNextStackOffset();
1018     FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1019 
1020     // ...and a similar frame index for the caller-allocated save area
1021     // that will be used to store the incoming registers.
1022     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
1023     unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1024     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1025 
1026     // Store the FPR varargs in the reserved frame slots.  (We store the
1027     // GPRs as part of the prologue.)
1028     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
1029       SDValue MemOps[SystemZ::NumArgFPRs];
1030       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
1031         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
1032         int FI = MFI.CreateFixedObject(8, RegSaveOffset + Offset, true);
1033         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1034         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
1035                                      &SystemZ::FP64BitRegClass);
1036         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1037         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1038                                  MachinePointerInfo::getFixedStack(MF, FI));
1039       }
1040       // Join the stores, which are independent of one another.
1041       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1042                           makeArrayRef(&MemOps[NumFixedFPRs],
1043                                        SystemZ::NumArgFPRs-NumFixedFPRs));
1044     }
1045   }
1046 
1047   return Chain;
1048 }
1049 
1050 static bool canUseSiblingCall(const CCState &ArgCCInfo,
1051                               SmallVectorImpl<CCValAssign> &ArgLocs,
1052                               SmallVectorImpl<ISD::OutputArg> &Outs) {
1053   // Punt if there are any indirect or stack arguments, or if the call
1054   // needs the callee-saved argument register R6, or if the call uses
1055   // the callee-saved register arguments SwiftSelf and SwiftError.
1056   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1057     CCValAssign &VA = ArgLocs[I];
1058     if (VA.getLocInfo() == CCValAssign::Indirect)
1059       return false;
1060     if (!VA.isRegLoc())
1061       return false;
1062     unsigned Reg = VA.getLocReg();
1063     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1064       return false;
1065     if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1066       return false;
1067   }
1068   return true;
1069 }
1070 
1071 SDValue
1072 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1073                                  SmallVectorImpl<SDValue> &InVals) const {
1074   SelectionDAG &DAG = CLI.DAG;
1075   SDLoc &DL = CLI.DL;
1076   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1077   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1078   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1079   SDValue Chain = CLI.Chain;
1080   SDValue Callee = CLI.Callee;
1081   bool &IsTailCall = CLI.IsTailCall;
1082   CallingConv::ID CallConv = CLI.CallConv;
1083   bool IsVarArg = CLI.IsVarArg;
1084   MachineFunction &MF = DAG.getMachineFunction();
1085   EVT PtrVT = getPointerTy(MF.getDataLayout());
1086 
1087   // Detect unsupported vector argument and return types.
1088   if (Subtarget.hasVector()) {
1089     VerifyVectorTypes(Outs);
1090     VerifyVectorTypes(Ins);
1091   }
1092 
1093   // Analyze the operands of the call, assigning locations to each operand.
1094   SmallVector<CCValAssign, 16> ArgLocs;
1095   SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1096   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1097 
1098   // We don't support GuaranteedTailCallOpt, only automatically-detected
1099   // sibling calls.
1100   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1101     IsTailCall = false;
1102 
1103   // Get a count of how many bytes are to be pushed on the stack.
1104   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1105 
1106   // Mark the start of the call.
1107   if (!IsTailCall)
1108     Chain = DAG.getCALLSEQ_START(Chain,
1109                                  DAG.getConstant(NumBytes, DL, PtrVT, true),
1110                                  DL);
1111 
1112   // Copy argument values to their designated locations.
1113   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1114   SmallVector<SDValue, 8> MemOpChains;
1115   SDValue StackPtr;
1116   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1117     CCValAssign &VA = ArgLocs[I];
1118     SDValue ArgValue = OutVals[I];
1119 
1120     if (VA.getLocInfo() == CCValAssign::Indirect) {
1121       // Store the argument in a stack slot and pass its address.
1122       SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1123       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1124       MemOpChains.push_back(
1125           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1126                        MachinePointerInfo::getFixedStack(MF, FI)));
1127       // If the original argument was split (e.g. i128), we need
1128       // to store all parts of it here (and pass just one address).
1129       unsigned ArgIndex = Outs[I].OrigArgIndex;
1130       assert (Outs[I].PartOffset == 0);
1131       while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1132         SDValue PartValue = OutVals[I + 1];
1133         unsigned PartOffset = Outs[I + 1].PartOffset;
1134         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1135                                       DAG.getIntPtrConstant(PartOffset, DL));
1136         MemOpChains.push_back(
1137             DAG.getStore(Chain, DL, PartValue, Address,
1138                          MachinePointerInfo::getFixedStack(MF, FI)));
1139         ++I;
1140       }
1141       ArgValue = SpillSlot;
1142     } else
1143       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1144 
1145     if (VA.isRegLoc())
1146       // Queue up the argument copies and emit them at the end.
1147       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1148     else {
1149       assert(VA.isMemLoc() && "Argument not register or memory");
1150 
1151       // Work out the address of the stack slot.  Unpromoted ints and
1152       // floats are passed as right-justified 8-byte values.
1153       if (!StackPtr.getNode())
1154         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1155       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1156       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1157         Offset += 4;
1158       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1159                                     DAG.getIntPtrConstant(Offset, DL));
1160 
1161       // Emit the store.
1162       MemOpChains.push_back(
1163           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1164     }
1165   }
1166 
1167   // Join the stores, which are independent of one another.
1168   if (!MemOpChains.empty())
1169     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1170 
1171   // Accept direct calls by converting symbolic call addresses to the
1172   // associated Target* opcodes.  Force %r1 to be used for indirect
1173   // tail calls.
1174   SDValue Glue;
1175   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1176     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1177     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1178   } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1179     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1180     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1181   } else if (IsTailCall) {
1182     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1183     Glue = Chain.getValue(1);
1184     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1185   }
1186 
1187   // Build a sequence of copy-to-reg nodes, chained and glued together.
1188   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1189     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1190                              RegsToPass[I].second, Glue);
1191     Glue = Chain.getValue(1);
1192   }
1193 
1194   // The first call operand is the chain and the second is the target address.
1195   SmallVector<SDValue, 8> Ops;
1196   Ops.push_back(Chain);
1197   Ops.push_back(Callee);
1198 
1199   // Add argument registers to the end of the list so that they are
1200   // known live into the call.
1201   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1202     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1203                                   RegsToPass[I].second.getValueType()));
1204 
1205   // Add a register mask operand representing the call-preserved registers.
1206   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1207   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1208   assert(Mask && "Missing call preserved mask for calling convention");
1209   Ops.push_back(DAG.getRegisterMask(Mask));
1210 
1211   // Glue the call to the argument copies, if any.
1212   if (Glue.getNode())
1213     Ops.push_back(Glue);
1214 
1215   // Emit the call.
1216   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1217   if (IsTailCall)
1218     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1219   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1220   Glue = Chain.getValue(1);
1221 
1222   // Mark the end of the call, which is glued to the call itself.
1223   Chain = DAG.getCALLSEQ_END(Chain,
1224                              DAG.getConstant(NumBytes, DL, PtrVT, true),
1225                              DAG.getConstant(0, DL, PtrVT, true),
1226                              Glue, DL);
1227   Glue = Chain.getValue(1);
1228 
1229   // Assign locations to each value returned by this call.
1230   SmallVector<CCValAssign, 16> RetLocs;
1231   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1232   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1233 
1234   // Copy all of the result registers out of their specified physreg.
1235   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1236     CCValAssign &VA = RetLocs[I];
1237 
1238     // Copy the value out, gluing the copy to the end of the call sequence.
1239     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1240                                           VA.getLocVT(), Glue);
1241     Chain = RetValue.getValue(1);
1242     Glue = RetValue.getValue(2);
1243 
1244     // Convert the value of the return register into the value that's
1245     // being returned.
1246     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1247   }
1248 
1249   return Chain;
1250 }
1251 
1252 bool SystemZTargetLowering::
1253 CanLowerReturn(CallingConv::ID CallConv,
1254                MachineFunction &MF, bool isVarArg,
1255                const SmallVectorImpl<ISD::OutputArg> &Outs,
1256                LLVMContext &Context) const {
1257   // Detect unsupported vector return types.
1258   if (Subtarget.hasVector())
1259     VerifyVectorTypes(Outs);
1260 
1261   // Special case that we cannot easily detect in RetCC_SystemZ since
1262   // i128 is not a legal type.
1263   for (auto &Out : Outs)
1264     if (Out.ArgVT == MVT::i128)
1265       return false;
1266 
1267   SmallVector<CCValAssign, 16> RetLocs;
1268   CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1269   return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1270 }
1271 
1272 SDValue
1273 SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1274                                    bool IsVarArg,
1275                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1276                                    const SmallVectorImpl<SDValue> &OutVals,
1277                                    const SDLoc &DL, SelectionDAG &DAG) const {
1278   MachineFunction &MF = DAG.getMachineFunction();
1279 
1280   // Detect unsupported vector return types.
1281   if (Subtarget.hasVector())
1282     VerifyVectorTypes(Outs);
1283 
1284   // Assign locations to each returned value.
1285   SmallVector<CCValAssign, 16> RetLocs;
1286   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1287   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1288 
1289   // Quick exit for void returns
1290   if (RetLocs.empty())
1291     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1292 
1293   // Copy the result values into the output registers.
1294   SDValue Glue;
1295   SmallVector<SDValue, 4> RetOps;
1296   RetOps.push_back(Chain);
1297   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1298     CCValAssign &VA = RetLocs[I];
1299     SDValue RetValue = OutVals[I];
1300 
1301     // Make the return register live on exit.
1302     assert(VA.isRegLoc() && "Can only return in registers!");
1303 
1304     // Promote the value as required.
1305     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1306 
1307     // Chain and glue the copies together.
1308     unsigned Reg = VA.getLocReg();
1309     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1310     Glue = Chain.getValue(1);
1311     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1312   }
1313 
1314   // Update chain and glue.
1315   RetOps[0] = Chain;
1316   if (Glue.getNode())
1317     RetOps.push_back(Glue);
1318 
1319   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1320 }
1321 
1322 SDValue SystemZTargetLowering::prepareVolatileOrAtomicLoad(
1323     SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const {
1324   return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1325 }
1326 
1327 // Return true if Op is an intrinsic node with chain that returns the CC value
1328 // as its only (other) argument.  Provide the associated SystemZISD opcode and
1329 // the mask of valid CC values if so.
1330 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1331                                       unsigned &CCValid) {
1332   unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1333   switch (Id) {
1334   case Intrinsic::s390_tbegin:
1335     Opcode = SystemZISD::TBEGIN;
1336     CCValid = SystemZ::CCMASK_TBEGIN;
1337     return true;
1338 
1339   case Intrinsic::s390_tbegin_nofloat:
1340     Opcode = SystemZISD::TBEGIN_NOFLOAT;
1341     CCValid = SystemZ::CCMASK_TBEGIN;
1342     return true;
1343 
1344   case Intrinsic::s390_tend:
1345     Opcode = SystemZISD::TEND;
1346     CCValid = SystemZ::CCMASK_TEND;
1347     return true;
1348 
1349   default:
1350     return false;
1351   }
1352 }
1353 
1354 // Return true if Op is an intrinsic node without chain that returns the
1355 // CC value as its final argument.  Provide the associated SystemZISD
1356 // opcode and the mask of valid CC values if so.
1357 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1358   unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1359   switch (Id) {
1360   case Intrinsic::s390_vpkshs:
1361   case Intrinsic::s390_vpksfs:
1362   case Intrinsic::s390_vpksgs:
1363     Opcode = SystemZISD::PACKS_CC;
1364     CCValid = SystemZ::CCMASK_VCMP;
1365     return true;
1366 
1367   case Intrinsic::s390_vpklshs:
1368   case Intrinsic::s390_vpklsfs:
1369   case Intrinsic::s390_vpklsgs:
1370     Opcode = SystemZISD::PACKLS_CC;
1371     CCValid = SystemZ::CCMASK_VCMP;
1372     return true;
1373 
1374   case Intrinsic::s390_vceqbs:
1375   case Intrinsic::s390_vceqhs:
1376   case Intrinsic::s390_vceqfs:
1377   case Intrinsic::s390_vceqgs:
1378     Opcode = SystemZISD::VICMPES;
1379     CCValid = SystemZ::CCMASK_VCMP;
1380     return true;
1381 
1382   case Intrinsic::s390_vchbs:
1383   case Intrinsic::s390_vchhs:
1384   case Intrinsic::s390_vchfs:
1385   case Intrinsic::s390_vchgs:
1386     Opcode = SystemZISD::VICMPHS;
1387     CCValid = SystemZ::CCMASK_VCMP;
1388     return true;
1389 
1390   case Intrinsic::s390_vchlbs:
1391   case Intrinsic::s390_vchlhs:
1392   case Intrinsic::s390_vchlfs:
1393   case Intrinsic::s390_vchlgs:
1394     Opcode = SystemZISD::VICMPHLS;
1395     CCValid = SystemZ::CCMASK_VCMP;
1396     return true;
1397 
1398   case Intrinsic::s390_vtm:
1399     Opcode = SystemZISD::VTM;
1400     CCValid = SystemZ::CCMASK_VCMP;
1401     return true;
1402 
1403   case Intrinsic::s390_vfaebs:
1404   case Intrinsic::s390_vfaehs:
1405   case Intrinsic::s390_vfaefs:
1406     Opcode = SystemZISD::VFAE_CC;
1407     CCValid = SystemZ::CCMASK_ANY;
1408     return true;
1409 
1410   case Intrinsic::s390_vfaezbs:
1411   case Intrinsic::s390_vfaezhs:
1412   case Intrinsic::s390_vfaezfs:
1413     Opcode = SystemZISD::VFAEZ_CC;
1414     CCValid = SystemZ::CCMASK_ANY;
1415     return true;
1416 
1417   case Intrinsic::s390_vfeebs:
1418   case Intrinsic::s390_vfeehs:
1419   case Intrinsic::s390_vfeefs:
1420     Opcode = SystemZISD::VFEE_CC;
1421     CCValid = SystemZ::CCMASK_ANY;
1422     return true;
1423 
1424   case Intrinsic::s390_vfeezbs:
1425   case Intrinsic::s390_vfeezhs:
1426   case Intrinsic::s390_vfeezfs:
1427     Opcode = SystemZISD::VFEEZ_CC;
1428     CCValid = SystemZ::CCMASK_ANY;
1429     return true;
1430 
1431   case Intrinsic::s390_vfenebs:
1432   case Intrinsic::s390_vfenehs:
1433   case Intrinsic::s390_vfenefs:
1434     Opcode = SystemZISD::VFENE_CC;
1435     CCValid = SystemZ::CCMASK_ANY;
1436     return true;
1437 
1438   case Intrinsic::s390_vfenezbs:
1439   case Intrinsic::s390_vfenezhs:
1440   case Intrinsic::s390_vfenezfs:
1441     Opcode = SystemZISD::VFENEZ_CC;
1442     CCValid = SystemZ::CCMASK_ANY;
1443     return true;
1444 
1445   case Intrinsic::s390_vistrbs:
1446   case Intrinsic::s390_vistrhs:
1447   case Intrinsic::s390_vistrfs:
1448     Opcode = SystemZISD::VISTR_CC;
1449     CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
1450     return true;
1451 
1452   case Intrinsic::s390_vstrcbs:
1453   case Intrinsic::s390_vstrchs:
1454   case Intrinsic::s390_vstrcfs:
1455     Opcode = SystemZISD::VSTRC_CC;
1456     CCValid = SystemZ::CCMASK_ANY;
1457     return true;
1458 
1459   case Intrinsic::s390_vstrczbs:
1460   case Intrinsic::s390_vstrczhs:
1461   case Intrinsic::s390_vstrczfs:
1462     Opcode = SystemZISD::VSTRCZ_CC;
1463     CCValid = SystemZ::CCMASK_ANY;
1464     return true;
1465 
1466   case Intrinsic::s390_vfcedbs:
1467     Opcode = SystemZISD::VFCMPES;
1468     CCValid = SystemZ::CCMASK_VCMP;
1469     return true;
1470 
1471   case Intrinsic::s390_vfchdbs:
1472     Opcode = SystemZISD::VFCMPHS;
1473     CCValid = SystemZ::CCMASK_VCMP;
1474     return true;
1475 
1476   case Intrinsic::s390_vfchedbs:
1477     Opcode = SystemZISD::VFCMPHES;
1478     CCValid = SystemZ::CCMASK_VCMP;
1479     return true;
1480 
1481   case Intrinsic::s390_vftcidb:
1482     Opcode = SystemZISD::VFTCI;
1483     CCValid = SystemZ::CCMASK_VCMP;
1484     return true;
1485 
1486   case Intrinsic::s390_tdc:
1487     Opcode = SystemZISD::TDC;
1488     CCValid = SystemZ::CCMASK_TDC;
1489     return true;
1490 
1491   default:
1492     return false;
1493   }
1494 }
1495 
1496 // Emit an intrinsic with chain with a glued value instead of its CC result.
1497 static SDValue emitIntrinsicWithChainAndGlue(SelectionDAG &DAG, SDValue Op,
1498                                              unsigned Opcode) {
1499   // Copy all operands except the intrinsic ID.
1500   unsigned NumOps = Op.getNumOperands();
1501   SmallVector<SDValue, 6> Ops;
1502   Ops.reserve(NumOps - 1);
1503   Ops.push_back(Op.getOperand(0));
1504   for (unsigned I = 2; I < NumOps; ++I)
1505     Ops.push_back(Op.getOperand(I));
1506 
1507   assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1508   SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1509   SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1510   SDValue OldChain = SDValue(Op.getNode(), 1);
1511   SDValue NewChain = SDValue(Intr.getNode(), 0);
1512   DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1513   return Intr;
1514 }
1515 
1516 // Emit an intrinsic with a glued value instead of its CC result.
1517 static SDValue emitIntrinsicWithGlue(SelectionDAG &DAG, SDValue Op,
1518                                      unsigned Opcode) {
1519   // Copy all operands except the intrinsic ID.
1520   unsigned NumOps = Op.getNumOperands();
1521   SmallVector<SDValue, 6> Ops;
1522   Ops.reserve(NumOps - 1);
1523   for (unsigned I = 1; I < NumOps; ++I)
1524     Ops.push_back(Op.getOperand(I));
1525 
1526   if (Op->getNumValues() == 1)
1527     return DAG.getNode(Opcode, SDLoc(Op), MVT::Glue, Ops);
1528   assert(Op->getNumValues() == 2 && "Expected exactly one non-CC result");
1529   SDVTList RawVTs = DAG.getVTList(Op->getValueType(0), MVT::Glue);
1530   return DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1531 }
1532 
1533 // CC is a comparison that will be implemented using an integer or
1534 // floating-point comparison.  Return the condition code mask for
1535 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
1536 // unsigned comparisons and clear for signed ones.  In the floating-point
1537 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1538 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1539 #define CONV(X) \
1540   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1541   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1542   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1543 
1544   switch (CC) {
1545   default:
1546     llvm_unreachable("Invalid integer condition!");
1547 
1548   CONV(EQ);
1549   CONV(NE);
1550   CONV(GT);
1551   CONV(GE);
1552   CONV(LT);
1553   CONV(LE);
1554 
1555   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
1556   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1557   }
1558 #undef CONV
1559 }
1560 
1561 // Return a sequence for getting a 1 from an IPM result when CC has a
1562 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1563 // The handling of CC values outside CCValid doesn't matter.
1564 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1565   // Deal with cases where the result can be taken directly from a bit
1566   // of the IPM result.
1567   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1568     return IPMConversion(0, 0, SystemZ::IPM_CC);
1569   if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1570     return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1571 
1572   // Deal with cases where we can add a value to force the sign bit
1573   // to contain the right value.  Putting the bit in 31 means we can
1574   // use SRL rather than RISBG(L), and also makes it easier to get a
1575   // 0/-1 value, so it has priority over the other tests below.
1576   //
1577   // These sequences rely on the fact that the upper two bits of the
1578   // IPM result are zero.
1579   uint64_t TopBit = uint64_t(1) << 31;
1580   if (CCMask == (CCValid & SystemZ::CCMASK_0))
1581     return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1582   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1583     return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1584   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1585                             | SystemZ::CCMASK_1
1586                             | SystemZ::CCMASK_2)))
1587     return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1588   if (CCMask == (CCValid & SystemZ::CCMASK_3))
1589     return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1590   if (CCMask == (CCValid & (SystemZ::CCMASK_1
1591                             | SystemZ::CCMASK_2
1592                             | SystemZ::CCMASK_3)))
1593     return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1594 
1595   // Next try inverting the value and testing a bit.  0/1 could be
1596   // handled this way too, but we dealt with that case above.
1597   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1598     return IPMConversion(-1, 0, SystemZ::IPM_CC);
1599 
1600   // Handle cases where adding a value forces a non-sign bit to contain
1601   // the right value.
1602   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1603     return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1604   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1605     return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1606 
1607   // The remaining cases are 1, 2, 0/1/3 and 0/2/3.  All these are
1608   // can be done by inverting the low CC bit and applying one of the
1609   // sign-based extractions above.
1610   if (CCMask == (CCValid & SystemZ::CCMASK_1))
1611     return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1612   if (CCMask == (CCValid & SystemZ::CCMASK_2))
1613     return IPMConversion(1 << SystemZ::IPM_CC,
1614                          TopBit - (3 << SystemZ::IPM_CC), 31);
1615   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1616                             | SystemZ::CCMASK_1
1617                             | SystemZ::CCMASK_3)))
1618     return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1619   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1620                             | SystemZ::CCMASK_2
1621                             | SystemZ::CCMASK_3)))
1622     return IPMConversion(1 << SystemZ::IPM_CC,
1623                          TopBit - (1 << SystemZ::IPM_CC), 31);
1624 
1625   llvm_unreachable("Unexpected CC combination");
1626 }
1627 
1628 // If C can be converted to a comparison against zero, adjust the operands
1629 // as necessary.
1630 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
1631   if (C.ICmpType == SystemZICMP::UnsignedOnly)
1632     return;
1633 
1634   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1635   if (!ConstOp1)
1636     return;
1637 
1638   int64_t Value = ConstOp1->getSExtValue();
1639   if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1640       (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1641       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1642       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1643     C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1644     C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1645   }
1646 }
1647 
1648 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1649 // adjust the operands as necessary.
1650 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
1651                              Comparison &C) {
1652   // For us to make any changes, it must a comparison between a single-use
1653   // load and a constant.
1654   if (!C.Op0.hasOneUse() ||
1655       C.Op0.getOpcode() != ISD::LOAD ||
1656       C.Op1.getOpcode() != ISD::Constant)
1657     return;
1658 
1659   // We must have an 8- or 16-bit load.
1660   auto *Load = cast<LoadSDNode>(C.Op0);
1661   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1662   if (NumBits != 8 && NumBits != 16)
1663     return;
1664 
1665   // The load must be an extending one and the constant must be within the
1666   // range of the unextended value.
1667   auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1668   uint64_t Value = ConstOp1->getZExtValue();
1669   uint64_t Mask = (1 << NumBits) - 1;
1670   if (Load->getExtensionType() == ISD::SEXTLOAD) {
1671     // Make sure that ConstOp1 is in range of C.Op0.
1672     int64_t SignedValue = ConstOp1->getSExtValue();
1673     if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1674       return;
1675     if (C.ICmpType != SystemZICMP::SignedOnly) {
1676       // Unsigned comparison between two sign-extended values is equivalent
1677       // to unsigned comparison between two zero-extended values.
1678       Value &= Mask;
1679     } else if (NumBits == 8) {
1680       // Try to treat the comparison as unsigned, so that we can use CLI.
1681       // Adjust CCMask and Value as necessary.
1682       if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1683         // Test whether the high bit of the byte is set.
1684         Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1685       else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1686         // Test whether the high bit of the byte is clear.
1687         Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1688       else
1689         // No instruction exists for this combination.
1690         return;
1691       C.ICmpType = SystemZICMP::UnsignedOnly;
1692     }
1693   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1694     if (Value > Mask)
1695       return;
1696     // If the constant is in range, we can use any comparison.
1697     C.ICmpType = SystemZICMP::Any;
1698   } else
1699     return;
1700 
1701   // Make sure that the first operand is an i32 of the right extension type.
1702   ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1703                               ISD::SEXTLOAD :
1704                               ISD::ZEXTLOAD);
1705   if (C.Op0.getValueType() != MVT::i32 ||
1706       Load->getExtensionType() != ExtType)
1707     C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
1708                            Load->getBasePtr(), Load->getPointerInfo(),
1709                            Load->getMemoryVT(), Load->getAlignment(),
1710                            Load->getMemOperand()->getFlags());
1711 
1712   // Make sure that the second operand is an i32 with the right value.
1713   if (C.Op1.getValueType() != MVT::i32 ||
1714       Value != ConstOp1->getZExtValue())
1715     C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1716 }
1717 
1718 // Return true if Op is either an unextended load, or a load suitable
1719 // for integer register-memory comparisons of type ICmpType.
1720 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1721   auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1722   if (Load) {
1723     // There are no instructions to compare a register with a memory byte.
1724     if (Load->getMemoryVT() == MVT::i8)
1725       return false;
1726     // Otherwise decide on extension type.
1727     switch (Load->getExtensionType()) {
1728     case ISD::NON_EXTLOAD:
1729       return true;
1730     case ISD::SEXTLOAD:
1731       return ICmpType != SystemZICMP::UnsignedOnly;
1732     case ISD::ZEXTLOAD:
1733       return ICmpType != SystemZICMP::SignedOnly;
1734     default:
1735       break;
1736     }
1737   }
1738   return false;
1739 }
1740 
1741 // Return true if it is better to swap the operands of C.
1742 static bool shouldSwapCmpOperands(const Comparison &C) {
1743   // Leave f128 comparisons alone, since they have no memory forms.
1744   if (C.Op0.getValueType() == MVT::f128)
1745     return false;
1746 
1747   // Always keep a floating-point constant second, since comparisons with
1748   // zero can use LOAD TEST and comparisons with other constants make a
1749   // natural memory operand.
1750   if (isa<ConstantFPSDNode>(C.Op1))
1751     return false;
1752 
1753   // Never swap comparisons with zero since there are many ways to optimize
1754   // those later.
1755   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1756   if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1757     return false;
1758 
1759   // Also keep natural memory operands second if the loaded value is
1760   // only used here.  Several comparisons have memory forms.
1761   if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1762     return false;
1763 
1764   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1765   // In that case we generally prefer the memory to be second.
1766   if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1767     // The only exceptions are when the second operand is a constant and
1768     // we can use things like CHHSI.
1769     if (!ConstOp1)
1770       return true;
1771     // The unsigned memory-immediate instructions can handle 16-bit
1772     // unsigned integers.
1773     if (C.ICmpType != SystemZICMP::SignedOnly &&
1774         isUInt<16>(ConstOp1->getZExtValue()))
1775       return false;
1776     // The signed memory-immediate instructions can handle 16-bit
1777     // signed integers.
1778     if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1779         isInt<16>(ConstOp1->getSExtValue()))
1780       return false;
1781     return true;
1782   }
1783 
1784   // Try to promote the use of CGFR and CLGFR.
1785   unsigned Opcode0 = C.Op0.getOpcode();
1786   if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1787     return true;
1788   if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1789     return true;
1790   if (C.ICmpType != SystemZICMP::SignedOnly &&
1791       Opcode0 == ISD::AND &&
1792       C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1793       cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1794     return true;
1795 
1796   return false;
1797 }
1798 
1799 // Return a version of comparison CC mask CCMask in which the LT and GT
1800 // actions are swapped.
1801 static unsigned reverseCCMask(unsigned CCMask) {
1802   return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1803           (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1804           (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1805           (CCMask & SystemZ::CCMASK_CMP_UO));
1806 }
1807 
1808 // Check whether C tests for equality between X and Y and whether X - Y
1809 // or Y - X is also computed.  In that case it's better to compare the
1810 // result of the subtraction against zero.
1811 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
1812                                  Comparison &C) {
1813   if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1814       C.CCMask == SystemZ::CCMASK_CMP_NE) {
1815     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1816       SDNode *N = *I;
1817       if (N->getOpcode() == ISD::SUB &&
1818           ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1819            (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1820         C.Op0 = SDValue(N, 0);
1821         C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1822         return;
1823       }
1824     }
1825   }
1826 }
1827 
1828 // Check whether C compares a floating-point value with zero and if that
1829 // floating-point value is also negated.  In this case we can use the
1830 // negation to set CC, so avoiding separate LOAD AND TEST and
1831 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1832 static void adjustForFNeg(Comparison &C) {
1833   auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1834   if (C1 && C1->isZero()) {
1835     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1836       SDNode *N = *I;
1837       if (N->getOpcode() == ISD::FNEG) {
1838         C.Op0 = SDValue(N, 0);
1839         C.CCMask = reverseCCMask(C.CCMask);
1840         return;
1841       }
1842     }
1843   }
1844 }
1845 
1846 // Check whether C compares (shl X, 32) with 0 and whether X is
1847 // also sign-extended.  In that case it is better to test the result
1848 // of the sign extension using LTGFR.
1849 //
1850 // This case is important because InstCombine transforms a comparison
1851 // with (sext (trunc X)) into a comparison with (shl X, 32).
1852 static void adjustForLTGFR(Comparison &C) {
1853   // Check for a comparison between (shl X, 32) and 0.
1854   if (C.Op0.getOpcode() == ISD::SHL &&
1855       C.Op0.getValueType() == MVT::i64 &&
1856       C.Op1.getOpcode() == ISD::Constant &&
1857       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1858     auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1859     if (C1 && C1->getZExtValue() == 32) {
1860       SDValue ShlOp0 = C.Op0.getOperand(0);
1861       // See whether X has any SIGN_EXTEND_INREG uses.
1862       for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1863         SDNode *N = *I;
1864         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1865             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1866           C.Op0 = SDValue(N, 0);
1867           return;
1868         }
1869       }
1870     }
1871   }
1872 }
1873 
1874 // If C compares the truncation of an extending load, try to compare
1875 // the untruncated value instead.  This exposes more opportunities to
1876 // reuse CC.
1877 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
1878                                Comparison &C) {
1879   if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1880       C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1881       C.Op1.getOpcode() == ISD::Constant &&
1882       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1883     auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1884     if (L->getMemoryVT().getStoreSizeInBits() <= C.Op0.getValueSizeInBits()) {
1885       unsigned Type = L->getExtensionType();
1886       if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1887           (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1888         C.Op0 = C.Op0.getOperand(0);
1889         C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1890       }
1891     }
1892   }
1893 }
1894 
1895 // Return true if shift operation N has an in-range constant shift value.
1896 // Store it in ShiftVal if so.
1897 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1898   auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1899   if (!Shift)
1900     return false;
1901 
1902   uint64_t Amount = Shift->getZExtValue();
1903   if (Amount >= N.getValueSizeInBits())
1904     return false;
1905 
1906   ShiftVal = Amount;
1907   return true;
1908 }
1909 
1910 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1911 // instruction and whether the CC value is descriptive enough to handle
1912 // a comparison of type Opcode between the AND result and CmpVal.
1913 // CCMask says which comparison result is being tested and BitSize is
1914 // the number of bits in the operands.  If TEST UNDER MASK can be used,
1915 // return the corresponding CC mask, otherwise return 0.
1916 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1917                                      uint64_t Mask, uint64_t CmpVal,
1918                                      unsigned ICmpType) {
1919   assert(Mask != 0 && "ANDs with zero should have been removed by now");
1920 
1921   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1922   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1923       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1924     return 0;
1925 
1926   // Work out the masks for the lowest and highest bits.
1927   unsigned HighShift = 63 - countLeadingZeros(Mask);
1928   uint64_t High = uint64_t(1) << HighShift;
1929   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1930 
1931   // Signed ordered comparisons are effectively unsigned if the sign
1932   // bit is dropped.
1933   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1934 
1935   // Check for equality comparisons with 0, or the equivalent.
1936   if (CmpVal == 0) {
1937     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1938       return SystemZ::CCMASK_TM_ALL_0;
1939     if (CCMask == SystemZ::CCMASK_CMP_NE)
1940       return SystemZ::CCMASK_TM_SOME_1;
1941   }
1942   if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
1943     if (CCMask == SystemZ::CCMASK_CMP_LT)
1944       return SystemZ::CCMASK_TM_ALL_0;
1945     if (CCMask == SystemZ::CCMASK_CMP_GE)
1946       return SystemZ::CCMASK_TM_SOME_1;
1947   }
1948   if (EffectivelyUnsigned && CmpVal < Low) {
1949     if (CCMask == SystemZ::CCMASK_CMP_LE)
1950       return SystemZ::CCMASK_TM_ALL_0;
1951     if (CCMask == SystemZ::CCMASK_CMP_GT)
1952       return SystemZ::CCMASK_TM_SOME_1;
1953   }
1954 
1955   // Check for equality comparisons with the mask, or the equivalent.
1956   if (CmpVal == Mask) {
1957     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1958       return SystemZ::CCMASK_TM_ALL_1;
1959     if (CCMask == SystemZ::CCMASK_CMP_NE)
1960       return SystemZ::CCMASK_TM_SOME_0;
1961   }
1962   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1963     if (CCMask == SystemZ::CCMASK_CMP_GT)
1964       return SystemZ::CCMASK_TM_ALL_1;
1965     if (CCMask == SystemZ::CCMASK_CMP_LE)
1966       return SystemZ::CCMASK_TM_SOME_0;
1967   }
1968   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1969     if (CCMask == SystemZ::CCMASK_CMP_GE)
1970       return SystemZ::CCMASK_TM_ALL_1;
1971     if (CCMask == SystemZ::CCMASK_CMP_LT)
1972       return SystemZ::CCMASK_TM_SOME_0;
1973   }
1974 
1975   // Check for ordered comparisons with the top bit.
1976   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1977     if (CCMask == SystemZ::CCMASK_CMP_LE)
1978       return SystemZ::CCMASK_TM_MSB_0;
1979     if (CCMask == SystemZ::CCMASK_CMP_GT)
1980       return SystemZ::CCMASK_TM_MSB_1;
1981   }
1982   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1983     if (CCMask == SystemZ::CCMASK_CMP_LT)
1984       return SystemZ::CCMASK_TM_MSB_0;
1985     if (CCMask == SystemZ::CCMASK_CMP_GE)
1986       return SystemZ::CCMASK_TM_MSB_1;
1987   }
1988 
1989   // If there are just two bits, we can do equality checks for Low and High
1990   // as well.
1991   if (Mask == Low + High) {
1992     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1993       return SystemZ::CCMASK_TM_MIXED_MSB_0;
1994     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1995       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1996     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1997       return SystemZ::CCMASK_TM_MIXED_MSB_1;
1998     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1999       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
2000   }
2001 
2002   // Looks like we've exhausted our options.
2003   return 0;
2004 }
2005 
2006 // See whether C can be implemented as a TEST UNDER MASK instruction.
2007 // Update the arguments with the TM version if so.
2008 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
2009                                    Comparison &C) {
2010   // Check that we have a comparison with a constant.
2011   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2012   if (!ConstOp1)
2013     return;
2014   uint64_t CmpVal = ConstOp1->getZExtValue();
2015 
2016   // Check whether the nonconstant input is an AND with a constant mask.
2017   Comparison NewC(C);
2018   uint64_t MaskVal;
2019   ConstantSDNode *Mask = nullptr;
2020   if (C.Op0.getOpcode() == ISD::AND) {
2021     NewC.Op0 = C.Op0.getOperand(0);
2022     NewC.Op1 = C.Op0.getOperand(1);
2023     Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2024     if (!Mask)
2025       return;
2026     MaskVal = Mask->getZExtValue();
2027   } else {
2028     // There is no instruction to compare with a 64-bit immediate
2029     // so use TMHH instead if possible.  We need an unsigned ordered
2030     // comparison with an i64 immediate.
2031     if (NewC.Op0.getValueType() != MVT::i64 ||
2032         NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2033         NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2034         NewC.ICmpType == SystemZICMP::SignedOnly)
2035       return;
2036     // Convert LE and GT comparisons into LT and GE.
2037     if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2038         NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2039       if (CmpVal == uint64_t(-1))
2040         return;
2041       CmpVal += 1;
2042       NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2043     }
2044     // If the low N bits of Op1 are zero than the low N bits of Op0 can
2045     // be masked off without changing the result.
2046     MaskVal = -(CmpVal & -CmpVal);
2047     NewC.ICmpType = SystemZICMP::UnsignedOnly;
2048   }
2049   if (!MaskVal)
2050     return;
2051 
2052   // Check whether the combination of mask, comparison value and comparison
2053   // type are suitable.
2054   unsigned BitSize = NewC.Op0.getValueSizeInBits();
2055   unsigned NewCCMask, ShiftVal;
2056   if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2057       NewC.Op0.getOpcode() == ISD::SHL &&
2058       isSimpleShift(NewC.Op0, ShiftVal) &&
2059       (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2060                                         MaskVal >> ShiftVal,
2061                                         CmpVal >> ShiftVal,
2062                                         SystemZICMP::Any))) {
2063     NewC.Op0 = NewC.Op0.getOperand(0);
2064     MaskVal >>= ShiftVal;
2065   } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2066              NewC.Op0.getOpcode() == ISD::SRL &&
2067              isSimpleShift(NewC.Op0, ShiftVal) &&
2068              (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2069                                                MaskVal << ShiftVal,
2070                                                CmpVal << ShiftVal,
2071                                                SystemZICMP::UnsignedOnly))) {
2072     NewC.Op0 = NewC.Op0.getOperand(0);
2073     MaskVal <<= ShiftVal;
2074   } else {
2075     NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2076                                      NewC.ICmpType);
2077     if (!NewCCMask)
2078       return;
2079   }
2080 
2081   // Go ahead and make the change.
2082   C.Opcode = SystemZISD::TM;
2083   C.Op0 = NewC.Op0;
2084   if (Mask && Mask->getZExtValue() == MaskVal)
2085     C.Op1 = SDValue(Mask, 0);
2086   else
2087     C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2088   C.CCValid = SystemZ::CCMASK_TM;
2089   C.CCMask = NewCCMask;
2090 }
2091 
2092 // Return a Comparison that tests the condition-code result of intrinsic
2093 // node Call against constant integer CC using comparison code Cond.
2094 // Opcode is the opcode of the SystemZISD operation for the intrinsic
2095 // and CCValid is the set of possible condition-code results.
2096 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2097                                   SDValue Call, unsigned CCValid, uint64_t CC,
2098                                   ISD::CondCode Cond) {
2099   Comparison C(Call, SDValue());
2100   C.Opcode = Opcode;
2101   C.CCValid = CCValid;
2102   if (Cond == ISD::SETEQ)
2103     // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2104     C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2105   else if (Cond == ISD::SETNE)
2106     // ...and the inverse of that.
2107     C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2108   else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2109     // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2110     // always true for CC>3.
2111     C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2112   else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2113     // ...and the inverse of that.
2114     C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2115   else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2116     // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2117     // always true for CC>3.
2118     C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2119   else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2120     // ...and the inverse of that.
2121     C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2122   else
2123     llvm_unreachable("Unexpected integer comparison type");
2124   C.CCMask &= CCValid;
2125   return C;
2126 }
2127 
2128 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2129 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2130                          ISD::CondCode Cond, const SDLoc &DL) {
2131   if (CmpOp1.getOpcode() == ISD::Constant) {
2132     uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2133     unsigned Opcode, CCValid;
2134     if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2135         CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2136         isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2137       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2138     if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2139         CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2140         isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2141       return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2142   }
2143   Comparison C(CmpOp0, CmpOp1);
2144   C.CCMask = CCMaskForCondCode(Cond);
2145   if (C.Op0.getValueType().isFloatingPoint()) {
2146     C.CCValid = SystemZ::CCMASK_FCMP;
2147     C.Opcode = SystemZISD::FCMP;
2148     adjustForFNeg(C);
2149   } else {
2150     C.CCValid = SystemZ::CCMASK_ICMP;
2151     C.Opcode = SystemZISD::ICMP;
2152     // Choose the type of comparison.  Equality and inequality tests can
2153     // use either signed or unsigned comparisons.  The choice also doesn't
2154     // matter if both sign bits are known to be clear.  In those cases we
2155     // want to give the main isel code the freedom to choose whichever
2156     // form fits best.
2157     if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2158         C.CCMask == SystemZ::CCMASK_CMP_NE ||
2159         (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2160       C.ICmpType = SystemZICMP::Any;
2161     else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2162       C.ICmpType = SystemZICMP::UnsignedOnly;
2163     else
2164       C.ICmpType = SystemZICMP::SignedOnly;
2165     C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2166     adjustZeroCmp(DAG, DL, C);
2167     adjustSubwordCmp(DAG, DL, C);
2168     adjustForSubtraction(DAG, DL, C);
2169     adjustForLTGFR(C);
2170     adjustICmpTruncate(DAG, DL, C);
2171   }
2172 
2173   if (shouldSwapCmpOperands(C)) {
2174     std::swap(C.Op0, C.Op1);
2175     C.CCMask = reverseCCMask(C.CCMask);
2176   }
2177 
2178   adjustForTestUnderMask(DAG, DL, C);
2179   return C;
2180 }
2181 
2182 // Emit the comparison instruction described by C.
2183 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2184   if (!C.Op1.getNode()) {
2185     SDValue Op;
2186     switch (C.Op0.getOpcode()) {
2187     case ISD::INTRINSIC_W_CHAIN:
2188       Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
2189       break;
2190     case ISD::INTRINSIC_WO_CHAIN:
2191       Op = emitIntrinsicWithGlue(DAG, C.Op0, C.Opcode);
2192       break;
2193     default:
2194       llvm_unreachable("Invalid comparison operands");
2195     }
2196     return SDValue(Op.getNode(), Op->getNumValues() - 1);
2197   }
2198   if (C.Opcode == SystemZISD::ICMP)
2199     return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
2200                        DAG.getConstant(C.ICmpType, DL, MVT::i32));
2201   if (C.Opcode == SystemZISD::TM) {
2202     bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2203                          bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2204     return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
2205                        DAG.getConstant(RegisterOnly, DL, MVT::i32));
2206   }
2207   return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
2208 }
2209 
2210 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
2211 // 64 bits.  Extend is the extension type to use.  Store the high part
2212 // in Hi and the low part in Lo.
2213 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2214                             SDValue Op0, SDValue Op1, SDValue &Hi,
2215                             SDValue &Lo) {
2216   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2217   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2218   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2219   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2220                    DAG.getConstant(32, DL, MVT::i64));
2221   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2222   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2223 }
2224 
2225 // Lower a binary operation that produces two VT results, one in each
2226 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
2227 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
2228 // on the extended Op0 and (unextended) Op1.  Store the even register result
2229 // in Even and the odd register result in Odd.
2230 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2231                              unsigned Extend, unsigned Opcode, SDValue Op0,
2232                              SDValue Op1, SDValue &Even, SDValue &Odd) {
2233   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
2234   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
2235                                SDValue(In128, 0), Op1);
2236   bool Is32Bit = is32Bit(VT);
2237   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2238   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2239 }
2240 
2241 // Return an i32 value that is 1 if the CC value produced by Glue is
2242 // in the mask CCMask and 0 otherwise.  CC is known to have a value
2243 // in CCValid, so other values can be ignored.
2244 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue Glue,
2245                          unsigned CCValid, unsigned CCMask) {
2246   IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
2247   SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
2248 
2249   if (Conversion.XORValue)
2250     Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
2251                          DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
2252 
2253   if (Conversion.AddValue)
2254     Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
2255                          DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
2256 
2257   // The SHR/AND sequence should get optimized to an RISBG.
2258   Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
2259                        DAG.getConstant(Conversion.Bit, DL, MVT::i32));
2260   if (Conversion.Bit != 31)
2261     Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
2262                          DAG.getConstant(1, DL, MVT::i32));
2263   return Result;
2264 }
2265 
2266 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2267 // be done directly.  IsFP is true if CC is for a floating-point rather than
2268 // integer comparison.
2269 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
2270   switch (CC) {
2271   case ISD::SETOEQ:
2272   case ISD::SETEQ:
2273     return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
2274 
2275   case ISD::SETOGE:
2276   case ISD::SETGE:
2277     return IsFP ? SystemZISD::VFCMPHE : static_cast<SystemZISD::NodeType>(0);
2278 
2279   case ISD::SETOGT:
2280   case ISD::SETGT:
2281     return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
2282 
2283   case ISD::SETUGT:
2284     return IsFP ? static_cast<SystemZISD::NodeType>(0) : SystemZISD::VICMPHL;
2285 
2286   default:
2287     return 0;
2288   }
2289 }
2290 
2291 // Return the SystemZISD vector comparison operation for CC or its inverse,
2292 // or 0 if neither can be done directly.  Indicate in Invert whether the
2293 // result is for the inverse of CC.  IsFP is true if CC is for a
2294 // floating-point rather than integer comparison.
2295 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2296                                             bool &Invert) {
2297   if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2298     Invert = false;
2299     return Opcode;
2300   }
2301 
2302   CC = ISD::getSetCCInverse(CC, !IsFP);
2303   if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2304     Invert = true;
2305     return Opcode;
2306   }
2307 
2308   return 0;
2309 }
2310 
2311 // Return a v2f64 that contains the extended form of elements Start and Start+1
2312 // of v4f32 value Op.
2313 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2314                                   SDValue Op) {
2315   int Mask[] = { Start, -1, Start + 1, -1 };
2316   Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2317   return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2318 }
2319 
2320 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2321 // producing a result of type VT.
2322 static SDValue getVectorCmp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &DL,
2323                             EVT VT, SDValue CmpOp0, SDValue CmpOp1) {
2324   // There is no hardware support for v4f32, so extend the vector into
2325   // two v2f64s and compare those.
2326   if (CmpOp0.getValueType() == MVT::v4f32) {
2327     SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2328     SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2329     SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2330     SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2331     SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2332     SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2333     return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2334   }
2335   return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2336 }
2337 
2338 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2339 // an integer mask of type VT.
2340 static SDValue lowerVectorSETCC(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2341                                 ISD::CondCode CC, SDValue CmpOp0,
2342                                 SDValue CmpOp1) {
2343   bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2344   bool Invert = false;
2345   SDValue Cmp;
2346   switch (CC) {
2347     // Handle tests for order using (or (ogt y x) (oge x y)).
2348   case ISD::SETUO:
2349     Invert = true;
2350   case ISD::SETO: {
2351     assert(IsFP && "Unexpected integer comparison");
2352     SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2353     SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2354     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2355     break;
2356   }
2357 
2358     // Handle <> tests using (or (ogt y x) (ogt x y)).
2359   case ISD::SETUEQ:
2360     Invert = true;
2361   case ISD::SETONE: {
2362     assert(IsFP && "Unexpected integer comparison");
2363     SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2364     SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2365     Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2366     break;
2367   }
2368 
2369     // Otherwise a single comparison is enough.  It doesn't really
2370     // matter whether we try the inversion or the swap first, since
2371     // there are no cases where both work.
2372   default:
2373     if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2374       Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2375     else {
2376       CC = ISD::getSetCCSwappedOperands(CC);
2377       if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2378         Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2379       else
2380         llvm_unreachable("Unhandled comparison");
2381     }
2382     break;
2383   }
2384   if (Invert) {
2385     SDValue Mask = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2386                                DAG.getConstant(65535, DL, MVT::i32));
2387     Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2388     Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2389   }
2390   return Cmp;
2391 }
2392 
2393 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2394                                           SelectionDAG &DAG) const {
2395   SDValue CmpOp0   = Op.getOperand(0);
2396   SDValue CmpOp1   = Op.getOperand(1);
2397   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2398   SDLoc DL(Op);
2399   EVT VT = Op.getValueType();
2400   if (VT.isVector())
2401     return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2402 
2403   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2404   SDValue Glue = emitCmp(DAG, DL, C);
2405   return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2406 }
2407 
2408 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2409   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2410   SDValue CmpOp0   = Op.getOperand(2);
2411   SDValue CmpOp1   = Op.getOperand(3);
2412   SDValue Dest     = Op.getOperand(4);
2413   SDLoc DL(Op);
2414 
2415   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2416   SDValue Glue = emitCmp(DAG, DL, C);
2417   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2418                      Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2419                      DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2420 }
2421 
2422 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2423 // allowing Pos and Neg to be wider than CmpOp.
2424 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2425   return (Neg.getOpcode() == ISD::SUB &&
2426           Neg.getOperand(0).getOpcode() == ISD::Constant &&
2427           cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2428           Neg.getOperand(1) == Pos &&
2429           (Pos == CmpOp ||
2430            (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2431             Pos.getOperand(0) == CmpOp)));
2432 }
2433 
2434 // Return the absolute or negative absolute of Op; IsNegative decides which.
2435 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
2436                            bool IsNegative) {
2437   Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2438   if (IsNegative)
2439     Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2440                      DAG.getConstant(0, DL, Op.getValueType()), Op);
2441   return Op;
2442 }
2443 
2444 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2445                                               SelectionDAG &DAG) const {
2446   SDValue CmpOp0   = Op.getOperand(0);
2447   SDValue CmpOp1   = Op.getOperand(1);
2448   SDValue TrueOp   = Op.getOperand(2);
2449   SDValue FalseOp  = Op.getOperand(3);
2450   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2451   SDLoc DL(Op);
2452 
2453   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2454 
2455   // Check for absolute and negative-absolute selections, including those
2456   // where the comparison value is sign-extended (for LPGFR and LNGFR).
2457   // This check supplements the one in DAGCombiner.
2458   if (C.Opcode == SystemZISD::ICMP &&
2459       C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2460       C.CCMask != SystemZ::CCMASK_CMP_NE &&
2461       C.Op1.getOpcode() == ISD::Constant &&
2462       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2463     if (isAbsolute(C.Op0, TrueOp, FalseOp))
2464       return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2465     if (isAbsolute(C.Op0, FalseOp, TrueOp))
2466       return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2467   }
2468 
2469   SDValue Glue = emitCmp(DAG, DL, C);
2470 
2471   // Special case for handling -1/0 results.  The shifts we use here
2472   // should get optimized with the IPM conversion sequence.
2473   auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2474   auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2475   if (TrueC && FalseC) {
2476     int64_t TrueVal = TrueC->getSExtValue();
2477     int64_t FalseVal = FalseC->getSExtValue();
2478     if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2479       // Invert the condition if we want -1 on false.
2480       if (TrueVal == 0)
2481         C.CCMask ^= C.CCValid;
2482       SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2483       EVT VT = Op.getValueType();
2484       // Extend the result to VT.  Upper bits are ignored.
2485       if (!is32Bit(VT))
2486         Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2487       // Sign-extend from the low bit.
2488       SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2489       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2490       return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2491     }
2492   }
2493 
2494   SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2495                    DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2496 
2497   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2498   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2499 }
2500 
2501 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2502                                                   SelectionDAG &DAG) const {
2503   SDLoc DL(Node);
2504   const GlobalValue *GV = Node->getGlobal();
2505   int64_t Offset = Node->getOffset();
2506   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2507   CodeModel::Model CM = DAG.getTarget().getCodeModel();
2508 
2509   SDValue Result;
2510   if (Subtarget.isPC32DBLSymbol(GV, CM)) {
2511     // Assign anchors at 1<<12 byte boundaries.
2512     uint64_t Anchor = Offset & ~uint64_t(0xfff);
2513     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2514     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2515 
2516     // The offset can be folded into the address if it is aligned to a halfword.
2517     Offset -= Anchor;
2518     if (Offset != 0 && (Offset & 1) == 0) {
2519       SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2520       Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2521       Offset = 0;
2522     }
2523   } else {
2524     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2525     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2526     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2527                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2528   }
2529 
2530   // If there was a non-zero offset that we didn't fold, create an explicit
2531   // addition for it.
2532   if (Offset != 0)
2533     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2534                          DAG.getConstant(Offset, DL, PtrVT));
2535 
2536   return Result;
2537 }
2538 
2539 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2540                                                  SelectionDAG &DAG,
2541                                                  unsigned Opcode,
2542                                                  SDValue GOTOffset) const {
2543   SDLoc DL(Node);
2544   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2545   SDValue Chain = DAG.getEntryNode();
2546   SDValue Glue;
2547 
2548   // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2549   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2550   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2551   Glue = Chain.getValue(1);
2552   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2553   Glue = Chain.getValue(1);
2554 
2555   // The first call operand is the chain and the second is the TLS symbol.
2556   SmallVector<SDValue, 8> Ops;
2557   Ops.push_back(Chain);
2558   Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2559                                            Node->getValueType(0),
2560                                            0, 0));
2561 
2562   // Add argument registers to the end of the list so that they are
2563   // known live into the call.
2564   Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2565   Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2566 
2567   // Add a register mask operand representing the call-preserved registers.
2568   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2569   const uint32_t *Mask =
2570       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
2571   assert(Mask && "Missing call preserved mask for calling convention");
2572   Ops.push_back(DAG.getRegisterMask(Mask));
2573 
2574   // Glue the call to the argument copies.
2575   Ops.push_back(Glue);
2576 
2577   // Emit the call.
2578   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2579   Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2580   Glue = Chain.getValue(1);
2581 
2582   // Copy the return value from %r2.
2583   return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2584 }
2585 
2586 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
2587                                                   SelectionDAG &DAG) const {
2588   SDValue Chain = DAG.getEntryNode();
2589   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2590 
2591   // The high part of the thread pointer is in access register 0.
2592   SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
2593   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2594 
2595   // The low part of the thread pointer is in access register 1.
2596   SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
2597   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2598 
2599   // Merge them into a single 64-bit address.
2600   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2601                                     DAG.getConstant(32, DL, PtrVT));
2602   return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2603 }
2604 
2605 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2606                                                      SelectionDAG &DAG) const {
2607   if (DAG.getTarget().Options.EmulatedTLS)
2608     return LowerToTLSEmulatedModel(Node, DAG);
2609   SDLoc DL(Node);
2610   const GlobalValue *GV = Node->getGlobal();
2611   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2612   TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2613 
2614   SDValue TP = lowerThreadPointer(DL, DAG);
2615 
2616   // Get the offset of GA from the thread pointer, based on the TLS model.
2617   SDValue Offset;
2618   switch (model) {
2619     case TLSModel::GeneralDynamic: {
2620       // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2621       SystemZConstantPoolValue *CPV =
2622         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
2623 
2624       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2625       Offset = DAG.getLoad(
2626           PtrVT, DL, DAG.getEntryNode(), Offset,
2627           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2628 
2629       // Call __tls_get_offset to retrieve the offset.
2630       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2631       break;
2632     }
2633 
2634     case TLSModel::LocalDynamic: {
2635       // Load the GOT offset of the module ID.
2636       SystemZConstantPoolValue *CPV =
2637         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
2638 
2639       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2640       Offset = DAG.getLoad(
2641           PtrVT, DL, DAG.getEntryNode(), Offset,
2642           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2643 
2644       // Call __tls_get_offset to retrieve the module base offset.
2645       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2646 
2647       // Note: The SystemZLDCleanupPass will remove redundant computations
2648       // of the module base offset.  Count total number of local-dynamic
2649       // accesses to trigger execution of that pass.
2650       SystemZMachineFunctionInfo* MFI =
2651         DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
2652       MFI->incNumLocalDynamicTLSAccesses();
2653 
2654       // Add the per-symbol offset.
2655       CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
2656 
2657       SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2658       DTPOffset = DAG.getLoad(
2659           PtrVT, DL, DAG.getEntryNode(), DTPOffset,
2660           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2661 
2662       Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2663       break;
2664     }
2665 
2666     case TLSModel::InitialExec: {
2667       // Load the offset from the GOT.
2668       Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2669                                           SystemZII::MO_INDNTPOFF);
2670       Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2671       Offset =
2672           DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
2673                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2674       break;
2675     }
2676 
2677     case TLSModel::LocalExec: {
2678       // Force the offset into the constant pool and load it from there.
2679       SystemZConstantPoolValue *CPV =
2680         SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
2681 
2682       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2683       Offset = DAG.getLoad(
2684           PtrVT, DL, DAG.getEntryNode(), Offset,
2685           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2686       break;
2687     }
2688   }
2689 
2690   // Add the base and offset together.
2691   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2692 }
2693 
2694 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2695                                                  SelectionDAG &DAG) const {
2696   SDLoc DL(Node);
2697   const BlockAddress *BA = Node->getBlockAddress();
2698   int64_t Offset = Node->getOffset();
2699   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2700 
2701   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2702   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2703   return Result;
2704 }
2705 
2706 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2707                                               SelectionDAG &DAG) const {
2708   SDLoc DL(JT);
2709   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2710   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2711 
2712   // Use LARL to load the address of the table.
2713   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2714 }
2715 
2716 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2717                                                  SelectionDAG &DAG) const {
2718   SDLoc DL(CP);
2719   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2720 
2721   SDValue Result;
2722   if (CP->isMachineConstantPoolEntry())
2723     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2724                                        CP->getAlignment());
2725   else
2726     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2727                                        CP->getAlignment(), CP->getOffset());
2728 
2729   // Use LARL to load the address of the constant pool entry.
2730   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2731 }
2732 
2733 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
2734                                               SelectionDAG &DAG) const {
2735   MachineFunction &MF = DAG.getMachineFunction();
2736   MachineFrameInfo &MFI = MF.getFrameInfo();
2737   MFI.setFrameAddressIsTaken(true);
2738 
2739   SDLoc DL(Op);
2740   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2741   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2742 
2743   // If the back chain frame index has not been allocated yet, do so.
2744   SystemZMachineFunctionInfo *FI = MF.getInfo<SystemZMachineFunctionInfo>();
2745   int BackChainIdx = FI->getFramePointerSaveIndex();
2746   if (!BackChainIdx) {
2747     // By definition, the frame address is the address of the back chain.
2748     BackChainIdx = MFI.CreateFixedObject(8, -SystemZMC::CallFrameSize, false);
2749     FI->setFramePointerSaveIndex(BackChainIdx);
2750   }
2751   SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
2752 
2753   // FIXME The frontend should detect this case.
2754   if (Depth > 0) {
2755     report_fatal_error("Unsupported stack frame traversal count");
2756   }
2757 
2758   return BackChain;
2759 }
2760 
2761 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
2762                                                SelectionDAG &DAG) const {
2763   MachineFunction &MF = DAG.getMachineFunction();
2764   MachineFrameInfo &MFI = MF.getFrameInfo();
2765   MFI.setReturnAddressIsTaken(true);
2766 
2767   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2768     return SDValue();
2769 
2770   SDLoc DL(Op);
2771   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2772   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2773 
2774   // FIXME The frontend should detect this case.
2775   if (Depth > 0) {
2776     report_fatal_error("Unsupported stack frame traversal count");
2777   }
2778 
2779   // Return R14D, which has the return address. Mark it an implicit live-in.
2780   unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
2781   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
2782 }
2783 
2784 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2785                                             SelectionDAG &DAG) const {
2786   SDLoc DL(Op);
2787   SDValue In = Op.getOperand(0);
2788   EVT InVT = In.getValueType();
2789   EVT ResVT = Op.getValueType();
2790 
2791   // Convert loads directly.  This is normally done by DAGCombiner,
2792   // but we need this case for bitcasts that are created during lowering
2793   // and which are then lowered themselves.
2794   if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2795     return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2796                        LoadN->getMemOperand());
2797 
2798   if (InVT == MVT::i32 && ResVT == MVT::f32) {
2799     SDValue In64;
2800     if (Subtarget.hasHighWord()) {
2801       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2802                                        MVT::i64);
2803       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2804                                        MVT::i64, SDValue(U64, 0), In);
2805     } else {
2806       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2807       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2808                          DAG.getConstant(32, DL, MVT::i64));
2809     }
2810     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2811     return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2812                                       DL, MVT::f32, Out64);
2813   }
2814   if (InVT == MVT::f32 && ResVT == MVT::i32) {
2815     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2816     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2817                                              MVT::f64, SDValue(U64, 0), In);
2818     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2819     if (Subtarget.hasHighWord())
2820       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2821                                         MVT::i32, Out64);
2822     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2823                                 DAG.getConstant(32, DL, MVT::i64));
2824     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2825   }
2826   llvm_unreachable("Unexpected bitcast combination");
2827 }
2828 
2829 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2830                                             SelectionDAG &DAG) const {
2831   MachineFunction &MF = DAG.getMachineFunction();
2832   SystemZMachineFunctionInfo *FuncInfo =
2833     MF.getInfo<SystemZMachineFunctionInfo>();
2834   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2835 
2836   SDValue Chain   = Op.getOperand(0);
2837   SDValue Addr    = Op.getOperand(1);
2838   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2839   SDLoc DL(Op);
2840 
2841   // The initial values of each field.
2842   const unsigned NumFields = 4;
2843   SDValue Fields[NumFields] = {
2844     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2845     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2846     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2847     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2848   };
2849 
2850   // Store each field into its respective slot.
2851   SDValue MemOps[NumFields];
2852   unsigned Offset = 0;
2853   for (unsigned I = 0; I < NumFields; ++I) {
2854     SDValue FieldAddr = Addr;
2855     if (Offset != 0)
2856       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2857                               DAG.getIntPtrConstant(Offset, DL));
2858     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2859                              MachinePointerInfo(SV, Offset));
2860     Offset += 8;
2861   }
2862   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2863 }
2864 
2865 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2866                                            SelectionDAG &DAG) const {
2867   SDValue Chain      = Op.getOperand(0);
2868   SDValue DstPtr     = Op.getOperand(1);
2869   SDValue SrcPtr     = Op.getOperand(2);
2870   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2871   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2872   SDLoc DL(Op);
2873 
2874   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2875                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2876                        /*isTailCall*/false,
2877                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2878 }
2879 
2880 SDValue SystemZTargetLowering::
2881 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2882   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
2883   MachineFunction &MF = DAG.getMachineFunction();
2884   bool RealignOpt = !MF.getFunction()-> hasFnAttribute("no-realign-stack");
2885   bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
2886 
2887   SDValue Chain = Op.getOperand(0);
2888   SDValue Size  = Op.getOperand(1);
2889   SDValue Align = Op.getOperand(2);
2890   SDLoc DL(Op);
2891 
2892   // If user has set the no alignment function attribute, ignore
2893   // alloca alignments.
2894   uint64_t AlignVal = (RealignOpt ?
2895                        dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0);
2896 
2897   uint64_t StackAlign = TFI->getStackAlignment();
2898   uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
2899   uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
2900 
2901   unsigned SPReg = getStackPointerRegisterToSaveRestore();
2902   SDValue NeededSpace = Size;
2903 
2904   // Get a reference to the stack pointer.
2905   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2906 
2907   // If we need a backchain, save it now.
2908   SDValue Backchain;
2909   if (StoreBackchain)
2910     Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
2911 
2912   // Add extra space for alignment if needed.
2913   if (ExtraAlignSpace)
2914     NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
2915                               DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2916 
2917   // Get the new stack pointer value.
2918   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
2919 
2920   // Copy the new stack pointer back.
2921   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2922 
2923   // The allocated data lives above the 160 bytes allocated for the standard
2924   // frame, plus any outgoing stack arguments.  We don't know how much that
2925   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2926   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2927   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2928 
2929   // Dynamically realign if needed.
2930   if (RequiredAlign > StackAlign) {
2931     Result =
2932       DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
2933                   DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2934     Result =
2935       DAG.getNode(ISD::AND, DL, MVT::i64, Result,
2936                   DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
2937   }
2938 
2939   if (StoreBackchain)
2940     Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
2941 
2942   SDValue Ops[2] = { Result, Chain };
2943   return DAG.getMergeValues(Ops, DL);
2944 }
2945 
2946 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
2947     SDValue Op, SelectionDAG &DAG) const {
2948   SDLoc DL(Op);
2949 
2950   return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2951 }
2952 
2953 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2954                                               SelectionDAG &DAG) const {
2955   EVT VT = Op.getValueType();
2956   SDLoc DL(Op);
2957   SDValue Ops[2];
2958   if (is32Bit(VT))
2959     // Just do a normal 64-bit multiplication and extract the results.
2960     // We define this so that it can be used for constant division.
2961     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2962                     Op.getOperand(1), Ops[1], Ops[0]);
2963   else {
2964     // Do a full 128-bit multiplication based on UMUL_LOHI64:
2965     //
2966     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2967     //
2968     // but using the fact that the upper halves are either all zeros
2969     // or all ones:
2970     //
2971     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2972     //
2973     // and grouping the right terms together since they are quicker than the
2974     // multiplication:
2975     //
2976     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2977     SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
2978     SDValue LL = Op.getOperand(0);
2979     SDValue RL = Op.getOperand(1);
2980     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2981     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2982     // UMUL_LOHI64 returns the low result in the odd register and the high
2983     // result in the even register.  SMUL_LOHI is defined to return the
2984     // low half first, so the results are in reverse order.
2985     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2986                      LL, RL, Ops[1], Ops[0]);
2987     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2988     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2989     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2990     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2991   }
2992   return DAG.getMergeValues(Ops, DL);
2993 }
2994 
2995 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
2996                                               SelectionDAG &DAG) const {
2997   EVT VT = Op.getValueType();
2998   SDLoc DL(Op);
2999   SDValue Ops[2];
3000   if (is32Bit(VT))
3001     // Just do a normal 64-bit multiplication and extract the results.
3002     // We define this so that it can be used for constant division.
3003     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
3004                     Op.getOperand(1), Ops[1], Ops[0]);
3005   else
3006     // UMUL_LOHI64 returns the low result in the odd register and the high
3007     // result in the even register.  UMUL_LOHI is defined to return the
3008     // low half first, so the results are in reverse order.
3009     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
3010                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3011   return DAG.getMergeValues(Ops, DL);
3012 }
3013 
3014 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
3015                                             SelectionDAG &DAG) const {
3016   SDValue Op0 = Op.getOperand(0);
3017   SDValue Op1 = Op.getOperand(1);
3018   EVT VT = Op.getValueType();
3019   SDLoc DL(Op);
3020   unsigned Opcode;
3021 
3022   // We use DSGF for 32-bit division.
3023   if (is32Bit(VT)) {
3024     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
3025     Opcode = SystemZISD::SDIVREM32;
3026   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
3027     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
3028     Opcode = SystemZISD::SDIVREM32;
3029   } else
3030     Opcode = SystemZISD::SDIVREM64;
3031 
3032   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
3033   // input is "don't care".  The instruction returns the remainder in
3034   // the even register and the quotient in the odd register.
3035   SDValue Ops[2];
3036   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
3037                    Op0, Op1, Ops[1], Ops[0]);
3038   return DAG.getMergeValues(Ops, DL);
3039 }
3040 
3041 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
3042                                             SelectionDAG &DAG) const {
3043   EVT VT = Op.getValueType();
3044   SDLoc DL(Op);
3045 
3046   // DL(G) uses a double-width dividend, so we need to clear the even
3047   // register in the GR128 input.  The instruction returns the remainder
3048   // in the even register and the quotient in the odd register.
3049   SDValue Ops[2];
3050   if (is32Bit(VT))
3051     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
3052                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3053   else
3054     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
3055                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3056   return DAG.getMergeValues(Ops, DL);
3057 }
3058 
3059 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
3060   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
3061 
3062   // Get the known-zero masks for each operand.
3063   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
3064   APInt KnownZero[2], KnownOne[2];
3065   DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
3066   DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
3067 
3068   // See if the upper 32 bits of one operand and the lower 32 bits of the
3069   // other are known zero.  They are the low and high operands respectively.
3070   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
3071                        KnownZero[1].getZExtValue() };
3072   unsigned High, Low;
3073   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3074     High = 1, Low = 0;
3075   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3076     High = 0, Low = 1;
3077   else
3078     return Op;
3079 
3080   SDValue LowOp = Ops[Low];
3081   SDValue HighOp = Ops[High];
3082 
3083   // If the high part is a constant, we're better off using IILH.
3084   if (HighOp.getOpcode() == ISD::Constant)
3085     return Op;
3086 
3087   // If the low part is a constant that is outside the range of LHI,
3088   // then we're better off using IILF.
3089   if (LowOp.getOpcode() == ISD::Constant) {
3090     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3091     if (!isInt<16>(Value))
3092       return Op;
3093   }
3094 
3095   // Check whether the high part is an AND that doesn't change the
3096   // high 32 bits and just masks out low bits.  We can skip it if so.
3097   if (HighOp.getOpcode() == ISD::AND &&
3098       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3099     SDValue HighOp0 = HighOp.getOperand(0);
3100     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3101     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3102       HighOp = HighOp0;
3103   }
3104 
3105   // Take advantage of the fact that all GR32 operations only change the
3106   // low 32 bits by truncating Low to an i32 and inserting it directly
3107   // using a subreg.  The interesting cases are those where the truncation
3108   // can be folded.
3109   SDLoc DL(Op);
3110   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3111   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3112                                    MVT::i64, HighOp, Low32);
3113 }
3114 
3115 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3116                                           SelectionDAG &DAG) const {
3117   EVT VT = Op.getValueType();
3118   SDLoc DL(Op);
3119   Op = Op.getOperand(0);
3120 
3121   // Handle vector types via VPOPCT.
3122   if (VT.isVector()) {
3123     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3124     Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3125     switch (VT.getScalarSizeInBits()) {
3126     case 8:
3127       break;
3128     case 16: {
3129       Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3130       SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3131       SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3132       Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3133       Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3134       break;
3135     }
3136     case 32: {
3137       SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3138                                 DAG.getConstant(0, DL, MVT::i32));
3139       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3140       break;
3141     }
3142     case 64: {
3143       SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3144                                 DAG.getConstant(0, DL, MVT::i32));
3145       Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3146       Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3147       break;
3148     }
3149     default:
3150       llvm_unreachable("Unexpected type");
3151     }
3152     return Op;
3153   }
3154 
3155   // Get the known-zero mask for the operand.
3156   APInt KnownZero, KnownOne;
3157   DAG.computeKnownBits(Op, KnownZero, KnownOne);
3158   unsigned NumSignificantBits = (~KnownZero).getActiveBits();
3159   if (NumSignificantBits == 0)
3160     return DAG.getConstant(0, DL, VT);
3161 
3162   // Skip known-zero high parts of the operand.
3163   int64_t OrigBitSize = VT.getSizeInBits();
3164   int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3165   BitSize = std::min(BitSize, OrigBitSize);
3166 
3167   // The POPCNT instruction counts the number of bits in each byte.
3168   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3169   Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3170   Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3171 
3172   // Add up per-byte counts in a binary tree.  All bits of Op at
3173   // position larger than BitSize remain zero throughout.
3174   for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3175     SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3176     if (BitSize != OrigBitSize)
3177       Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3178                         DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3179     Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3180   }
3181 
3182   // Extract overall result from high byte.
3183   if (BitSize > 8)
3184     Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3185                      DAG.getConstant(BitSize - 8, DL, VT));
3186 
3187   return Op;
3188 }
3189 
3190 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3191                                                  SelectionDAG &DAG) const {
3192   SDLoc DL(Op);
3193   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3194     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3195   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
3196     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3197 
3198   // The only fence that needs an instruction is a sequentially-consistent
3199   // cross-thread fence.
3200   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3201       FenceScope == CrossThread) {
3202     return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3203                                       Op.getOperand(0)),
3204                    0);
3205   }
3206 
3207   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3208   return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3209 }
3210 
3211 // Op is an atomic load.  Lower it into a normal volatile load.
3212 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3213                                                 SelectionDAG &DAG) const {
3214   auto *Node = cast<AtomicSDNode>(Op.getNode());
3215   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3216                         Node->getChain(), Node->getBasePtr(),
3217                         Node->getMemoryVT(), Node->getMemOperand());
3218 }
3219 
3220 // Op is an atomic store.  Lower it into a normal volatile store followed
3221 // by a serialization.
3222 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3223                                                  SelectionDAG &DAG) const {
3224   auto *Node = cast<AtomicSDNode>(Op.getNode());
3225   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3226                                     Node->getBasePtr(), Node->getMemoryVT(),
3227                                     Node->getMemOperand());
3228   return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
3229                                     Chain), 0);
3230 }
3231 
3232 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
3233 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3234 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3235                                                    SelectionDAG &DAG,
3236                                                    unsigned Opcode) const {
3237   auto *Node = cast<AtomicSDNode>(Op.getNode());
3238 
3239   // 32-bit operations need no code outside the main loop.
3240   EVT NarrowVT = Node->getMemoryVT();
3241   EVT WideVT = MVT::i32;
3242   if (NarrowVT == WideVT)
3243     return Op;
3244 
3245   int64_t BitSize = NarrowVT.getSizeInBits();
3246   SDValue ChainIn = Node->getChain();
3247   SDValue Addr = Node->getBasePtr();
3248   SDValue Src2 = Node->getVal();
3249   MachineMemOperand *MMO = Node->getMemOperand();
3250   SDLoc DL(Node);
3251   EVT PtrVT = Addr.getValueType();
3252 
3253   // Convert atomic subtracts of constants into additions.
3254   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3255     if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3256       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
3257       Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3258     }
3259 
3260   // Get the address of the containing word.
3261   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3262                                     DAG.getConstant(-4, DL, PtrVT));
3263 
3264   // Get the number of bits that the word must be rotated left in order
3265   // to bring the field to the top bits of a GR32.
3266   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3267                                  DAG.getConstant(3, DL, PtrVT));
3268   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3269 
3270   // Get the complementing shift amount, for rotating a field in the top
3271   // bits back to its proper position.
3272   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3273                                     DAG.getConstant(0, DL, WideVT), BitShift);
3274 
3275   // Extend the source operand to 32 bits and prepare it for the inner loop.
3276   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3277   // operations require the source to be shifted in advance.  (This shift
3278   // can be folded if the source is constant.)  For AND and NAND, the lower
3279   // bits must be set, while for other opcodes they should be left clear.
3280   if (Opcode != SystemZISD::ATOMIC_SWAPW)
3281     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3282                        DAG.getConstant(32 - BitSize, DL, WideVT));
3283   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3284       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
3285     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3286                        DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3287 
3288   // Construct the ATOMIC_LOADW_* node.
3289   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3290   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3291                     DAG.getConstant(BitSize, DL, WideVT) };
3292   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3293                                              NarrowVT, MMO);
3294 
3295   // Rotate the result of the final CS so that the field is in the lower
3296   // bits of a GR32, then truncate it.
3297   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3298                                     DAG.getConstant(BitSize, DL, WideVT));
3299   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3300 
3301   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3302   return DAG.getMergeValues(RetOps, DL);
3303 }
3304 
3305 // Op is an ATOMIC_LOAD_SUB operation.  Lower 8- and 16-bit operations
3306 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3307 // operations into additions.
3308 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3309                                                     SelectionDAG &DAG) const {
3310   auto *Node = cast<AtomicSDNode>(Op.getNode());
3311   EVT MemVT = Node->getMemoryVT();
3312   if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3313     // A full-width operation.
3314     assert(Op.getValueType() == MemVT && "Mismatched VTs");
3315     SDValue Src2 = Node->getVal();
3316     SDValue NegSrc2;
3317     SDLoc DL(Src2);
3318 
3319     if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3320       // Use an addition if the operand is constant and either LAA(G) is
3321       // available or the negative value is in the range of A(G)FHI.
3322       int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3323       if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3324         NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3325     } else if (Subtarget.hasInterlockedAccess1())
3326       // Use LAA(G) if available.
3327       NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3328                             Src2);
3329 
3330     if (NegSrc2.getNode())
3331       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3332                            Node->getChain(), Node->getBasePtr(), NegSrc2,
3333                            Node->getMemOperand());
3334 
3335     // Use the node as-is.
3336     return Op;
3337   }
3338 
3339   return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3340 }
3341 
3342 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
3343 // into a fullword ATOMIC_CMP_SWAPW operation.
3344 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3345                                                     SelectionDAG &DAG) const {
3346   auto *Node = cast<AtomicSDNode>(Op.getNode());
3347 
3348   // We have native support for 32-bit compare and swap.
3349   EVT NarrowVT = Node->getMemoryVT();
3350   EVT WideVT = MVT::i32;
3351   if (NarrowVT == WideVT)
3352     return Op;
3353 
3354   int64_t BitSize = NarrowVT.getSizeInBits();
3355   SDValue ChainIn = Node->getOperand(0);
3356   SDValue Addr = Node->getOperand(1);
3357   SDValue CmpVal = Node->getOperand(2);
3358   SDValue SwapVal = Node->getOperand(3);
3359   MachineMemOperand *MMO = Node->getMemOperand();
3360   SDLoc DL(Node);
3361   EVT PtrVT = Addr.getValueType();
3362 
3363   // Get the address of the containing word.
3364   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3365                                     DAG.getConstant(-4, DL, PtrVT));
3366 
3367   // Get the number of bits that the word must be rotated left in order
3368   // to bring the field to the top bits of a GR32.
3369   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3370                                  DAG.getConstant(3, DL, PtrVT));
3371   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3372 
3373   // Get the complementing shift amount, for rotating a field in the top
3374   // bits back to its proper position.
3375   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3376                                     DAG.getConstant(0, DL, WideVT), BitShift);
3377 
3378   // Construct the ATOMIC_CMP_SWAPW node.
3379   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3380   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
3381                     NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
3382   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
3383                                              VTList, Ops, NarrowVT, MMO);
3384   return AtomicOp;
3385 }
3386 
3387 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
3388                                               SelectionDAG &DAG) const {
3389   MachineFunction &MF = DAG.getMachineFunction();
3390   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3391   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
3392                             SystemZ::R15D, Op.getValueType());
3393 }
3394 
3395 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
3396                                                  SelectionDAG &DAG) const {
3397   MachineFunction &MF = DAG.getMachineFunction();
3398   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3399   bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
3400 
3401   SDValue Chain = Op.getOperand(0);
3402   SDValue NewSP = Op.getOperand(1);
3403   SDValue Backchain;
3404   SDLoc DL(Op);
3405 
3406   if (StoreBackchain) {
3407     SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
3408     Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
3409   }
3410 
3411   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
3412 
3413   if (StoreBackchain)
3414     Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3415 
3416   return Chain;
3417 }
3418 
3419 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
3420                                              SelectionDAG &DAG) const {
3421   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3422   if (!IsData)
3423     // Just preserve the chain.
3424     return Op.getOperand(0);
3425 
3426   SDLoc DL(Op);
3427   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3428   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
3429   auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
3430   SDValue Ops[] = {
3431     Op.getOperand(0),
3432     DAG.getConstant(Code, DL, MVT::i32),
3433     Op.getOperand(1)
3434   };
3435   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
3436                                  Node->getVTList(), Ops,
3437                                  Node->getMemoryVT(), Node->getMemOperand());
3438 }
3439 
3440 // Return an i32 that contains the value of CC immediately after After,
3441 // whose final operand must be MVT::Glue.
3442 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3443   SDLoc DL(After);
3444   SDValue Glue = SDValue(After, After->getNumValues() - 1);
3445   SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3446   return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3447                      DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
3448 }
3449 
3450 SDValue
3451 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3452                                               SelectionDAG &DAG) const {
3453   unsigned Opcode, CCValid;
3454   if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3455     assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3456     SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3457     SDValue CC = getCCResult(DAG, Glued.getNode());
3458     DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3459     return SDValue();
3460   }
3461 
3462   return SDValue();
3463 }
3464 
3465 SDValue
3466 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
3467                                                SelectionDAG &DAG) const {
3468   unsigned Opcode, CCValid;
3469   if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
3470     SDValue Glued = emitIntrinsicWithGlue(DAG, Op, Opcode);
3471     SDValue CC = getCCResult(DAG, Glued.getNode());
3472     if (Op->getNumValues() == 1)
3473       return CC;
3474     assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
3475     return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), Glued,
3476                        CC);
3477   }
3478 
3479   unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3480   switch (Id) {
3481   case Intrinsic::thread_pointer:
3482     return lowerThreadPointer(SDLoc(Op), DAG);
3483 
3484   case Intrinsic::s390_vpdi:
3485     return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
3486                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3487 
3488   case Intrinsic::s390_vperm:
3489     return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
3490                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3491 
3492   case Intrinsic::s390_vuphb:
3493   case Intrinsic::s390_vuphh:
3494   case Intrinsic::s390_vuphf:
3495     return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
3496                        Op.getOperand(1));
3497 
3498   case Intrinsic::s390_vuplhb:
3499   case Intrinsic::s390_vuplhh:
3500   case Intrinsic::s390_vuplhf:
3501     return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
3502                        Op.getOperand(1));
3503 
3504   case Intrinsic::s390_vuplb:
3505   case Intrinsic::s390_vuplhw:
3506   case Intrinsic::s390_vuplf:
3507     return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
3508                        Op.getOperand(1));
3509 
3510   case Intrinsic::s390_vupllb:
3511   case Intrinsic::s390_vupllh:
3512   case Intrinsic::s390_vupllf:
3513     return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
3514                        Op.getOperand(1));
3515 
3516   case Intrinsic::s390_vsumb:
3517   case Intrinsic::s390_vsumh:
3518   case Intrinsic::s390_vsumgh:
3519   case Intrinsic::s390_vsumgf:
3520   case Intrinsic::s390_vsumqf:
3521   case Intrinsic::s390_vsumqg:
3522     return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
3523                        Op.getOperand(1), Op.getOperand(2));
3524   }
3525 
3526   return SDValue();
3527 }
3528 
3529 namespace {
3530 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3531 // of a VPERM with permute vector Bytes.  If Opcode takes three operands,
3532 // Operand is the constant third operand, otherwise it is the number of
3533 // bytes in each element of the result.
3534 struct Permute {
3535   unsigned Opcode;
3536   unsigned Operand;
3537   unsigned char Bytes[SystemZ::VectorBytes];
3538 };
3539 }
3540 
3541 static const Permute PermuteForms[] = {
3542   // VMRHG
3543   { SystemZISD::MERGE_HIGH, 8,
3544     { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3545   // VMRHF
3546   { SystemZISD::MERGE_HIGH, 4,
3547     { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3548   // VMRHH
3549   { SystemZISD::MERGE_HIGH, 2,
3550     { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3551   // VMRHB
3552   { SystemZISD::MERGE_HIGH, 1,
3553     { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3554   // VMRLG
3555   { SystemZISD::MERGE_LOW, 8,
3556     { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3557   // VMRLF
3558   { SystemZISD::MERGE_LOW, 4,
3559     { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3560   // VMRLH
3561   { SystemZISD::MERGE_LOW, 2,
3562     { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3563   // VMRLB
3564   { SystemZISD::MERGE_LOW, 1,
3565     { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3566   // VPKG
3567   { SystemZISD::PACK, 4,
3568     { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3569   // VPKF
3570   { SystemZISD::PACK, 2,
3571     { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3572   // VPKH
3573   { SystemZISD::PACK, 1,
3574     { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3575   // VPDI V1, V2, 4  (low half of V1, high half of V2)
3576   { SystemZISD::PERMUTE_DWORDS, 4,
3577     { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3578   // VPDI V1, V2, 1  (high half of V1, low half of V2)
3579   { SystemZISD::PERMUTE_DWORDS, 1,
3580     { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3581 };
3582 
3583 // Called after matching a vector shuffle against a particular pattern.
3584 // Both the original shuffle and the pattern have two vector operands.
3585 // OpNos[0] is the operand of the original shuffle that should be used for
3586 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3587 // OpNos[1] is the same for operand 1 of the pattern.  Resolve these -1s and
3588 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3589 // for operands 0 and 1 of the pattern.
3590 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3591   if (OpNos[0] < 0) {
3592     if (OpNos[1] < 0)
3593       return false;
3594     OpNo0 = OpNo1 = OpNos[1];
3595   } else if (OpNos[1] < 0) {
3596     OpNo0 = OpNo1 = OpNos[0];
3597   } else {
3598     OpNo0 = OpNos[0];
3599     OpNo1 = OpNos[1];
3600   }
3601   return true;
3602 }
3603 
3604 // Bytes is a VPERM-like permute vector, except that -1 is used for
3605 // undefined bytes.  Return true if the VPERM can be implemented using P.
3606 // When returning true set OpNo0 to the VPERM operand that should be
3607 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3608 //
3609 // For example, if swapping the VPERM operands allows P to match, OpNo0
3610 // will be 1 and OpNo1 will be 0.  If instead Bytes only refers to one
3611 // operand, but rewriting it to use two duplicated operands allows it to
3612 // match P, then OpNo0 and OpNo1 will be the same.
3613 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3614                          unsigned &OpNo0, unsigned &OpNo1) {
3615   int OpNos[] = { -1, -1 };
3616   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3617     int Elt = Bytes[I];
3618     if (Elt >= 0) {
3619       // Make sure that the two permute vectors use the same suboperand
3620       // byte number.  Only the operand numbers (the high bits) are
3621       // allowed to differ.
3622       if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3623         return false;
3624       int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3625       int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3626       // Make sure that the operand mappings are consistent with previous
3627       // elements.
3628       if (OpNos[ModelOpNo] == 1 - RealOpNo)
3629         return false;
3630       OpNos[ModelOpNo] = RealOpNo;
3631     }
3632   }
3633   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3634 }
3635 
3636 // As above, but search for a matching permute.
3637 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3638                                    unsigned &OpNo0, unsigned &OpNo1) {
3639   for (auto &P : PermuteForms)
3640     if (matchPermute(Bytes, P, OpNo0, OpNo1))
3641       return &P;
3642   return nullptr;
3643 }
3644 
3645 // Bytes is a VPERM-like permute vector, except that -1 is used for
3646 // undefined bytes.  This permute is an operand of an outer permute.
3647 // See whether redistributing the -1 bytes gives a shuffle that can be
3648 // implemented using P.  If so, set Transform to a VPERM-like permute vector
3649 // that, when applied to the result of P, gives the original permute in Bytes.
3650 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3651                                const Permute &P,
3652                                SmallVectorImpl<int> &Transform) {
3653   unsigned To = 0;
3654   for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3655     int Elt = Bytes[From];
3656     if (Elt < 0)
3657       // Byte number From of the result is undefined.
3658       Transform[From] = -1;
3659     else {
3660       while (P.Bytes[To] != Elt) {
3661         To += 1;
3662         if (To == SystemZ::VectorBytes)
3663           return false;
3664       }
3665       Transform[From] = To;
3666     }
3667   }
3668   return true;
3669 }
3670 
3671 // As above, but search for a matching permute.
3672 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3673                                          SmallVectorImpl<int> &Transform) {
3674   for (auto &P : PermuteForms)
3675     if (matchDoublePermute(Bytes, P, Transform))
3676       return &P;
3677   return nullptr;
3678 }
3679 
3680 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3681 // as if it had type vNi8.
3682 static void getVPermMask(ShuffleVectorSDNode *VSN,
3683                          SmallVectorImpl<int> &Bytes) {
3684   EVT VT = VSN->getValueType(0);
3685   unsigned NumElements = VT.getVectorNumElements();
3686   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3687   Bytes.resize(NumElements * BytesPerElement, -1);
3688   for (unsigned I = 0; I < NumElements; ++I) {
3689     int Index = VSN->getMaskElt(I);
3690     if (Index >= 0)
3691       for (unsigned J = 0; J < BytesPerElement; ++J)
3692         Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3693   }
3694 }
3695 
3696 // Bytes is a VPERM-like permute vector, except that -1 is used for
3697 // undefined bytes.  See whether bytes [Start, Start + BytesPerElement) of
3698 // the result come from a contiguous sequence of bytes from one input.
3699 // Set Base to the selector for the first byte if so.
3700 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3701                             unsigned BytesPerElement, int &Base) {
3702   Base = -1;
3703   for (unsigned I = 0; I < BytesPerElement; ++I) {
3704     if (Bytes[Start + I] >= 0) {
3705       unsigned Elem = Bytes[Start + I];
3706       if (Base < 0) {
3707         Base = Elem - I;
3708         // Make sure the bytes would come from one input operand.
3709         if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3710           return false;
3711       } else if (unsigned(Base) != Elem - I)
3712         return false;
3713     }
3714   }
3715   return true;
3716 }
3717 
3718 // Bytes is a VPERM-like permute vector, except that -1 is used for
3719 // undefined bytes.  Return true if it can be performed using VSLDI.
3720 // When returning true, set StartIndex to the shift amount and OpNo0
3721 // and OpNo1 to the VPERM operands that should be used as the first
3722 // and second shift operand respectively.
3723 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3724                                unsigned &StartIndex, unsigned &OpNo0,
3725                                unsigned &OpNo1) {
3726   int OpNos[] = { -1, -1 };
3727   int Shift = -1;
3728   for (unsigned I = 0; I < 16; ++I) {
3729     int Index = Bytes[I];
3730     if (Index >= 0) {
3731       int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3732       int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3733       int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3734       if (Shift < 0)
3735         Shift = ExpectedShift;
3736       else if (Shift != ExpectedShift)
3737         return false;
3738       // Make sure that the operand mappings are consistent with previous
3739       // elements.
3740       if (OpNos[ModelOpNo] == 1 - RealOpNo)
3741         return false;
3742       OpNos[ModelOpNo] = RealOpNo;
3743     }
3744   }
3745   StartIndex = Shift;
3746   return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3747 }
3748 
3749 // Create a node that performs P on operands Op0 and Op1, casting the
3750 // operands to the appropriate type.  The type of the result is determined by P.
3751 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
3752                               const Permute &P, SDValue Op0, SDValue Op1) {
3753   // VPDI (PERMUTE_DWORDS) always operates on v2i64s.  The input
3754   // elements of a PACK are twice as wide as the outputs.
3755   unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3756                       P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3757                       P.Operand);
3758   // Cast both operands to the appropriate type.
3759   MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3760                               SystemZ::VectorBytes / InBytes);
3761   Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3762   Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3763   SDValue Op;
3764   if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3765     SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3766     Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3767   } else if (P.Opcode == SystemZISD::PACK) {
3768     MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3769                                  SystemZ::VectorBytes / P.Operand);
3770     Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3771   } else {
3772     Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3773   }
3774   return Op;
3775 }
3776 
3777 // Bytes is a VPERM-like permute vector, except that -1 is used for
3778 // undefined bytes.  Implement it on operands Ops[0] and Ops[1] using
3779 // VSLDI or VPERM.
3780 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
3781                                      SDValue *Ops,
3782                                      const SmallVectorImpl<int> &Bytes) {
3783   for (unsigned I = 0; I < 2; ++I)
3784     Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3785 
3786   // First see whether VSLDI can be used.
3787   unsigned StartIndex, OpNo0, OpNo1;
3788   if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3789     return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3790                        Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3791 
3792   // Fall back on VPERM.  Construct an SDNode for the permute vector.
3793   SDValue IndexNodes[SystemZ::VectorBytes];
3794   for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3795     if (Bytes[I] >= 0)
3796       IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3797     else
3798       IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3799   SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
3800   return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3801 }
3802 
3803 namespace {
3804 // Describes a general N-operand vector shuffle.
3805 struct GeneralShuffle {
3806   GeneralShuffle(EVT vt) : VT(vt) {}
3807   void addUndef();
3808   bool add(SDValue, unsigned);
3809   SDValue getNode(SelectionDAG &, const SDLoc &);
3810 
3811   // The operands of the shuffle.
3812   SmallVector<SDValue, SystemZ::VectorBytes> Ops;
3813 
3814   // Index I is -1 if byte I of the result is undefined.  Otherwise the
3815   // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3816   // Bytes[I] / SystemZ::VectorBytes.
3817   SmallVector<int, SystemZ::VectorBytes> Bytes;
3818 
3819   // The type of the shuffle result.
3820   EVT VT;
3821 };
3822 }
3823 
3824 // Add an extra undefined element to the shuffle.
3825 void GeneralShuffle::addUndef() {
3826   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3827   for (unsigned I = 0; I < BytesPerElement; ++I)
3828     Bytes.push_back(-1);
3829 }
3830 
3831 // Add an extra element to the shuffle, taking it from element Elem of Op.
3832 // A null Op indicates a vector input whose value will be calculated later;
3833 // there is at most one such input per shuffle and it always has the same
3834 // type as the result. Aborts and returns false if the source vector elements
3835 // of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
3836 // LLVM they become implicitly extended, but this is rare and not optimized.
3837 bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
3838   unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3839 
3840   // The source vector can have wider elements than the result,
3841   // either through an explicit TRUNCATE or because of type legalization.
3842   // We want the least significant part.
3843   EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3844   unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3845 
3846   // Return false if the source elements are smaller than their destination
3847   // elements.
3848   if (FromBytesPerElement < BytesPerElement)
3849     return false;
3850 
3851   unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3852                    (FromBytesPerElement - BytesPerElement));
3853 
3854   // Look through things like shuffles and bitcasts.
3855   while (Op.getNode()) {
3856     if (Op.getOpcode() == ISD::BITCAST)
3857       Op = Op.getOperand(0);
3858     else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3859       // See whether the bytes we need come from a contiguous part of one
3860       // operand.
3861       SmallVector<int, SystemZ::VectorBytes> OpBytes;
3862       getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3863       int NewByte;
3864       if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3865         break;
3866       if (NewByte < 0) {
3867         addUndef();
3868         return true;
3869       }
3870       Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3871       Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3872     } else if (Op.isUndef()) {
3873       addUndef();
3874       return true;
3875     } else
3876       break;
3877   }
3878 
3879   // Make sure that the source of the extraction is in Ops.
3880   unsigned OpNo = 0;
3881   for (; OpNo < Ops.size(); ++OpNo)
3882     if (Ops[OpNo] == Op)
3883       break;
3884   if (OpNo == Ops.size())
3885     Ops.push_back(Op);
3886 
3887   // Add the element to Bytes.
3888   unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3889   for (unsigned I = 0; I < BytesPerElement; ++I)
3890     Bytes.push_back(Base + I);
3891 
3892   return true;
3893 }
3894 
3895 // Return SDNodes for the completed shuffle.
3896 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
3897   assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3898 
3899   if (Ops.size() == 0)
3900     return DAG.getUNDEF(VT);
3901 
3902   // Make sure that there are at least two shuffle operands.
3903   if (Ops.size() == 1)
3904     Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3905 
3906   // Create a tree of shuffles, deferring root node until after the loop.
3907   // Try to redistribute the undefined elements of non-root nodes so that
3908   // the non-root shuffles match something like a pack or merge, then adjust
3909   // the parent node's permute vector to compensate for the new order.
3910   // Among other things, this copes with vectors like <2 x i16> that were
3911   // padded with undefined elements during type legalization.
3912   //
3913   // In the best case this redistribution will lead to the whole tree
3914   // using packs and merges.  It should rarely be a loss in other cases.
3915   unsigned Stride = 1;
3916   for (; Stride * 2 < Ops.size(); Stride *= 2) {
3917     for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3918       SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3919 
3920       // Create a mask for just these two operands.
3921       SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
3922       for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3923         unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3924         unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3925         if (OpNo == I)
3926           NewBytes[J] = Byte;
3927         else if (OpNo == I + Stride)
3928           NewBytes[J] = SystemZ::VectorBytes + Byte;
3929         else
3930           NewBytes[J] = -1;
3931       }
3932       // See if it would be better to reorganize NewMask to avoid using VPERM.
3933       SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
3934       if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
3935         Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
3936         // Applying NewBytesMap to Ops[I] gets back to NewBytes.
3937         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3938           if (NewBytes[J] >= 0) {
3939             assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
3940                    "Invalid double permute");
3941             Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
3942           } else
3943             assert(NewBytesMap[J] < 0 && "Invalid double permute");
3944         }
3945       } else {
3946         // Just use NewBytes on the operands.
3947         Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
3948         for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
3949           if (NewBytes[J] >= 0)
3950             Bytes[J] = I * SystemZ::VectorBytes + J;
3951       }
3952     }
3953   }
3954 
3955   // Now we just have 2 inputs.  Put the second operand in Ops[1].
3956   if (Stride > 1) {
3957     Ops[1] = Ops[Stride];
3958     for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3959       if (Bytes[I] >= int(SystemZ::VectorBytes))
3960         Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
3961   }
3962 
3963   // Look for an instruction that can do the permute without resorting
3964   // to VPERM.
3965   unsigned OpNo0, OpNo1;
3966   SDValue Op;
3967   if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
3968     Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
3969   else
3970     Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
3971   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3972 }
3973 
3974 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
3975 static bool isScalarToVector(SDValue Op) {
3976   for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
3977     if (!Op.getOperand(I).isUndef())
3978       return false;
3979   return true;
3980 }
3981 
3982 // Return a vector of type VT that contains Value in the first element.
3983 // The other elements don't matter.
3984 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3985                                    SDValue Value) {
3986   // If we have a constant, replicate it to all elements and let the
3987   // BUILD_VECTOR lowering take care of it.
3988   if (Value.getOpcode() == ISD::Constant ||
3989       Value.getOpcode() == ISD::ConstantFP) {
3990     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
3991     return DAG.getBuildVector(VT, DL, Ops);
3992   }
3993   if (Value.isUndef())
3994     return DAG.getUNDEF(VT);
3995   return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
3996 }
3997 
3998 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
3999 // element 1.  Used for cases in which replication is cheap.
4000 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4001                                  SDValue Op0, SDValue Op1) {
4002   if (Op0.isUndef()) {
4003     if (Op1.isUndef())
4004       return DAG.getUNDEF(VT);
4005     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
4006   }
4007   if (Op1.isUndef())
4008     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
4009   return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
4010                      buildScalarToVector(DAG, DL, VT, Op0),
4011                      buildScalarToVector(DAG, DL, VT, Op1));
4012 }
4013 
4014 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
4015 // vector for them.
4016 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
4017                           SDValue Op1) {
4018   if (Op0.isUndef() && Op1.isUndef())
4019     return DAG.getUNDEF(MVT::v2i64);
4020   // If one of the two inputs is undefined then replicate the other one,
4021   // in order to avoid using another register unnecessarily.
4022   if (Op0.isUndef())
4023     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4024   else if (Op1.isUndef())
4025     Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4026   else {
4027     Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4028     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4029   }
4030   return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
4031 }
4032 
4033 // Try to represent constant BUILD_VECTOR node BVN using a
4034 // SystemZISD::BYTE_MASK-style mask.  Store the mask value in Mask
4035 // on success.
4036 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
4037   EVT ElemVT = BVN->getValueType(0).getVectorElementType();
4038   unsigned BytesPerElement = ElemVT.getStoreSize();
4039   for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
4040     SDValue Op = BVN->getOperand(I);
4041     if (!Op.isUndef()) {
4042       uint64_t Value;
4043       if (Op.getOpcode() == ISD::Constant)
4044         Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
4045       else if (Op.getOpcode() == ISD::ConstantFP)
4046         Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
4047                  .getZExtValue());
4048       else
4049         return false;
4050       for (unsigned J = 0; J < BytesPerElement; ++J) {
4051         uint64_t Byte = (Value >> (J * 8)) & 0xff;
4052         if (Byte == 0xff)
4053           Mask |= 1ULL << ((E - I - 1) * BytesPerElement + J);
4054         else if (Byte != 0)
4055           return false;
4056       }
4057     }
4058   }
4059   return true;
4060 }
4061 
4062 // Try to load a vector constant in which BitsPerElement-bit value Value
4063 // is replicated to fill the vector.  VT is the type of the resulting
4064 // constant, which may have elements of a different size from BitsPerElement.
4065 // Return the SDValue of the constant on success, otherwise return
4066 // an empty value.
4067 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG,
4068                                        const SystemZInstrInfo *TII,
4069                                        const SDLoc &DL, EVT VT, uint64_t Value,
4070                                        unsigned BitsPerElement) {
4071   // Signed 16-bit values can be replicated using VREPI.
4072   int64_t SignedValue = SignExtend64(Value, BitsPerElement);
4073   if (isInt<16>(SignedValue)) {
4074     MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4075                                  SystemZ::VectorBits / BitsPerElement);
4076     SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
4077                              DAG.getConstant(SignedValue, DL, MVT::i32));
4078     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4079   }
4080   // See whether rotating the constant left some N places gives a value that
4081   // is one less than a power of 2 (i.e. all zeros followed by all ones).
4082   // If so we can use VGM.
4083   unsigned Start, End;
4084   if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
4085     // isRxSBGMask returns the bit numbers for a full 64-bit value,
4086     // with 0 denoting 1 << 63 and 63 denoting 1.  Convert them to
4087     // bit numbers for an BitsPerElement value, so that 0 denotes
4088     // 1 << (BitsPerElement-1).
4089     Start -= 64 - BitsPerElement;
4090     End -= 64 - BitsPerElement;
4091     MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4092                                  SystemZ::VectorBits / BitsPerElement);
4093     SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
4094                              DAG.getConstant(Start, DL, MVT::i32),
4095                              DAG.getConstant(End, DL, MVT::i32));
4096     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4097   }
4098   return SDValue();
4099 }
4100 
4101 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4102 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4103 // the non-EXTRACT_VECTOR_ELT elements.  See if the given BUILD_VECTOR
4104 // would benefit from this representation and return it if so.
4105 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
4106                                      BuildVectorSDNode *BVN) {
4107   EVT VT = BVN->getValueType(0);
4108   unsigned NumElements = VT.getVectorNumElements();
4109 
4110   // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4111   // on byte vectors.  If there are non-EXTRACT_VECTOR_ELT elements that still
4112   // need a BUILD_VECTOR, add an additional placeholder operand for that
4113   // BUILD_VECTOR and store its operands in ResidueOps.
4114   GeneralShuffle GS(VT);
4115   SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
4116   bool FoundOne = false;
4117   for (unsigned I = 0; I < NumElements; ++I) {
4118     SDValue Op = BVN->getOperand(I);
4119     if (Op.getOpcode() == ISD::TRUNCATE)
4120       Op = Op.getOperand(0);
4121     if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4122         Op.getOperand(1).getOpcode() == ISD::Constant) {
4123       unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4124       if (!GS.add(Op.getOperand(0), Elem))
4125         return SDValue();
4126       FoundOne = true;
4127     } else if (Op.isUndef()) {
4128       GS.addUndef();
4129     } else {
4130       if (!GS.add(SDValue(), ResidueOps.size()))
4131         return SDValue();
4132       ResidueOps.push_back(BVN->getOperand(I));
4133     }
4134   }
4135 
4136   // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4137   if (!FoundOne)
4138     return SDValue();
4139 
4140   // Create the BUILD_VECTOR for the remaining elements, if any.
4141   if (!ResidueOps.empty()) {
4142     while (ResidueOps.size() < NumElements)
4143       ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4144     for (auto &Op : GS.Ops) {
4145       if (!Op.getNode()) {
4146         Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4147         break;
4148       }
4149     }
4150   }
4151   return GS.getNode(DAG, SDLoc(BVN));
4152 }
4153 
4154 // Combine GPR scalar values Elems into a vector of type VT.
4155 static SDValue buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4156                            SmallVectorImpl<SDValue> &Elems) {
4157   // See whether there is a single replicated value.
4158   SDValue Single;
4159   unsigned int NumElements = Elems.size();
4160   unsigned int Count = 0;
4161   for (auto Elem : Elems) {
4162     if (!Elem.isUndef()) {
4163       if (!Single.getNode())
4164         Single = Elem;
4165       else if (Elem != Single) {
4166         Single = SDValue();
4167         break;
4168       }
4169       Count += 1;
4170     }
4171   }
4172   // There are three cases here:
4173   //
4174   // - if the only defined element is a loaded one, the best sequence
4175   //   is a replicating load.
4176   //
4177   // - otherwise, if the only defined element is an i64 value, we will
4178   //   end up with the same VLVGP sequence regardless of whether we short-cut
4179   //   for replication or fall through to the later code.
4180   //
4181   // - otherwise, if the only defined element is an i32 or smaller value,
4182   //   we would need 2 instructions to replicate it: VLVGP followed by VREPx.
4183   //   This is only a win if the single defined element is used more than once.
4184   //   In other cases we're better off using a single VLVGx.
4185   if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
4186     return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
4187 
4188   // The best way of building a v2i64 from two i64s is to use VLVGP.
4189   if (VT == MVT::v2i64)
4190     return joinDwords(DAG, DL, Elems[0], Elems[1]);
4191 
4192   // Use a 64-bit merge high to combine two doubles.
4193   if (VT == MVT::v2f64)
4194     return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4195 
4196   // Build v4f32 values directly from the FPRs:
4197   //
4198   //   <Axxx> <Bxxx> <Cxxxx> <Dxxx>
4199   //         V              V         VMRHF
4200   //      <ABxx>         <CDxx>
4201   //                V                 VMRHG
4202   //              <ABCD>
4203   if (VT == MVT::v4f32) {
4204     SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4205     SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
4206     // Avoid unnecessary undefs by reusing the other operand.
4207     if (Op01.isUndef())
4208       Op01 = Op23;
4209     else if (Op23.isUndef())
4210       Op23 = Op01;
4211     // Merging identical replications is a no-op.
4212     if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
4213       return Op01;
4214     Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
4215     Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
4216     SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
4217                              DL, MVT::v2i64, Op01, Op23);
4218     return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4219   }
4220 
4221   // Collect the constant terms.
4222   SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
4223   SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
4224 
4225   unsigned NumConstants = 0;
4226   for (unsigned I = 0; I < NumElements; ++I) {
4227     SDValue Elem = Elems[I];
4228     if (Elem.getOpcode() == ISD::Constant ||
4229         Elem.getOpcode() == ISD::ConstantFP) {
4230       NumConstants += 1;
4231       Constants[I] = Elem;
4232       Done[I] = true;
4233     }
4234   }
4235   // If there was at least one constant, fill in the other elements of
4236   // Constants with undefs to get a full vector constant and use that
4237   // as the starting point.
4238   SDValue Result;
4239   if (NumConstants > 0) {
4240     for (unsigned I = 0; I < NumElements; ++I)
4241       if (!Constants[I].getNode())
4242         Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4243     Result = DAG.getBuildVector(VT, DL, Constants);
4244   } else {
4245     // Otherwise try to use VLVGP to start the sequence in order to
4246     // avoid a false dependency on any previous contents of the vector
4247     // register.  This only makes sense if one of the associated elements
4248     // is defined.
4249     unsigned I1 = NumElements / 2 - 1;
4250     unsigned I2 = NumElements - 1;
4251     bool Def1 = !Elems[I1].isUndef();
4252     bool Def2 = !Elems[I2].isUndef();
4253     if (Def1 || Def2) {
4254       SDValue Elem1 = Elems[Def1 ? I1 : I2];
4255       SDValue Elem2 = Elems[Def2 ? I2 : I1];
4256       Result = DAG.getNode(ISD::BITCAST, DL, VT,
4257                            joinDwords(DAG, DL, Elem1, Elem2));
4258       Done[I1] = true;
4259       Done[I2] = true;
4260     } else
4261       Result = DAG.getUNDEF(VT);
4262   }
4263 
4264   // Use VLVGx to insert the other elements.
4265   for (unsigned I = 0; I < NumElements; ++I)
4266     if (!Done[I] && !Elems[I].isUndef())
4267       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4268                            DAG.getConstant(I, DL, MVT::i32));
4269   return Result;
4270 }
4271 
4272 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4273                                                  SelectionDAG &DAG) const {
4274   const SystemZInstrInfo *TII =
4275     static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4276   auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4277   SDLoc DL(Op);
4278   EVT VT = Op.getValueType();
4279 
4280   if (BVN->isConstant()) {
4281     // Try using VECTOR GENERATE BYTE MASK.  This is the architecturally-
4282     // preferred way of creating all-zero and all-one vectors so give it
4283     // priority over other methods below.
4284     uint64_t Mask = 0;
4285     if (tryBuildVectorByteMask(BVN, Mask)) {
4286       SDValue Op = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
4287                                DAG.getConstant(Mask, DL, MVT::i32));
4288       return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4289     }
4290 
4291     // Try using some form of replication.
4292     APInt SplatBits, SplatUndef;
4293     unsigned SplatBitSize;
4294     bool HasAnyUndefs;
4295     if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4296                              8, true) &&
4297         SplatBitSize <= 64) {
4298       // First try assuming that any undefined bits above the highest set bit
4299       // and below the lowest set bit are 1s.  This increases the likelihood of
4300       // being able to use a sign-extended element value in VECTOR REPLICATE
4301       // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
4302       uint64_t SplatBitsZ = SplatBits.getZExtValue();
4303       uint64_t SplatUndefZ = SplatUndef.getZExtValue();
4304       uint64_t Lower = (SplatUndefZ
4305                         & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
4306       uint64_t Upper = (SplatUndefZ
4307                         & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
4308       uint64_t Value = SplatBitsZ | Upper | Lower;
4309       SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
4310                                            SplatBitSize);
4311       if (Op.getNode())
4312         return Op;
4313 
4314       // Now try assuming that any undefined bits between the first and
4315       // last defined set bits are set.  This increases the chances of
4316       // using a non-wraparound mask.
4317       uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
4318       Value = SplatBitsZ | Middle;
4319       Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
4320       if (Op.getNode())
4321         return Op;
4322     }
4323 
4324     // Fall back to loading it from memory.
4325     return SDValue();
4326   }
4327 
4328   // See if we should use shuffles to construct the vector from other vectors.
4329   if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
4330     return Res;
4331 
4332   // Detect SCALAR_TO_VECTOR conversions.
4333   if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
4334     return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4335 
4336   // Otherwise use buildVector to build the vector up from GPRs.
4337   unsigned NumElements = Op.getNumOperands();
4338   SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
4339   for (unsigned I = 0; I < NumElements; ++I)
4340     Ops[I] = Op.getOperand(I);
4341   return buildVector(DAG, DL, VT, Ops);
4342 }
4343 
4344 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4345                                                    SelectionDAG &DAG) const {
4346   auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4347   SDLoc DL(Op);
4348   EVT VT = Op.getValueType();
4349   unsigned NumElements = VT.getVectorNumElements();
4350 
4351   if (VSN->isSplat()) {
4352     SDValue Op0 = Op.getOperand(0);
4353     unsigned Index = VSN->getSplatIndex();
4354     assert(Index < VT.getVectorNumElements() &&
4355            "Splat index should be defined and in first operand");
4356     // See whether the value we're splatting is directly available as a scalar.
4357     if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4358         Op0.getOpcode() == ISD::BUILD_VECTOR)
4359       return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4360     // Otherwise keep it as a vector-to-vector operation.
4361     return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4362                        DAG.getConstant(Index, DL, MVT::i32));
4363   }
4364 
4365   GeneralShuffle GS(VT);
4366   for (unsigned I = 0; I < NumElements; ++I) {
4367     int Elt = VSN->getMaskElt(I);
4368     if (Elt < 0)
4369       GS.addUndef();
4370     else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4371                      unsigned(Elt) % NumElements))
4372       return SDValue();
4373   }
4374   return GS.getNode(DAG, SDLoc(VSN));
4375 }
4376 
4377 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4378                                                      SelectionDAG &DAG) const {
4379   SDLoc DL(Op);
4380   // Just insert the scalar into element 0 of an undefined vector.
4381   return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4382                      Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4383                      Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4384 }
4385 
4386 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4387                                                       SelectionDAG &DAG) const {
4388   // Handle insertions of floating-point values.
4389   SDLoc DL(Op);
4390   SDValue Op0 = Op.getOperand(0);
4391   SDValue Op1 = Op.getOperand(1);
4392   SDValue Op2 = Op.getOperand(2);
4393   EVT VT = Op.getValueType();
4394 
4395   // Insertions into constant indices of a v2f64 can be done using VPDI.
4396   // However, if the inserted value is a bitcast or a constant then it's
4397   // better to use GPRs, as below.
4398   if (VT == MVT::v2f64 &&
4399       Op1.getOpcode() != ISD::BITCAST &&
4400       Op1.getOpcode() != ISD::ConstantFP &&
4401       Op2.getOpcode() == ISD::Constant) {
4402     uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
4403     unsigned Mask = VT.getVectorNumElements() - 1;
4404     if (Index <= Mask)
4405       return Op;
4406   }
4407 
4408   // Otherwise bitcast to the equivalent integer form and insert via a GPR.
4409   MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
4410   MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
4411   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
4412                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
4413                             DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
4414   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4415 }
4416 
4417 SDValue
4418 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4419                                                SelectionDAG &DAG) const {
4420   // Handle extractions of floating-point values.
4421   SDLoc DL(Op);
4422   SDValue Op0 = Op.getOperand(0);
4423   SDValue Op1 = Op.getOperand(1);
4424   EVT VT = Op.getValueType();
4425   EVT VecVT = Op0.getValueType();
4426 
4427   // Extractions of constant indices can be done directly.
4428   if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
4429     uint64_t Index = CIndexN->getZExtValue();
4430     unsigned Mask = VecVT.getVectorNumElements() - 1;
4431     if (Index <= Mask)
4432       return Op;
4433   }
4434 
4435   // Otherwise bitcast to the equivalent integer form and extract via a GPR.
4436   MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
4437   MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
4438   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
4439                             DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
4440   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4441 }
4442 
4443 SDValue
4444 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
4445                                               unsigned UnpackHigh) const {
4446   SDValue PackedOp = Op.getOperand(0);
4447   EVT OutVT = Op.getValueType();
4448   EVT InVT = PackedOp.getValueType();
4449   unsigned ToBits = OutVT.getScalarSizeInBits();
4450   unsigned FromBits = InVT.getScalarSizeInBits();
4451   do {
4452     FromBits *= 2;
4453     EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
4454                                  SystemZ::VectorBits / FromBits);
4455     PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
4456   } while (FromBits != ToBits);
4457   return PackedOp;
4458 }
4459 
4460 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
4461                                           unsigned ByScalar) const {
4462   // Look for cases where a vector shift can use the *_BY_SCALAR form.
4463   SDValue Op0 = Op.getOperand(0);
4464   SDValue Op1 = Op.getOperand(1);
4465   SDLoc DL(Op);
4466   EVT VT = Op.getValueType();
4467   unsigned ElemBitSize = VT.getScalarSizeInBits();
4468 
4469   // See whether the shift vector is a splat represented as BUILD_VECTOR.
4470   if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
4471     APInt SplatBits, SplatUndef;
4472     unsigned SplatBitSize;
4473     bool HasAnyUndefs;
4474     // Check for constant splats.  Use ElemBitSize as the minimum element
4475     // width and reject splats that need wider elements.
4476     if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4477                              ElemBitSize, true) &&
4478         SplatBitSize == ElemBitSize) {
4479       SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
4480                                       DL, MVT::i32);
4481       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4482     }
4483     // Check for variable splats.
4484     BitVector UndefElements;
4485     SDValue Splat = BVN->getSplatValue(&UndefElements);
4486     if (Splat) {
4487       // Since i32 is the smallest legal type, we either need a no-op
4488       // or a truncation.
4489       SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
4490       return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4491     }
4492   }
4493 
4494   // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
4495   // and the shift amount is directly available in a GPR.
4496   if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
4497     if (VSN->isSplat()) {
4498       SDValue VSNOp0 = VSN->getOperand(0);
4499       unsigned Index = VSN->getSplatIndex();
4500       assert(Index < VT.getVectorNumElements() &&
4501              "Splat index should be defined and in first operand");
4502       if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4503           VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
4504         // Since i32 is the smallest legal type, we either need a no-op
4505         // or a truncation.
4506         SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
4507                                     VSNOp0.getOperand(Index));
4508         return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4509       }
4510     }
4511   }
4512 
4513   // Otherwise just treat the current form as legal.
4514   return Op;
4515 }
4516 
4517 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
4518                                               SelectionDAG &DAG) const {
4519   switch (Op.getOpcode()) {
4520   case ISD::FRAMEADDR:
4521     return lowerFRAMEADDR(Op, DAG);
4522   case ISD::RETURNADDR:
4523     return lowerRETURNADDR(Op, DAG);
4524   case ISD::BR_CC:
4525     return lowerBR_CC(Op, DAG);
4526   case ISD::SELECT_CC:
4527     return lowerSELECT_CC(Op, DAG);
4528   case ISD::SETCC:
4529     return lowerSETCC(Op, DAG);
4530   case ISD::GlobalAddress:
4531     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
4532   case ISD::GlobalTLSAddress:
4533     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
4534   case ISD::BlockAddress:
4535     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
4536   case ISD::JumpTable:
4537     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
4538   case ISD::ConstantPool:
4539     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
4540   case ISD::BITCAST:
4541     return lowerBITCAST(Op, DAG);
4542   case ISD::VASTART:
4543     return lowerVASTART(Op, DAG);
4544   case ISD::VACOPY:
4545     return lowerVACOPY(Op, DAG);
4546   case ISD::DYNAMIC_STACKALLOC:
4547     return lowerDYNAMIC_STACKALLOC(Op, DAG);
4548   case ISD::GET_DYNAMIC_AREA_OFFSET:
4549     return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
4550   case ISD::SMUL_LOHI:
4551     return lowerSMUL_LOHI(Op, DAG);
4552   case ISD::UMUL_LOHI:
4553     return lowerUMUL_LOHI(Op, DAG);
4554   case ISD::SDIVREM:
4555     return lowerSDIVREM(Op, DAG);
4556   case ISD::UDIVREM:
4557     return lowerUDIVREM(Op, DAG);
4558   case ISD::OR:
4559     return lowerOR(Op, DAG);
4560   case ISD::CTPOP:
4561     return lowerCTPOP(Op, DAG);
4562   case ISD::ATOMIC_FENCE:
4563     return lowerATOMIC_FENCE(Op, DAG);
4564   case ISD::ATOMIC_SWAP:
4565     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
4566   case ISD::ATOMIC_STORE:
4567     return lowerATOMIC_STORE(Op, DAG);
4568   case ISD::ATOMIC_LOAD:
4569     return lowerATOMIC_LOAD(Op, DAG);
4570   case ISD::ATOMIC_LOAD_ADD:
4571     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
4572   case ISD::ATOMIC_LOAD_SUB:
4573     return lowerATOMIC_LOAD_SUB(Op, DAG);
4574   case ISD::ATOMIC_LOAD_AND:
4575     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
4576   case ISD::ATOMIC_LOAD_OR:
4577     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
4578   case ISD::ATOMIC_LOAD_XOR:
4579     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
4580   case ISD::ATOMIC_LOAD_NAND:
4581     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
4582   case ISD::ATOMIC_LOAD_MIN:
4583     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
4584   case ISD::ATOMIC_LOAD_MAX:
4585     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
4586   case ISD::ATOMIC_LOAD_UMIN:
4587     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
4588   case ISD::ATOMIC_LOAD_UMAX:
4589     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
4590   case ISD::ATOMIC_CMP_SWAP:
4591     return lowerATOMIC_CMP_SWAP(Op, DAG);
4592   case ISD::STACKSAVE:
4593     return lowerSTACKSAVE(Op, DAG);
4594   case ISD::STACKRESTORE:
4595     return lowerSTACKRESTORE(Op, DAG);
4596   case ISD::PREFETCH:
4597     return lowerPREFETCH(Op, DAG);
4598   case ISD::INTRINSIC_W_CHAIN:
4599     return lowerINTRINSIC_W_CHAIN(Op, DAG);
4600   case ISD::INTRINSIC_WO_CHAIN:
4601     return lowerINTRINSIC_WO_CHAIN(Op, DAG);
4602   case ISD::BUILD_VECTOR:
4603     return lowerBUILD_VECTOR(Op, DAG);
4604   case ISD::VECTOR_SHUFFLE:
4605     return lowerVECTOR_SHUFFLE(Op, DAG);
4606   case ISD::SCALAR_TO_VECTOR:
4607     return lowerSCALAR_TO_VECTOR(Op, DAG);
4608   case ISD::INSERT_VECTOR_ELT:
4609     return lowerINSERT_VECTOR_ELT(Op, DAG);
4610   case ISD::EXTRACT_VECTOR_ELT:
4611     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4612   case ISD::SIGN_EXTEND_VECTOR_INREG:
4613     return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
4614   case ISD::ZERO_EXTEND_VECTOR_INREG:
4615     return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
4616   case ISD::SHL:
4617     return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
4618   case ISD::SRL:
4619     return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
4620   case ISD::SRA:
4621     return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
4622   default:
4623     llvm_unreachable("Unexpected node to lower");
4624   }
4625 }
4626 
4627 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
4628 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
4629   switch ((SystemZISD::NodeType)Opcode) {
4630     case SystemZISD::FIRST_NUMBER: break;
4631     OPCODE(RET_FLAG);
4632     OPCODE(CALL);
4633     OPCODE(SIBCALL);
4634     OPCODE(TLS_GDCALL);
4635     OPCODE(TLS_LDCALL);
4636     OPCODE(PCREL_WRAPPER);
4637     OPCODE(PCREL_OFFSET);
4638     OPCODE(IABS);
4639     OPCODE(ICMP);
4640     OPCODE(FCMP);
4641     OPCODE(TM);
4642     OPCODE(BR_CCMASK);
4643     OPCODE(SELECT_CCMASK);
4644     OPCODE(ADJDYNALLOC);
4645     OPCODE(POPCNT);
4646     OPCODE(UMUL_LOHI64);
4647     OPCODE(SDIVREM32);
4648     OPCODE(SDIVREM64);
4649     OPCODE(UDIVREM32);
4650     OPCODE(UDIVREM64);
4651     OPCODE(MVC);
4652     OPCODE(MVC_LOOP);
4653     OPCODE(NC);
4654     OPCODE(NC_LOOP);
4655     OPCODE(OC);
4656     OPCODE(OC_LOOP);
4657     OPCODE(XC);
4658     OPCODE(XC_LOOP);
4659     OPCODE(CLC);
4660     OPCODE(CLC_LOOP);
4661     OPCODE(STPCPY);
4662     OPCODE(STRCMP);
4663     OPCODE(SEARCH_STRING);
4664     OPCODE(IPM);
4665     OPCODE(SERIALIZE);
4666     OPCODE(MEMBARRIER);
4667     OPCODE(TBEGIN);
4668     OPCODE(TBEGIN_NOFLOAT);
4669     OPCODE(TEND);
4670     OPCODE(BYTE_MASK);
4671     OPCODE(ROTATE_MASK);
4672     OPCODE(REPLICATE);
4673     OPCODE(JOIN_DWORDS);
4674     OPCODE(SPLAT);
4675     OPCODE(MERGE_HIGH);
4676     OPCODE(MERGE_LOW);
4677     OPCODE(SHL_DOUBLE);
4678     OPCODE(PERMUTE_DWORDS);
4679     OPCODE(PERMUTE);
4680     OPCODE(PACK);
4681     OPCODE(PACKS_CC);
4682     OPCODE(PACKLS_CC);
4683     OPCODE(UNPACK_HIGH);
4684     OPCODE(UNPACKL_HIGH);
4685     OPCODE(UNPACK_LOW);
4686     OPCODE(UNPACKL_LOW);
4687     OPCODE(VSHL_BY_SCALAR);
4688     OPCODE(VSRL_BY_SCALAR);
4689     OPCODE(VSRA_BY_SCALAR);
4690     OPCODE(VSUM);
4691     OPCODE(VICMPE);
4692     OPCODE(VICMPH);
4693     OPCODE(VICMPHL);
4694     OPCODE(VICMPES);
4695     OPCODE(VICMPHS);
4696     OPCODE(VICMPHLS);
4697     OPCODE(VFCMPE);
4698     OPCODE(VFCMPH);
4699     OPCODE(VFCMPHE);
4700     OPCODE(VFCMPES);
4701     OPCODE(VFCMPHS);
4702     OPCODE(VFCMPHES);
4703     OPCODE(VFTCI);
4704     OPCODE(VEXTEND);
4705     OPCODE(VROUND);
4706     OPCODE(VTM);
4707     OPCODE(VFAE_CC);
4708     OPCODE(VFAEZ_CC);
4709     OPCODE(VFEE_CC);
4710     OPCODE(VFEEZ_CC);
4711     OPCODE(VFENE_CC);
4712     OPCODE(VFENEZ_CC);
4713     OPCODE(VISTR_CC);
4714     OPCODE(VSTRC_CC);
4715     OPCODE(VSTRCZ_CC);
4716     OPCODE(TDC);
4717     OPCODE(ATOMIC_SWAPW);
4718     OPCODE(ATOMIC_LOADW_ADD);
4719     OPCODE(ATOMIC_LOADW_SUB);
4720     OPCODE(ATOMIC_LOADW_AND);
4721     OPCODE(ATOMIC_LOADW_OR);
4722     OPCODE(ATOMIC_LOADW_XOR);
4723     OPCODE(ATOMIC_LOADW_NAND);
4724     OPCODE(ATOMIC_LOADW_MIN);
4725     OPCODE(ATOMIC_LOADW_MAX);
4726     OPCODE(ATOMIC_LOADW_UMIN);
4727     OPCODE(ATOMIC_LOADW_UMAX);
4728     OPCODE(ATOMIC_CMP_SWAPW);
4729     OPCODE(LRV);
4730     OPCODE(STRV);
4731     OPCODE(PREFETCH);
4732   }
4733   return nullptr;
4734 #undef OPCODE
4735 }
4736 
4737 // Return true if VT is a vector whose elements are a whole number of bytes
4738 // in width.
4739 static bool canTreatAsByteVector(EVT VT) {
4740   return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0;
4741 }
4742 
4743 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
4744 // producing a result of type ResVT.  Op is a possibly bitcast version
4745 // of the input vector and Index is the index (based on type VecVT) that
4746 // should be extracted.  Return the new extraction if a simplification
4747 // was possible or if Force is true.
4748 SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
4749                                               EVT VecVT, SDValue Op,
4750                                               unsigned Index,
4751                                               DAGCombinerInfo &DCI,
4752                                               bool Force) const {
4753   SelectionDAG &DAG = DCI.DAG;
4754 
4755   // The number of bytes being extracted.
4756   unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4757 
4758   for (;;) {
4759     unsigned Opcode = Op.getOpcode();
4760     if (Opcode == ISD::BITCAST)
4761       // Look through bitcasts.
4762       Op = Op.getOperand(0);
4763     else if (Opcode == ISD::VECTOR_SHUFFLE &&
4764              canTreatAsByteVector(Op.getValueType())) {
4765       // Get a VPERM-like permute mask and see whether the bytes covered
4766       // by the extracted element are a contiguous sequence from one
4767       // source operand.
4768       SmallVector<int, SystemZ::VectorBytes> Bytes;
4769       getVPermMask(cast<ShuffleVectorSDNode>(Op), Bytes);
4770       int First;
4771       if (!getShuffleInput(Bytes, Index * BytesPerElement,
4772                            BytesPerElement, First))
4773         break;
4774       if (First < 0)
4775         return DAG.getUNDEF(ResVT);
4776       // Make sure the contiguous sequence starts at a multiple of the
4777       // original element size.
4778       unsigned Byte = unsigned(First) % Bytes.size();
4779       if (Byte % BytesPerElement != 0)
4780         break;
4781       // We can get the extracted value directly from an input.
4782       Index = Byte / BytesPerElement;
4783       Op = Op.getOperand(unsigned(First) / Bytes.size());
4784       Force = true;
4785     } else if (Opcode == ISD::BUILD_VECTOR &&
4786                canTreatAsByteVector(Op.getValueType())) {
4787       // We can only optimize this case if the BUILD_VECTOR elements are
4788       // at least as wide as the extracted value.
4789       EVT OpVT = Op.getValueType();
4790       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4791       if (OpBytesPerElement < BytesPerElement)
4792         break;
4793       // Make sure that the least-significant bit of the extracted value
4794       // is the least significant bit of an input.
4795       unsigned End = (Index + 1) * BytesPerElement;
4796       if (End % OpBytesPerElement != 0)
4797         break;
4798       // We're extracting the low part of one operand of the BUILD_VECTOR.
4799       Op = Op.getOperand(End / OpBytesPerElement - 1);
4800       if (!Op.getValueType().isInteger()) {
4801         EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits());
4802         Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
4803         DCI.AddToWorklist(Op.getNode());
4804       }
4805       EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
4806       Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
4807       if (VT != ResVT) {
4808         DCI.AddToWorklist(Op.getNode());
4809         Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
4810       }
4811       return Op;
4812     } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
4813                 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
4814                 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
4815                canTreatAsByteVector(Op.getValueType()) &&
4816                canTreatAsByteVector(Op.getOperand(0).getValueType())) {
4817       // Make sure that only the unextended bits are significant.
4818       EVT ExtVT = Op.getValueType();
4819       EVT OpVT = Op.getOperand(0).getValueType();
4820       unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
4821       unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4822       unsigned Byte = Index * BytesPerElement;
4823       unsigned SubByte = Byte % ExtBytesPerElement;
4824       unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
4825       if (SubByte < MinSubByte ||
4826           SubByte + BytesPerElement > ExtBytesPerElement)
4827         break;
4828       // Get the byte offset of the unextended element
4829       Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
4830       // ...then add the byte offset relative to that element.
4831       Byte += SubByte - MinSubByte;
4832       if (Byte % BytesPerElement != 0)
4833         break;
4834       Op = Op.getOperand(0);
4835       Index = Byte / BytesPerElement;
4836       Force = true;
4837     } else
4838       break;
4839   }
4840   if (Force) {
4841     if (Op.getValueType() != VecVT) {
4842       Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
4843       DCI.AddToWorklist(Op.getNode());
4844     }
4845     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
4846                        DAG.getConstant(Index, DL, MVT::i32));
4847   }
4848   return SDValue();
4849 }
4850 
4851 // Optimize vector operations in scalar value Op on the basis that Op
4852 // is truncated to TruncVT.
4853 SDValue SystemZTargetLowering::combineTruncateExtract(
4854     const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
4855   // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
4856   // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
4857   // of type TruncVT.
4858   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4859       TruncVT.getSizeInBits() % 8 == 0) {
4860     SDValue Vec = Op.getOperand(0);
4861     EVT VecVT = Vec.getValueType();
4862     if (canTreatAsByteVector(VecVT)) {
4863       if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4864         unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4865         unsigned TruncBytes = TruncVT.getStoreSize();
4866         if (BytesPerElement % TruncBytes == 0) {
4867           // Calculate the value of Y' in the above description.  We are
4868           // splitting the original elements into Scale equal-sized pieces
4869           // and for truncation purposes want the last (least-significant)
4870           // of these pieces for IndexN.  This is easiest to do by calculating
4871           // the start index of the following element and then subtracting 1.
4872           unsigned Scale = BytesPerElement / TruncBytes;
4873           unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
4874 
4875           // Defer the creation of the bitcast from X to combineExtract,
4876           // which might be able to optimize the extraction.
4877           VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
4878                                    VecVT.getStoreSize() / TruncBytes);
4879           EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
4880           return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
4881         }
4882       }
4883     }
4884   }
4885   return SDValue();
4886 }
4887 
4888 SDValue SystemZTargetLowering::combineSIGN_EXTEND(
4889     SDNode *N, DAGCombinerInfo &DCI) const {
4890   // Convert (sext (ashr (shl X, C1), C2)) to
4891   // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
4892   // cheap as narrower ones.
4893   SelectionDAG &DAG = DCI.DAG;
4894   SDValue N0 = N->getOperand(0);
4895   EVT VT = N->getValueType(0);
4896   if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
4897     auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4898     SDValue Inner = N0.getOperand(0);
4899     if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
4900       if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
4901         unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
4902         unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
4903         unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
4904         EVT ShiftVT = N0.getOperand(1).getValueType();
4905         SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
4906                                   Inner.getOperand(0));
4907         SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
4908                                   DAG.getConstant(NewShlAmt, SDLoc(Inner),
4909                                                   ShiftVT));
4910         return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
4911                            DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
4912       }
4913     }
4914   }
4915   return SDValue();
4916 }
4917 
4918 SDValue SystemZTargetLowering::combineMERGE(
4919     SDNode *N, DAGCombinerInfo &DCI) const {
4920   SelectionDAG &DAG = DCI.DAG;
4921   unsigned Opcode = N->getOpcode();
4922   SDValue Op0 = N->getOperand(0);
4923   SDValue Op1 = N->getOperand(1);
4924   if (Op0.getOpcode() == ISD::BITCAST)
4925     Op0 = Op0.getOperand(0);
4926   if (Op0.getOpcode() == SystemZISD::BYTE_MASK &&
4927       cast<ConstantSDNode>(Op0.getOperand(0))->getZExtValue() == 0) {
4928     // (z_merge_* 0, 0) -> 0.  This is mostly useful for using VLLEZF
4929     // for v4f32.
4930     if (Op1 == N->getOperand(0))
4931       return Op1;
4932     // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
4933     EVT VT = Op1.getValueType();
4934     unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
4935     if (ElemBytes <= 4) {
4936       Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
4937                 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
4938       EVT InVT = VT.changeVectorElementTypeToInteger();
4939       EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
4940                                    SystemZ::VectorBytes / ElemBytes / 2);
4941       if (VT != InVT) {
4942         Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
4943         DCI.AddToWorklist(Op1.getNode());
4944       }
4945       SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
4946       DCI.AddToWorklist(Op.getNode());
4947       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
4948     }
4949   }
4950   return SDValue();
4951 }
4952 
4953 SDValue SystemZTargetLowering::combineSTORE(
4954     SDNode *N, DAGCombinerInfo &DCI) const {
4955   SelectionDAG &DAG = DCI.DAG;
4956   auto *SN = cast<StoreSDNode>(N);
4957   auto &Op1 = N->getOperand(1);
4958   EVT MemVT = SN->getMemoryVT();
4959   // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
4960   // for the extraction to be done on a vMiN value, so that we can use VSTE.
4961   // If X has wider elements then convert it to:
4962   // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
4963   if (MemVT.isInteger()) {
4964     if (SDValue Value =
4965             combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
4966       DCI.AddToWorklist(Value.getNode());
4967 
4968       // Rewrite the store with the new form of stored value.
4969       return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
4970                                SN->getBasePtr(), SN->getMemoryVT(),
4971                                SN->getMemOperand());
4972     }
4973   }
4974   // Combine STORE (BSWAP) into STRVH/STRV/STRVG
4975   // See comment in combineBSWAP about volatile accesses.
4976   if (!SN->isVolatile() &&
4977       Op1.getOpcode() == ISD::BSWAP &&
4978       Op1.getNode()->hasOneUse() &&
4979       (Op1.getValueType() == MVT::i16 ||
4980        Op1.getValueType() == MVT::i32 ||
4981        Op1.getValueType() == MVT::i64)) {
4982 
4983       SDValue BSwapOp = Op1.getOperand(0);
4984 
4985       if (BSwapOp.getValueType() == MVT::i16)
4986         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
4987 
4988       SDValue Ops[] = {
4989         N->getOperand(0), BSwapOp, N->getOperand(2),
4990         DAG.getValueType(Op1.getValueType())
4991       };
4992 
4993       return
4994         DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
4995                                 Ops, MemVT, SN->getMemOperand());
4996     }
4997   return SDValue();
4998 }
4999 
5000 SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
5001     SDNode *N, DAGCombinerInfo &DCI) const {
5002   // Try to simplify a vector extraction.
5003   if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
5004     SDValue Op0 = N->getOperand(0);
5005     EVT VecVT = Op0.getValueType();
5006     return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
5007                           IndexN->getZExtValue(), DCI, false);
5008   }
5009   return SDValue();
5010 }
5011 
5012 SDValue SystemZTargetLowering::combineJOIN_DWORDS(
5013     SDNode *N, DAGCombinerInfo &DCI) const {
5014   SelectionDAG &DAG = DCI.DAG;
5015   // (join_dwords X, X) == (replicate X)
5016   if (N->getOperand(0) == N->getOperand(1))
5017     return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
5018                        N->getOperand(0));
5019   return SDValue();
5020 }
5021 
5022 SDValue SystemZTargetLowering::combineFP_ROUND(
5023     SDNode *N, DAGCombinerInfo &DCI) const {
5024   // (fpround (extract_vector_elt X 0))
5025   // (fpround (extract_vector_elt X 1)) ->
5026   // (extract_vector_elt (VROUND X) 0)
5027   // (extract_vector_elt (VROUND X) 1)
5028   //
5029   // This is a special case since the target doesn't really support v2f32s.
5030   SelectionDAG &DAG = DCI.DAG;
5031   SDValue Op0 = N->getOperand(0);
5032   if (N->getValueType(0) == MVT::f32 &&
5033       Op0.hasOneUse() &&
5034       Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5035       Op0.getOperand(0).getValueType() == MVT::v2f64 &&
5036       Op0.getOperand(1).getOpcode() == ISD::Constant &&
5037       cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
5038     SDValue Vec = Op0.getOperand(0);
5039     for (auto *U : Vec->uses()) {
5040       if (U != Op0.getNode() &&
5041           U->hasOneUse() &&
5042           U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5043           U->getOperand(0) == Vec &&
5044           U->getOperand(1).getOpcode() == ISD::Constant &&
5045           cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
5046         SDValue OtherRound = SDValue(*U->use_begin(), 0);
5047         if (OtherRound.getOpcode() == ISD::FP_ROUND &&
5048             OtherRound.getOperand(0) == SDValue(U, 0) &&
5049             OtherRound.getValueType() == MVT::f32) {
5050           SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
5051                                        MVT::v4f32, Vec);
5052           DCI.AddToWorklist(VRound.getNode());
5053           SDValue Extract1 =
5054             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
5055                         VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
5056           DCI.AddToWorklist(Extract1.getNode());
5057           DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
5058           SDValue Extract0 =
5059             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
5060                         VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
5061           return Extract0;
5062         }
5063       }
5064     }
5065   }
5066   return SDValue();
5067 }
5068 
5069 SDValue SystemZTargetLowering::combineBSWAP(
5070     SDNode *N, DAGCombinerInfo &DCI) const {
5071   SelectionDAG &DAG = DCI.DAG;
5072   // Combine BSWAP (LOAD) into LRVH/LRV/LRVG
5073   // These loads are allowed to access memory multiple times, and so we must check
5074   // that the loads are not volatile before performing the combine.
5075   if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
5076       N->getOperand(0).hasOneUse() &&
5077       (N->getValueType(0) == MVT::i16 || N->getValueType(0) == MVT::i32 ||
5078        N->getValueType(0) == MVT::i64) &&
5079        !cast<LoadSDNode>(N->getOperand(0))->isVolatile()) {
5080       SDValue Load = N->getOperand(0);
5081       LoadSDNode *LD = cast<LoadSDNode>(Load);
5082 
5083       // Create the byte-swapping load.
5084       SDValue Ops[] = {
5085         LD->getChain(),    // Chain
5086         LD->getBasePtr(),  // Ptr
5087         DAG.getValueType(N->getValueType(0)) // VT
5088       };
5089       SDValue BSLoad =
5090         DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
5091                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
5092                                               MVT::i64 : MVT::i32, MVT::Other),
5093                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
5094 
5095       // If this is an i16 load, insert the truncate.
5096       SDValue ResVal = BSLoad;
5097       if (N->getValueType(0) == MVT::i16)
5098         ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
5099 
5100       // First, combine the bswap away.  This makes the value produced by the
5101       // load dead.
5102       DCI.CombineTo(N, ResVal);
5103 
5104       // Next, combine the load away, we give it a bogus result value but a real
5105       // chain result.  The result value is dead because the bswap is dead.
5106       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
5107 
5108       // Return N so it doesn't get rechecked!
5109       return SDValue(N, 0);
5110     }
5111   return SDValue();
5112 }
5113 
5114 SDValue SystemZTargetLowering::combineSHIFTROT(
5115     SDNode *N, DAGCombinerInfo &DCI) const {
5116 
5117   SelectionDAG &DAG = DCI.DAG;
5118 
5119   // Shift/rotate instructions only use the last 6 bits of the second operand
5120   // register. If the second operand is the result of an AND with an immediate
5121   // value that has its last 6 bits set, we can safely remove the AND operation.
5122   //
5123   // If the AND operation doesn't have the last 6 bits set, we can't remove it
5124   // entirely, but we can still truncate it to a 16-bit value. This prevents
5125   // us from ending up with a NILL with a signed operand, which will cause the
5126   // instruction printer to abort.
5127   SDValue N1 = N->getOperand(1);
5128   if (N1.getOpcode() == ISD::AND) {
5129     SDValue AndMaskOp = N1->getOperand(1);
5130     auto *AndMask = dyn_cast<ConstantSDNode>(AndMaskOp);
5131 
5132     // The AND mask is constant
5133     if (AndMask) {
5134       auto AmtVal = AndMask->getZExtValue();
5135 
5136       // Bottom 6 bits are set
5137       if ((AmtVal & 0x3f) == 0x3f) {
5138         SDValue AndOp = N1->getOperand(0);
5139 
5140         // This is the only use, so remove the node
5141         if (N1.hasOneUse()) {
5142           // Combine the AND away
5143           DCI.CombineTo(N1.getNode(), AndOp);
5144 
5145           // Return N so it isn't rechecked
5146           return SDValue(N, 0);
5147 
5148         // The node will be reused, so create a new node for this one use
5149         } else {
5150           SDValue Replace = DAG.getNode(N->getOpcode(), SDLoc(N),
5151                                         N->getValueType(0), N->getOperand(0),
5152                                         AndOp);
5153           DCI.AddToWorklist(Replace.getNode());
5154 
5155           return Replace;
5156         }
5157 
5158       // We can't remove the AND, but we can use NILL here (normally we would
5159       // use NILF). Only keep the last 16 bits of the mask. The actual
5160       // transformation will be handled by .td definitions.
5161       } else if (AmtVal >> 16 != 0) {
5162         SDValue AndOp = N1->getOperand(0);
5163 
5164         auto NewMask = DAG.getConstant(AndMask->getZExtValue() & 0x0000ffff,
5165                                        SDLoc(AndMaskOp),
5166                                        AndMaskOp.getValueType());
5167 
5168         auto NewAnd = DAG.getNode(N1.getOpcode(), SDLoc(N1), N1.getValueType(),
5169                                   AndOp, NewMask);
5170 
5171         SDValue Replace = DAG.getNode(N->getOpcode(), SDLoc(N),
5172                                       N->getValueType(0), N->getOperand(0),
5173                                       NewAnd);
5174         DCI.AddToWorklist(Replace.getNode());
5175 
5176         return Replace;
5177       }
5178     }
5179   }
5180 
5181   return SDValue();
5182 }
5183 
5184 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
5185                                                  DAGCombinerInfo &DCI) const {
5186   switch(N->getOpcode()) {
5187   default: break;
5188   case ISD::SIGN_EXTEND:        return combineSIGN_EXTEND(N, DCI);
5189   case SystemZISD::MERGE_HIGH:
5190   case SystemZISD::MERGE_LOW:   return combineMERGE(N, DCI);
5191   case ISD::STORE:              return combineSTORE(N, DCI);
5192   case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
5193   case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
5194   case ISD::FP_ROUND:           return combineFP_ROUND(N, DCI);
5195   case ISD::BSWAP:              return combineBSWAP(N, DCI);
5196   case ISD::SHL:
5197   case ISD::SRA:
5198   case ISD::SRL:
5199   case ISD::ROTL:               return combineSHIFTROT(N, DCI);
5200   }
5201 
5202   return SDValue();
5203 }
5204 
5205 //===----------------------------------------------------------------------===//
5206 // Custom insertion
5207 //===----------------------------------------------------------------------===//
5208 
5209 // Create a new basic block after MBB.
5210 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
5211   MachineFunction &MF = *MBB->getParent();
5212   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
5213   MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
5214   return NewMBB;
5215 }
5216 
5217 // Split MBB after MI and return the new block (the one that contains
5218 // instructions after MI).
5219 static MachineBasicBlock *splitBlockAfter(MachineBasicBlock::iterator MI,
5220                                           MachineBasicBlock *MBB) {
5221   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
5222   NewMBB->splice(NewMBB->begin(), MBB,
5223                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
5224   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
5225   return NewMBB;
5226 }
5227 
5228 // Split MBB before MI and return the new block (the one that contains MI).
5229 static MachineBasicBlock *splitBlockBefore(MachineBasicBlock::iterator MI,
5230                                            MachineBasicBlock *MBB) {
5231   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
5232   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
5233   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
5234   return NewMBB;
5235 }
5236 
5237 // Force base value Base into a register before MI.  Return the register.
5238 static unsigned forceReg(MachineInstr &MI, MachineOperand &Base,
5239                          const SystemZInstrInfo *TII) {
5240   if (Base.isReg())
5241     return Base.getReg();
5242 
5243   MachineBasicBlock *MBB = MI.getParent();
5244   MachineFunction &MF = *MBB->getParent();
5245   MachineRegisterInfo &MRI = MF.getRegInfo();
5246 
5247   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5248   BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
5249       .add(Base)
5250       .addImm(0)
5251       .addReg(0);
5252   return Reg;
5253 }
5254 
5255 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
5256 MachineBasicBlock *
5257 SystemZTargetLowering::emitSelect(MachineInstr &MI,
5258                                   MachineBasicBlock *MBB,
5259                                   unsigned LOCROpcode) const {
5260   const SystemZInstrInfo *TII =
5261       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5262 
5263   unsigned DestReg = MI.getOperand(0).getReg();
5264   unsigned TrueReg = MI.getOperand(1).getReg();
5265   unsigned FalseReg = MI.getOperand(2).getReg();
5266   unsigned CCValid = MI.getOperand(3).getImm();
5267   unsigned CCMask = MI.getOperand(4).getImm();
5268   DebugLoc DL = MI.getDebugLoc();
5269 
5270   // Use LOCROpcode if possible.
5271   if (LOCROpcode && Subtarget.hasLoadStoreOnCond()) {
5272     BuildMI(*MBB, MI, DL, TII->get(LOCROpcode), DestReg)
5273       .addReg(FalseReg).addReg(TrueReg)
5274       .addImm(CCValid).addImm(CCMask);
5275     MI.eraseFromParent();
5276     return MBB;
5277   }
5278 
5279   MachineBasicBlock *StartMBB = MBB;
5280   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
5281   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
5282 
5283   //  StartMBB:
5284   //   BRC CCMask, JoinMBB
5285   //   # fallthrough to FalseMBB
5286   MBB = StartMBB;
5287   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5288     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
5289   MBB->addSuccessor(JoinMBB);
5290   MBB->addSuccessor(FalseMBB);
5291 
5292   //  FalseMBB:
5293   //   # fallthrough to JoinMBB
5294   MBB = FalseMBB;
5295   MBB->addSuccessor(JoinMBB);
5296 
5297   //  JoinMBB:
5298   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
5299   //  ...
5300   MBB = JoinMBB;
5301   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
5302     .addReg(TrueReg).addMBB(StartMBB)
5303     .addReg(FalseReg).addMBB(FalseMBB);
5304 
5305   MI.eraseFromParent();
5306   return JoinMBB;
5307 }
5308 
5309 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
5310 // StoreOpcode is the store to use and Invert says whether the store should
5311 // happen when the condition is false rather than true.  If a STORE ON
5312 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
5313 MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
5314                                                         MachineBasicBlock *MBB,
5315                                                         unsigned StoreOpcode,
5316                                                         unsigned STOCOpcode,
5317                                                         bool Invert) const {
5318   const SystemZInstrInfo *TII =
5319       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5320 
5321   unsigned SrcReg = MI.getOperand(0).getReg();
5322   MachineOperand Base = MI.getOperand(1);
5323   int64_t Disp = MI.getOperand(2).getImm();
5324   unsigned IndexReg = MI.getOperand(3).getReg();
5325   unsigned CCValid = MI.getOperand(4).getImm();
5326   unsigned CCMask = MI.getOperand(5).getImm();
5327   DebugLoc DL = MI.getDebugLoc();
5328 
5329   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
5330 
5331   // Use STOCOpcode if possible.  We could use different store patterns in
5332   // order to avoid matching the index register, but the performance trade-offs
5333   // might be more complicated in that case.
5334   if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
5335     if (Invert)
5336       CCMask ^= CCValid;
5337     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
5338         .addReg(SrcReg)
5339         .add(Base)
5340         .addImm(Disp)
5341         .addImm(CCValid)
5342         .addImm(CCMask);
5343     MI.eraseFromParent();
5344     return MBB;
5345   }
5346 
5347   // Get the condition needed to branch around the store.
5348   if (!Invert)
5349     CCMask ^= CCValid;
5350 
5351   MachineBasicBlock *StartMBB = MBB;
5352   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
5353   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
5354 
5355   //  StartMBB:
5356   //   BRC CCMask, JoinMBB
5357   //   # fallthrough to FalseMBB
5358   MBB = StartMBB;
5359   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5360     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
5361   MBB->addSuccessor(JoinMBB);
5362   MBB->addSuccessor(FalseMBB);
5363 
5364   //  FalseMBB:
5365   //   store %SrcReg, %Disp(%Index,%Base)
5366   //   # fallthrough to JoinMBB
5367   MBB = FalseMBB;
5368   BuildMI(MBB, DL, TII->get(StoreOpcode))
5369       .addReg(SrcReg)
5370       .add(Base)
5371       .addImm(Disp)
5372       .addReg(IndexReg);
5373   MBB->addSuccessor(JoinMBB);
5374 
5375   MI.eraseFromParent();
5376   return JoinMBB;
5377 }
5378 
5379 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
5380 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
5381 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
5382 // BitSize is the width of the field in bits, or 0 if this is a partword
5383 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
5384 // is one of the operands.  Invert says whether the field should be
5385 // inverted after performing BinOpcode (e.g. for NAND).
5386 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
5387     MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
5388     unsigned BitSize, bool Invert) const {
5389   MachineFunction &MF = *MBB->getParent();
5390   const SystemZInstrInfo *TII =
5391       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5392   MachineRegisterInfo &MRI = MF.getRegInfo();
5393   bool IsSubWord = (BitSize < 32);
5394 
5395   // Extract the operands.  Base can be a register or a frame index.
5396   // Src2 can be a register or immediate.
5397   unsigned Dest = MI.getOperand(0).getReg();
5398   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5399   int64_t Disp = MI.getOperand(2).getImm();
5400   MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
5401   unsigned BitShift = (IsSubWord ? MI.getOperand(4).getReg() : 0);
5402   unsigned NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : 0);
5403   DebugLoc DL = MI.getDebugLoc();
5404   if (IsSubWord)
5405     BitSize = MI.getOperand(6).getImm();
5406 
5407   // Subword operations use 32-bit registers.
5408   const TargetRegisterClass *RC = (BitSize <= 32 ?
5409                                    &SystemZ::GR32BitRegClass :
5410                                    &SystemZ::GR64BitRegClass);
5411   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
5412   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5413 
5414   // Get the right opcodes for the displacement.
5415   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
5416   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5417   assert(LOpcode && CSOpcode && "Displacement out of range");
5418 
5419   // Create virtual registers for temporary results.
5420   unsigned OrigVal       = MRI.createVirtualRegister(RC);
5421   unsigned OldVal        = MRI.createVirtualRegister(RC);
5422   unsigned NewVal        = (BinOpcode || IsSubWord ?
5423                             MRI.createVirtualRegister(RC) : Src2.getReg());
5424   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5425   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5426 
5427   // Insert a basic block for the main loop.
5428   MachineBasicBlock *StartMBB = MBB;
5429   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
5430   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
5431 
5432   //  StartMBB:
5433   //   ...
5434   //   %OrigVal = L Disp(%Base)
5435   //   # fall through to LoopMMB
5436   MBB = StartMBB;
5437   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
5438   MBB->addSuccessor(LoopMBB);
5439 
5440   //  LoopMBB:
5441   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
5442   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5443   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
5444   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
5445   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
5446   //   JNE LoopMBB
5447   //   # fall through to DoneMMB
5448   MBB = LoopMBB;
5449   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5450     .addReg(OrigVal).addMBB(StartMBB)
5451     .addReg(Dest).addMBB(LoopMBB);
5452   if (IsSubWord)
5453     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5454       .addReg(OldVal).addReg(BitShift).addImm(0);
5455   if (Invert) {
5456     // Perform the operation normally and then invert every bit of the field.
5457     unsigned Tmp = MRI.createVirtualRegister(RC);
5458     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp).addReg(RotatedOldVal).add(Src2);
5459     if (BitSize <= 32)
5460       // XILF with the upper BitSize bits set.
5461       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
5462         .addReg(Tmp).addImm(-1U << (32 - BitSize));
5463     else {
5464       // Use LCGR and add -1 to the result, which is more compact than
5465       // an XILF, XILH pair.
5466       unsigned Tmp2 = MRI.createVirtualRegister(RC);
5467       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
5468       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
5469         .addReg(Tmp2).addImm(-1);
5470     }
5471   } else if (BinOpcode)
5472     // A simply binary operation.
5473     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
5474         .addReg(RotatedOldVal)
5475         .add(Src2);
5476   else if (IsSubWord)
5477     // Use RISBG to rotate Src2 into position and use it to replace the
5478     // field in RotatedOldVal.
5479     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
5480       .addReg(RotatedOldVal).addReg(Src2.getReg())
5481       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
5482   if (IsSubWord)
5483     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5484       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5485   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5486       .addReg(OldVal)
5487       .addReg(NewVal)
5488       .add(Base)
5489       .addImm(Disp);
5490   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5491     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5492   MBB->addSuccessor(LoopMBB);
5493   MBB->addSuccessor(DoneMBB);
5494 
5495   MI.eraseFromParent();
5496   return DoneMBB;
5497 }
5498 
5499 // Implement EmitInstrWithCustomInserter for pseudo
5500 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
5501 // instruction that should be used to compare the current field with the
5502 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
5503 // for when the current field should be kept.  BitSize is the width of
5504 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
5505 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
5506     MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
5507     unsigned KeepOldMask, unsigned BitSize) const {
5508   MachineFunction &MF = *MBB->getParent();
5509   const SystemZInstrInfo *TII =
5510       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5511   MachineRegisterInfo &MRI = MF.getRegInfo();
5512   bool IsSubWord = (BitSize < 32);
5513 
5514   // Extract the operands.  Base can be a register or a frame index.
5515   unsigned Dest = MI.getOperand(0).getReg();
5516   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5517   int64_t Disp = MI.getOperand(2).getImm();
5518   unsigned Src2 = MI.getOperand(3).getReg();
5519   unsigned BitShift = (IsSubWord ? MI.getOperand(4).getReg() : 0);
5520   unsigned NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : 0);
5521   DebugLoc DL = MI.getDebugLoc();
5522   if (IsSubWord)
5523     BitSize = MI.getOperand(6).getImm();
5524 
5525   // Subword operations use 32-bit registers.
5526   const TargetRegisterClass *RC = (BitSize <= 32 ?
5527                                    &SystemZ::GR32BitRegClass :
5528                                    &SystemZ::GR64BitRegClass);
5529   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
5530   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5531 
5532   // Get the right opcodes for the displacement.
5533   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
5534   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5535   assert(LOpcode && CSOpcode && "Displacement out of range");
5536 
5537   // Create virtual registers for temporary results.
5538   unsigned OrigVal       = MRI.createVirtualRegister(RC);
5539   unsigned OldVal        = MRI.createVirtualRegister(RC);
5540   unsigned NewVal        = MRI.createVirtualRegister(RC);
5541   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5542   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
5543   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5544 
5545   // Insert 3 basic blocks for the loop.
5546   MachineBasicBlock *StartMBB  = MBB;
5547   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
5548   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
5549   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
5550   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
5551 
5552   //  StartMBB:
5553   //   ...
5554   //   %OrigVal     = L Disp(%Base)
5555   //   # fall through to LoopMMB
5556   MBB = StartMBB;
5557   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
5558   MBB->addSuccessor(LoopMBB);
5559 
5560   //  LoopMBB:
5561   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
5562   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5563   //   CompareOpcode %RotatedOldVal, %Src2
5564   //   BRC KeepOldMask, UpdateMBB
5565   MBB = LoopMBB;
5566   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5567     .addReg(OrigVal).addMBB(StartMBB)
5568     .addReg(Dest).addMBB(UpdateMBB);
5569   if (IsSubWord)
5570     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5571       .addReg(OldVal).addReg(BitShift).addImm(0);
5572   BuildMI(MBB, DL, TII->get(CompareOpcode))
5573     .addReg(RotatedOldVal).addReg(Src2);
5574   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5575     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
5576   MBB->addSuccessor(UpdateMBB);
5577   MBB->addSuccessor(UseAltMBB);
5578 
5579   //  UseAltMBB:
5580   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
5581   //   # fall through to UpdateMMB
5582   MBB = UseAltMBB;
5583   if (IsSubWord)
5584     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
5585       .addReg(RotatedOldVal).addReg(Src2)
5586       .addImm(32).addImm(31 + BitSize).addImm(0);
5587   MBB->addSuccessor(UpdateMBB);
5588 
5589   //  UpdateMBB:
5590   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
5591   //                        [ %RotatedAltVal, UseAltMBB ]
5592   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
5593   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
5594   //   JNE LoopMBB
5595   //   # fall through to DoneMMB
5596   MBB = UpdateMBB;
5597   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
5598     .addReg(RotatedOldVal).addMBB(LoopMBB)
5599     .addReg(RotatedAltVal).addMBB(UseAltMBB);
5600   if (IsSubWord)
5601     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5602       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5603   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5604       .addReg(OldVal)
5605       .addReg(NewVal)
5606       .add(Base)
5607       .addImm(Disp);
5608   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5609     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5610   MBB->addSuccessor(LoopMBB);
5611   MBB->addSuccessor(DoneMBB);
5612 
5613   MI.eraseFromParent();
5614   return DoneMBB;
5615 }
5616 
5617 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
5618 // instruction MI.
5619 MachineBasicBlock *
5620 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
5621                                           MachineBasicBlock *MBB) const {
5622 
5623   MachineFunction &MF = *MBB->getParent();
5624   const SystemZInstrInfo *TII =
5625       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5626   MachineRegisterInfo &MRI = MF.getRegInfo();
5627 
5628   // Extract the operands.  Base can be a register or a frame index.
5629   unsigned Dest = MI.getOperand(0).getReg();
5630   MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5631   int64_t Disp = MI.getOperand(2).getImm();
5632   unsigned OrigCmpVal = MI.getOperand(3).getReg();
5633   unsigned OrigSwapVal = MI.getOperand(4).getReg();
5634   unsigned BitShift = MI.getOperand(5).getReg();
5635   unsigned NegBitShift = MI.getOperand(6).getReg();
5636   int64_t BitSize = MI.getOperand(7).getImm();
5637   DebugLoc DL = MI.getDebugLoc();
5638 
5639   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
5640 
5641   // Get the right opcodes for the displacement.
5642   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
5643   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
5644   assert(LOpcode && CSOpcode && "Displacement out of range");
5645 
5646   // Create virtual registers for temporary results.
5647   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
5648   unsigned OldVal       = MRI.createVirtualRegister(RC);
5649   unsigned CmpVal       = MRI.createVirtualRegister(RC);
5650   unsigned SwapVal      = MRI.createVirtualRegister(RC);
5651   unsigned StoreVal     = MRI.createVirtualRegister(RC);
5652   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
5653   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
5654   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
5655 
5656   // Insert 2 basic blocks for the loop.
5657   MachineBasicBlock *StartMBB = MBB;
5658   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
5659   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
5660   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
5661 
5662   //  StartMBB:
5663   //   ...
5664   //   %OrigOldVal     = L Disp(%Base)
5665   //   # fall through to LoopMMB
5666   MBB = StartMBB;
5667   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
5668       .add(Base)
5669       .addImm(Disp)
5670       .addReg(0);
5671   MBB->addSuccessor(LoopMBB);
5672 
5673   //  LoopMBB:
5674   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
5675   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
5676   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
5677   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
5678   //                      ^^ The low BitSize bits contain the field
5679   //                         of interest.
5680   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
5681   //                      ^^ Replace the upper 32-BitSize bits of the
5682   //                         comparison value with those that we loaded,
5683   //                         so that we can use a full word comparison.
5684   //   CR %Dest, %RetryCmpVal
5685   //   JNE DoneMBB
5686   //   # Fall through to SetMBB
5687   MBB = LoopMBB;
5688   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5689     .addReg(OrigOldVal).addMBB(StartMBB)
5690     .addReg(RetryOldVal).addMBB(SetMBB);
5691   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
5692     .addReg(OrigCmpVal).addMBB(StartMBB)
5693     .addReg(RetryCmpVal).addMBB(SetMBB);
5694   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
5695     .addReg(OrigSwapVal).addMBB(StartMBB)
5696     .addReg(RetrySwapVal).addMBB(SetMBB);
5697   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
5698     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
5699   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
5700     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5701   BuildMI(MBB, DL, TII->get(SystemZ::CR))
5702     .addReg(Dest).addReg(RetryCmpVal);
5703   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5704     .addImm(SystemZ::CCMASK_ICMP)
5705     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
5706   MBB->addSuccessor(DoneMBB);
5707   MBB->addSuccessor(SetMBB);
5708 
5709   //  SetMBB:
5710   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
5711   //                      ^^ Replace the upper 32-BitSize bits of the new
5712   //                         value with those that we loaded.
5713   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
5714   //                      ^^ Rotate the new field to its proper position.
5715   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
5716   //   JNE LoopMBB
5717   //   # fall through to ExitMMB
5718   MBB = SetMBB;
5719   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
5720     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5721   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
5722     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
5723   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
5724       .addReg(OldVal)
5725       .addReg(StoreVal)
5726       .add(Base)
5727       .addImm(Disp);
5728   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5729     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5730   MBB->addSuccessor(LoopMBB);
5731   MBB->addSuccessor(DoneMBB);
5732 
5733   MI.eraseFromParent();
5734   return DoneMBB;
5735 }
5736 
5737 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
5738 // if the high register of the GR128 value must be cleared or false if
5739 // it's "don't care".  SubReg is subreg_l32 when extending a GR32
5740 // and subreg_l64 when extending a GR64.
5741 MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI,
5742                                                      MachineBasicBlock *MBB,
5743                                                      bool ClearEven,
5744                                                      unsigned SubReg) const {
5745   MachineFunction &MF = *MBB->getParent();
5746   const SystemZInstrInfo *TII =
5747       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5748   MachineRegisterInfo &MRI = MF.getRegInfo();
5749   DebugLoc DL = MI.getDebugLoc();
5750 
5751   unsigned Dest = MI.getOperand(0).getReg();
5752   unsigned Src = MI.getOperand(1).getReg();
5753   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5754 
5755   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
5756   if (ClearEven) {
5757     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5758     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
5759 
5760     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
5761       .addImm(0);
5762     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
5763       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
5764     In128 = NewIn128;
5765   }
5766   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
5767     .addReg(In128).addReg(Src).addImm(SubReg);
5768 
5769   MI.eraseFromParent();
5770   return MBB;
5771 }
5772 
5773 MachineBasicBlock *SystemZTargetLowering::emitMemMemWrapper(
5774     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
5775   MachineFunction &MF = *MBB->getParent();
5776   const SystemZInstrInfo *TII =
5777       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5778   MachineRegisterInfo &MRI = MF.getRegInfo();
5779   DebugLoc DL = MI.getDebugLoc();
5780 
5781   MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
5782   uint64_t DestDisp = MI.getOperand(1).getImm();
5783   MachineOperand SrcBase = earlyUseOperand(MI.getOperand(2));
5784   uint64_t SrcDisp = MI.getOperand(3).getImm();
5785   uint64_t Length = MI.getOperand(4).getImm();
5786 
5787   // When generating more than one CLC, all but the last will need to
5788   // branch to the end when a difference is found.
5789   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
5790                                splitBlockAfter(MI, MBB) : nullptr);
5791 
5792   // Check for the loop form, in which operand 5 is the trip count.
5793   if (MI.getNumExplicitOperands() > 5) {
5794     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
5795 
5796     uint64_t StartCountReg = MI.getOperand(5).getReg();
5797     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
5798     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
5799                               forceReg(MI, DestBase, TII));
5800 
5801     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
5802     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
5803     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
5804                             MRI.createVirtualRegister(RC));
5805     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
5806     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
5807                             MRI.createVirtualRegister(RC));
5808 
5809     RC = &SystemZ::GR64BitRegClass;
5810     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
5811     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
5812 
5813     MachineBasicBlock *StartMBB = MBB;
5814     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5815     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5816     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
5817 
5818     //  StartMBB:
5819     //   # fall through to LoopMMB
5820     MBB->addSuccessor(LoopMBB);
5821 
5822     //  LoopMBB:
5823     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
5824     //                      [ %NextDestReg, NextMBB ]
5825     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
5826     //                     [ %NextSrcReg, NextMBB ]
5827     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
5828     //                       [ %NextCountReg, NextMBB ]
5829     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
5830     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
5831     //   ( JLH EndMBB )
5832     //
5833     // The prefetch is used only for MVC.  The JLH is used only for CLC.
5834     MBB = LoopMBB;
5835 
5836     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
5837       .addReg(StartDestReg).addMBB(StartMBB)
5838       .addReg(NextDestReg).addMBB(NextMBB);
5839     if (!HaveSingleBase)
5840       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
5841         .addReg(StartSrcReg).addMBB(StartMBB)
5842         .addReg(NextSrcReg).addMBB(NextMBB);
5843     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
5844       .addReg(StartCountReg).addMBB(StartMBB)
5845       .addReg(NextCountReg).addMBB(NextMBB);
5846     if (Opcode == SystemZ::MVC)
5847       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
5848         .addImm(SystemZ::PFD_WRITE)
5849         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
5850     BuildMI(MBB, DL, TII->get(Opcode))
5851       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
5852       .addReg(ThisSrcReg).addImm(SrcDisp);
5853     if (EndMBB) {
5854       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5855         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5856         .addMBB(EndMBB);
5857       MBB->addSuccessor(EndMBB);
5858       MBB->addSuccessor(NextMBB);
5859     }
5860 
5861     // NextMBB:
5862     //   %NextDestReg = LA 256(%ThisDestReg)
5863     //   %NextSrcReg = LA 256(%ThisSrcReg)
5864     //   %NextCountReg = AGHI %ThisCountReg, -1
5865     //   CGHI %NextCountReg, 0
5866     //   JLH LoopMBB
5867     //   # fall through to DoneMMB
5868     //
5869     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
5870     MBB = NextMBB;
5871 
5872     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
5873       .addReg(ThisDestReg).addImm(256).addReg(0);
5874     if (!HaveSingleBase)
5875       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
5876         .addReg(ThisSrcReg).addImm(256).addReg(0);
5877     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
5878       .addReg(ThisCountReg).addImm(-1);
5879     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
5880       .addReg(NextCountReg).addImm(0);
5881     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5882       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5883       .addMBB(LoopMBB);
5884     MBB->addSuccessor(LoopMBB);
5885     MBB->addSuccessor(DoneMBB);
5886 
5887     DestBase = MachineOperand::CreateReg(NextDestReg, false);
5888     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
5889     Length &= 255;
5890     MBB = DoneMBB;
5891   }
5892   // Handle any remaining bytes with straight-line code.
5893   while (Length > 0) {
5894     uint64_t ThisLength = std::min(Length, uint64_t(256));
5895     // The previous iteration might have created out-of-range displacements.
5896     // Apply them using LAY if so.
5897     if (!isUInt<12>(DestDisp)) {
5898       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5899       BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5900           .add(DestBase)
5901           .addImm(DestDisp)
5902           .addReg(0);
5903       DestBase = MachineOperand::CreateReg(Reg, false);
5904       DestDisp = 0;
5905     }
5906     if (!isUInt<12>(SrcDisp)) {
5907       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5908       BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5909           .add(SrcBase)
5910           .addImm(SrcDisp)
5911           .addReg(0);
5912       SrcBase = MachineOperand::CreateReg(Reg, false);
5913       SrcDisp = 0;
5914     }
5915     BuildMI(*MBB, MI, DL, TII->get(Opcode))
5916         .add(DestBase)
5917         .addImm(DestDisp)
5918         .addImm(ThisLength)
5919         .add(SrcBase)
5920         .addImm(SrcDisp);
5921     DestDisp += ThisLength;
5922     SrcDisp += ThisLength;
5923     Length -= ThisLength;
5924     // If there's another CLC to go, branch to the end if a difference
5925     // was found.
5926     if (EndMBB && Length > 0) {
5927       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
5928       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5929         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5930         .addMBB(EndMBB);
5931       MBB->addSuccessor(EndMBB);
5932       MBB->addSuccessor(NextMBB);
5933       MBB = NextMBB;
5934     }
5935   }
5936   if (EndMBB) {
5937     MBB->addSuccessor(EndMBB);
5938     MBB = EndMBB;
5939     MBB->addLiveIn(SystemZ::CC);
5940   }
5941 
5942   MI.eraseFromParent();
5943   return MBB;
5944 }
5945 
5946 // Decompose string pseudo-instruction MI into a loop that continually performs
5947 // Opcode until CC != 3.
5948 MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
5949     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
5950   MachineFunction &MF = *MBB->getParent();
5951   const SystemZInstrInfo *TII =
5952       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5953   MachineRegisterInfo &MRI = MF.getRegInfo();
5954   DebugLoc DL = MI.getDebugLoc();
5955 
5956   uint64_t End1Reg = MI.getOperand(0).getReg();
5957   uint64_t Start1Reg = MI.getOperand(1).getReg();
5958   uint64_t Start2Reg = MI.getOperand(2).getReg();
5959   uint64_t CharReg = MI.getOperand(3).getReg();
5960 
5961   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
5962   uint64_t This1Reg = MRI.createVirtualRegister(RC);
5963   uint64_t This2Reg = MRI.createVirtualRegister(RC);
5964   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
5965 
5966   MachineBasicBlock *StartMBB = MBB;
5967   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5968   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5969 
5970   //  StartMBB:
5971   //   # fall through to LoopMMB
5972   MBB->addSuccessor(LoopMBB);
5973 
5974   //  LoopMBB:
5975   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
5976   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
5977   //   R0L = %CharReg
5978   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
5979   //   JO LoopMBB
5980   //   # fall through to DoneMMB
5981   //
5982   // The load of R0L can be hoisted by post-RA LICM.
5983   MBB = LoopMBB;
5984 
5985   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
5986     .addReg(Start1Reg).addMBB(StartMBB)
5987     .addReg(End1Reg).addMBB(LoopMBB);
5988   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
5989     .addReg(Start2Reg).addMBB(StartMBB)
5990     .addReg(End2Reg).addMBB(LoopMBB);
5991   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
5992   BuildMI(MBB, DL, TII->get(Opcode))
5993     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
5994     .addReg(This1Reg).addReg(This2Reg);
5995   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5996     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
5997   MBB->addSuccessor(LoopMBB);
5998   MBB->addSuccessor(DoneMBB);
5999 
6000   DoneMBB->addLiveIn(SystemZ::CC);
6001 
6002   MI.eraseFromParent();
6003   return DoneMBB;
6004 }
6005 
6006 // Update TBEGIN instruction with final opcode and register clobbers.
6007 MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
6008     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
6009     bool NoFloat) const {
6010   MachineFunction &MF = *MBB->getParent();
6011   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
6012   const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
6013 
6014   // Update opcode.
6015   MI.setDesc(TII->get(Opcode));
6016 
6017   // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
6018   // Make sure to add the corresponding GRSM bits if they are missing.
6019   uint64_t Control = MI.getOperand(2).getImm();
6020   static const unsigned GPRControlBit[16] = {
6021     0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
6022     0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
6023   };
6024   Control |= GPRControlBit[15];
6025   if (TFI->hasFP(MF))
6026     Control |= GPRControlBit[11];
6027   MI.getOperand(2).setImm(Control);
6028 
6029   // Add GPR clobbers.
6030   for (int I = 0; I < 16; I++) {
6031     if ((Control & GPRControlBit[I]) == 0) {
6032       unsigned Reg = SystemZMC::GR64Regs[I];
6033       MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
6034     }
6035   }
6036 
6037   // Add FPR/VR clobbers.
6038   if (!NoFloat && (Control & 4) != 0) {
6039     if (Subtarget.hasVector()) {
6040       for (int I = 0; I < 32; I++) {
6041         unsigned Reg = SystemZMC::VR128Regs[I];
6042         MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
6043       }
6044     } else {
6045       for (int I = 0; I < 16; I++) {
6046         unsigned Reg = SystemZMC::FP64Regs[I];
6047         MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
6048       }
6049     }
6050   }
6051 
6052   return MBB;
6053 }
6054 
6055 MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
6056     MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
6057   MachineFunction &MF = *MBB->getParent();
6058   MachineRegisterInfo *MRI = &MF.getRegInfo();
6059   const SystemZInstrInfo *TII =
6060       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
6061   DebugLoc DL = MI.getDebugLoc();
6062 
6063   unsigned SrcReg = MI.getOperand(0).getReg();
6064 
6065   // Create new virtual register of the same class as source.
6066   const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
6067   unsigned DstReg = MRI->createVirtualRegister(RC);
6068 
6069   // Replace pseudo with a normal load-and-test that models the def as
6070   // well.
6071   BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
6072     .addReg(SrcReg);
6073   MI.eraseFromParent();
6074 
6075   return MBB;
6076 }
6077 
6078 MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter(
6079     MachineInstr &MI, MachineBasicBlock *MBB) const {
6080   switch (MI.getOpcode()) {
6081   case SystemZ::Select32Mux:
6082     return emitSelect(MI, MBB,
6083                       Subtarget.hasLoadStoreOnCond2()? SystemZ::LOCRMux : 0);
6084   case SystemZ::Select32:
6085     return emitSelect(MI, MBB, SystemZ::LOCR);
6086   case SystemZ::Select64:
6087     return emitSelect(MI, MBB, SystemZ::LOCGR);
6088   case SystemZ::SelectF32:
6089   case SystemZ::SelectF64:
6090   case SystemZ::SelectF128:
6091     return emitSelect(MI, MBB, 0);
6092 
6093   case SystemZ::CondStore8Mux:
6094     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
6095   case SystemZ::CondStore8MuxInv:
6096     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
6097   case SystemZ::CondStore16Mux:
6098     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
6099   case SystemZ::CondStore16MuxInv:
6100     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
6101   case SystemZ::CondStore32Mux:
6102     return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
6103   case SystemZ::CondStore32MuxInv:
6104     return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
6105   case SystemZ::CondStore8:
6106     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
6107   case SystemZ::CondStore8Inv:
6108     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
6109   case SystemZ::CondStore16:
6110     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
6111   case SystemZ::CondStore16Inv:
6112     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
6113   case SystemZ::CondStore32:
6114     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
6115   case SystemZ::CondStore32Inv:
6116     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
6117   case SystemZ::CondStore64:
6118     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
6119   case SystemZ::CondStore64Inv:
6120     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
6121   case SystemZ::CondStoreF32:
6122     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
6123   case SystemZ::CondStoreF32Inv:
6124     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
6125   case SystemZ::CondStoreF64:
6126     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
6127   case SystemZ::CondStoreF64Inv:
6128     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
6129 
6130   case SystemZ::AEXT128_64:
6131     return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
6132   case SystemZ::ZEXT128_32:
6133     return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
6134   case SystemZ::ZEXT128_64:
6135     return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
6136 
6137   case SystemZ::ATOMIC_SWAPW:
6138     return emitAtomicLoadBinary(MI, MBB, 0, 0);
6139   case SystemZ::ATOMIC_SWAP_32:
6140     return emitAtomicLoadBinary(MI, MBB, 0, 32);
6141   case SystemZ::ATOMIC_SWAP_64:
6142     return emitAtomicLoadBinary(MI, MBB, 0, 64);
6143 
6144   case SystemZ::ATOMIC_LOADW_AR:
6145     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
6146   case SystemZ::ATOMIC_LOADW_AFI:
6147     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
6148   case SystemZ::ATOMIC_LOAD_AR:
6149     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
6150   case SystemZ::ATOMIC_LOAD_AHI:
6151     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
6152   case SystemZ::ATOMIC_LOAD_AFI:
6153     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
6154   case SystemZ::ATOMIC_LOAD_AGR:
6155     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
6156   case SystemZ::ATOMIC_LOAD_AGHI:
6157     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
6158   case SystemZ::ATOMIC_LOAD_AGFI:
6159     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
6160 
6161   case SystemZ::ATOMIC_LOADW_SR:
6162     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
6163   case SystemZ::ATOMIC_LOAD_SR:
6164     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
6165   case SystemZ::ATOMIC_LOAD_SGR:
6166     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
6167 
6168   case SystemZ::ATOMIC_LOADW_NR:
6169     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
6170   case SystemZ::ATOMIC_LOADW_NILH:
6171     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
6172   case SystemZ::ATOMIC_LOAD_NR:
6173     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
6174   case SystemZ::ATOMIC_LOAD_NILL:
6175     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
6176   case SystemZ::ATOMIC_LOAD_NILH:
6177     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
6178   case SystemZ::ATOMIC_LOAD_NILF:
6179     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
6180   case SystemZ::ATOMIC_LOAD_NGR:
6181     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
6182   case SystemZ::ATOMIC_LOAD_NILL64:
6183     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
6184   case SystemZ::ATOMIC_LOAD_NILH64:
6185     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
6186   case SystemZ::ATOMIC_LOAD_NIHL64:
6187     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
6188   case SystemZ::ATOMIC_LOAD_NIHH64:
6189     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
6190   case SystemZ::ATOMIC_LOAD_NILF64:
6191     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
6192   case SystemZ::ATOMIC_LOAD_NIHF64:
6193     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
6194 
6195   case SystemZ::ATOMIC_LOADW_OR:
6196     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
6197   case SystemZ::ATOMIC_LOADW_OILH:
6198     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
6199   case SystemZ::ATOMIC_LOAD_OR:
6200     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
6201   case SystemZ::ATOMIC_LOAD_OILL:
6202     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
6203   case SystemZ::ATOMIC_LOAD_OILH:
6204     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
6205   case SystemZ::ATOMIC_LOAD_OILF:
6206     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
6207   case SystemZ::ATOMIC_LOAD_OGR:
6208     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
6209   case SystemZ::ATOMIC_LOAD_OILL64:
6210     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
6211   case SystemZ::ATOMIC_LOAD_OILH64:
6212     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
6213   case SystemZ::ATOMIC_LOAD_OIHL64:
6214     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
6215   case SystemZ::ATOMIC_LOAD_OIHH64:
6216     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
6217   case SystemZ::ATOMIC_LOAD_OILF64:
6218     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
6219   case SystemZ::ATOMIC_LOAD_OIHF64:
6220     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
6221 
6222   case SystemZ::ATOMIC_LOADW_XR:
6223     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
6224   case SystemZ::ATOMIC_LOADW_XILF:
6225     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
6226   case SystemZ::ATOMIC_LOAD_XR:
6227     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
6228   case SystemZ::ATOMIC_LOAD_XILF:
6229     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
6230   case SystemZ::ATOMIC_LOAD_XGR:
6231     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
6232   case SystemZ::ATOMIC_LOAD_XILF64:
6233     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
6234   case SystemZ::ATOMIC_LOAD_XIHF64:
6235     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
6236 
6237   case SystemZ::ATOMIC_LOADW_NRi:
6238     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
6239   case SystemZ::ATOMIC_LOADW_NILHi:
6240     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
6241   case SystemZ::ATOMIC_LOAD_NRi:
6242     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
6243   case SystemZ::ATOMIC_LOAD_NILLi:
6244     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
6245   case SystemZ::ATOMIC_LOAD_NILHi:
6246     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
6247   case SystemZ::ATOMIC_LOAD_NILFi:
6248     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
6249   case SystemZ::ATOMIC_LOAD_NGRi:
6250     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
6251   case SystemZ::ATOMIC_LOAD_NILL64i:
6252     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
6253   case SystemZ::ATOMIC_LOAD_NILH64i:
6254     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
6255   case SystemZ::ATOMIC_LOAD_NIHL64i:
6256     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
6257   case SystemZ::ATOMIC_LOAD_NIHH64i:
6258     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
6259   case SystemZ::ATOMIC_LOAD_NILF64i:
6260     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
6261   case SystemZ::ATOMIC_LOAD_NIHF64i:
6262     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
6263 
6264   case SystemZ::ATOMIC_LOADW_MIN:
6265     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6266                                 SystemZ::CCMASK_CMP_LE, 0);
6267   case SystemZ::ATOMIC_LOAD_MIN_32:
6268     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6269                                 SystemZ::CCMASK_CMP_LE, 32);
6270   case SystemZ::ATOMIC_LOAD_MIN_64:
6271     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
6272                                 SystemZ::CCMASK_CMP_LE, 64);
6273 
6274   case SystemZ::ATOMIC_LOADW_MAX:
6275     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6276                                 SystemZ::CCMASK_CMP_GE, 0);
6277   case SystemZ::ATOMIC_LOAD_MAX_32:
6278     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6279                                 SystemZ::CCMASK_CMP_GE, 32);
6280   case SystemZ::ATOMIC_LOAD_MAX_64:
6281     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
6282                                 SystemZ::CCMASK_CMP_GE, 64);
6283 
6284   case SystemZ::ATOMIC_LOADW_UMIN:
6285     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6286                                 SystemZ::CCMASK_CMP_LE, 0);
6287   case SystemZ::ATOMIC_LOAD_UMIN_32:
6288     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6289                                 SystemZ::CCMASK_CMP_LE, 32);
6290   case SystemZ::ATOMIC_LOAD_UMIN_64:
6291     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
6292                                 SystemZ::CCMASK_CMP_LE, 64);
6293 
6294   case SystemZ::ATOMIC_LOADW_UMAX:
6295     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6296                                 SystemZ::CCMASK_CMP_GE, 0);
6297   case SystemZ::ATOMIC_LOAD_UMAX_32:
6298     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6299                                 SystemZ::CCMASK_CMP_GE, 32);
6300   case SystemZ::ATOMIC_LOAD_UMAX_64:
6301     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
6302                                 SystemZ::CCMASK_CMP_GE, 64);
6303 
6304   case SystemZ::ATOMIC_CMP_SWAPW:
6305     return emitAtomicCmpSwapW(MI, MBB);
6306   case SystemZ::MVCSequence:
6307   case SystemZ::MVCLoop:
6308     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
6309   case SystemZ::NCSequence:
6310   case SystemZ::NCLoop:
6311     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
6312   case SystemZ::OCSequence:
6313   case SystemZ::OCLoop:
6314     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
6315   case SystemZ::XCSequence:
6316   case SystemZ::XCLoop:
6317     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
6318   case SystemZ::CLCSequence:
6319   case SystemZ::CLCLoop:
6320     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
6321   case SystemZ::CLSTLoop:
6322     return emitStringWrapper(MI, MBB, SystemZ::CLST);
6323   case SystemZ::MVSTLoop:
6324     return emitStringWrapper(MI, MBB, SystemZ::MVST);
6325   case SystemZ::SRSTLoop:
6326     return emitStringWrapper(MI, MBB, SystemZ::SRST);
6327   case SystemZ::TBEGIN:
6328     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
6329   case SystemZ::TBEGIN_nofloat:
6330     return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
6331   case SystemZ::TBEGINC:
6332     return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
6333   case SystemZ::LTEBRCompare_VecPseudo:
6334     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
6335   case SystemZ::LTDBRCompare_VecPseudo:
6336     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
6337   case SystemZ::LTXBRCompare_VecPseudo:
6338     return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
6339 
6340   default:
6341     llvm_unreachable("Unexpected instr type to insert");
6342   }
6343 }
6344