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