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