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